Search in sources :

Example 56 with SingleVariableDeclaration

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

the class JUnitCodeGenerator method createNewInstanceMethod.

@SuppressWarnings({ "rawtypes", "unchecked" })
private void createNewInstanceMethod(final TypeDeclaration td, final CompilationUnit cu, final AST ast) {
    // public static Object newInstance(final String clazzName, final Object receiver, final Object[] args, final Class[] parameterTypes) throws Exception
    // {
    // final Class<?>     clazz = Class.forName(clazzName);
    // final Constructor   c    = clazz.getDeclaredConstructor(parameterTypes);
    // c.setAccessible(true);
    // 
    // return c.newInstance(args);
    // }
    // -- add necessary import statements
    List imports = cu.imports();
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "java", "lang", "reflect", "Constructor" }));
    imports.add(id);
    // -- create method frame: "public static Object newInstance(final String clazzName, final Object[] args, Class[] paramTypes) throws Exception"
    final MethodDeclaration md = ast.newMethodDeclaration();
    td.bodyDeclarations().add(md);
    md.setName(ast.newSimpleName("newInstance"));
    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.newArrayType(ast.newSimpleType(ast.newSimpleName("Object"))));
    svd.setName(ast.newSimpleName("args"));
    parameters.add(svd);
    svd = ast.newSingleVariableDeclaration();
    svd.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("Class"))));
    svd.setName(ast.newSimpleName("paramTypes"));
    parameters.add(svd);
    md.setReturnType2(ast.newSimpleType(ast.newSimpleName("Object")));
    // -- create method body
    // final Class<?>     clazz = Class.forName(clazzName);
    // final Constructor   c    = clazz.getDeclaredConstructor(parameterTypes);
    // c.setAccessible(true);
    // 
    // return c.newInstance(args);
    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 Constructor c = clazz.getDeclaredConstructor(parameterTypes);
    init = ast.newMethodInvocation();
    init.setName(ast.newSimpleName("getDeclaredConstructor"));
    init.setExpression(ast.newSimpleName("clazz"));
    init.arguments().add(ast.newSimpleName("paramTypes"));
    varDeclFrag = ast.newVariableDeclarationFragment();
    varDeclFrag.setName(ast.newSimpleName("c"));
    varDeclFrag.setInitializer(init);
    varDeclStmt = ast.newVariableDeclarationStatement(varDeclFrag);
    varDeclStmt.setType(ast.newSimpleType(ast.newSimpleName("Constructor")));
    methodStmts.add(varDeclStmt);
    // c.setAccessible(true);
    MethodInvocation minv = ast.newMethodInvocation();
    minv.setName(ast.newSimpleName("setAccessible"));
    minv.setExpression(ast.newSimpleName("c"));
    minv.arguments().add(ast.newBooleanLiteral(true));
    methodStmts.add(ast.newExpressionStatement(minv));
    // return c.newInstance(args);
    minv = ast.newMethodInvocation();
    minv.setName(ast.newSimpleName("newInstance"));
    minv.setExpression(ast.newSimpleName("c"));
    minv.arguments().add(ast.newSimpleName("args"));
    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 57 with SingleVariableDeclaration

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

the class JUnitCodeGenerator method createTryStmtWithEmptyCatch.

/*
	 * Needed to preserve program flow: 
	 * 
	 * try
	 * {
	 *    var0.doSth();
	 * }
	 * catch(Throwable t) {}
	 */
@SuppressWarnings("unchecked")
private TryStatement createTryStmtWithEmptyCatch(final AST ast, Statement stmt) {
    final TryStatement tryStmt = ast.newTryStatement();
    tryStmt.getBody().statements().add(stmt);
    final CatchClause cc = ast.newCatchClause();
    SingleVariableDeclaration excDecl = ast.newSingleVariableDeclaration();
    excDecl.setType(ast.newSimpleType(ast.newSimpleName("Throwable")));
    excDecl.setName(ast.newSimpleName("t"));
    cc.setException(excDecl);
    tryStmt.catchClauses().add(cc);
    return tryStmt;
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause)

Example 58 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration 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 59 with SingleVariableDeclaration

use of org.eclipse.jdt.core.dom.SingleVariableDeclaration 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 60 with SingleVariableDeclaration

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

the class ASTUtil method buildMethodSignature.

public static String buildMethodSignature(MethodDeclaration method) {
    StringBuilder builder = new StringBuilder();
    builder.append(method.getName());
    builder.append('(');
    @SuppressWarnings("unchecked") List<SingleVariableDeclaration> params = method.parameters();
    for (Iterator<SingleVariableDeclaration> iter = params.iterator(); iter.hasNext(); ) {
        String paramType;
        SingleVariableDeclaration param = iter.next();
        ITypeBinding typeBinding = param.getType().resolveBinding();
        if (typeBinding != null)
            paramType = typeBinding.getBinaryName();
        else
            paramType = param.getName().getIdentifier();
        builder.append(paramType);
        if (iter.hasNext())
            builder.append(",");
    }
    builder.append(')');
    return builder.toString();
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding)

Aggregations

SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)124 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)41 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)39 Type (org.eclipse.jdt.core.dom.Type)37 Block (org.eclipse.jdt.core.dom.Block)35 ASTNode (org.eclipse.jdt.core.dom.ASTNode)33 AST (org.eclipse.jdt.core.dom.AST)32 ArrayList (java.util.ArrayList)29 List (java.util.List)27 SimpleName (org.eclipse.jdt.core.dom.SimpleName)27 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)27 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)26 Expression (org.eclipse.jdt.core.dom.Expression)22 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)20 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)18 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)18 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)17 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)16 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)16 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)16