Search in sources :

Example 51 with ImportDeclaration

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

the class ResolutionMarkerEvoIgnoreForMethod method run.

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();
    try {
        ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res);
        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);
        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        if (position == 1) {
            int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
            position = compunit.getPosition(line, 0);
        }
        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);
        IJavaElement element = icomp.getElementAt(position);
        IJavaElement method = getMethod(element);
        // TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        MethodDeclaration md = td.getMethods()[0];
        int counter = 1;
        while (!md.getName().getFullyQualifiedName().equals(method.getElementName()) && counter < td.getMethods().length) {
            md = td.getMethods()[counter];
            System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName());
            counter++;
        }
        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(md.getParent(), TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
        ListRewrite lr2 = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);
        // lr.insertFirst(annotation, null);
        lr.insertBefore(annotation, md, null);
        lr2.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 : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) 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) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) 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) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) IResource(org.eclipse.core.resources.IResource) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 52 with ImportDeclaration

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

the class ResolutionMarkerTryBlock method run.

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();
    try {
        String markerMessage = (String) marker.getAttribute(IMarker.MESSAGE);
        String exception = markerMessage.split(" ")[0];
        String[] exceptionPackageArray = exception.split("\\.");
        String exceptionPackage = "";
        for (int i = 0; i < exceptionPackageArray.length - 1; i++) {
            exceptionPackage += exceptionPackageArray[i] + ".";
        }
        exception = exception.substring(exceptionPackage.length());
        System.out.println("Package: " + exceptionPackage + ", Exception: " + exception);
        ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res);
        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);
        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
        if (position == 1) {
            position = compunit.getPosition(line, 0);
        }
        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);
        IJavaElement element = icomp.getElementAt(position);
        IJavaElement method = getMethod(element);
        // TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        MethodDeclaration md = td.getMethods()[0];
        int counter = 1;
        while (!md.getName().getFullyQualifiedName().equals(method.getElementName()) && counter < td.getMethods().length) {
            md = td.getMethods()[counter];
            System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName());
            counter++;
        }
        Block block = md.getBody();
        ListRewrite lr = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName(exceptionPackage + exception));
        ListRewrite lrClass = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);
        lrClass.insertAt(id, 0, null);
        ASTNode currentNode = null;
        List<ASTNode> list = new ArrayList<ASTNode>();
        for (Object o : lr.getOriginalList()) {
            if (o instanceof ASTNode) {
                list.add((ASTNode) o);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            ASTNode node = list.get(i);
            int nodeLine = compunit.getLineNumber(node.getStartPosition());
            System.out.println(line + " " + nodeLine);
            if (line == nodeLine) {
                currentNode = node;
                break;
            }
            List childrenList = node.structuralPropertiesForType();
            for (int j = 0; j < childrenList.size(); j++) {
                StructuralPropertyDescriptor curr = (StructuralPropertyDescriptor) childrenList.get(j);
                Object child = node.getStructuralProperty(curr);
                if (child instanceof List) {
                    for (Object ob : (List) child) {
                        if (ob instanceof ASTNode) {
                            list.add((ASTNode) ob);
                        }
                    }
                } else if (child instanceof ASTNode) {
                    list.add((ASTNode) child);
                }
            }
        }
        TryStatement ts = ast.newTryStatement();
        Statement emptyStatement = (Statement) rewriter.createStringPlaceholder("\n", ASTNode.EMPTY_STATEMENT);
        Statement emptyStatement2 = (Statement) rewriter.createStringPlaceholder("\n\t", ASTNode.EMPTY_STATEMENT);
        Block b2 = ast.newBlock();
        b2.statements().add(0, ASTNode.copySubtree(b2.getAST(), currentNode));
        b2.statements().add(1, emptyStatement);
        b2.statements().add(0, emptyStatement2);
        ts.setBody(b2);
        CatchClause cc = ast.newCatchClause();
        SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
        svd.setName(ast.newSimpleName("e"));
        Type type = ast.newSimpleType(ast.newName(exception));
        svd.setType(type);
        cc.setException(svd);
        Block b3 = ast.newBlock();
        Statement printStatement = (Statement) rewriter.createStringPlaceholder("e.printStackTrace();", ASTNode.EMPTY_STATEMENT);
        b3.statements().add(0, printStatement);
        cc.setBody(b3);
        ListRewrite parentList = rewriter.getListRewrite(currentNode.getParent(), Block.STATEMENTS_PROPERTY);
        parentList.replace(currentNode, ts, null);
        parentList.insertAfter(cc, ts, 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)
        }
        marker.delete();
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ArrayList(java.util.ArrayList) List(java.util.List) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) AST(org.eclipse.jdt.core.dom.AST) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) TryStatement(org.eclipse.jdt.core.dom.TryStatement) Statement(org.eclipse.jdt.core.dom.Statement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) CatchClause(org.eclipse.jdt.core.dom.CatchClause) IOException(java.io.IOException) Type(org.eclipse.jdt.core.dom.Type) 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) Block(org.eclipse.jdt.core.dom.Block) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) IResource(org.eclipse.core.resources.IResource) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 53 with ImportDeclaration

use of org.eclipse.jdt.core.dom.ImportDeclaration in project sts4 by spring-projects.

the class ImportRewrite method create.

/**
 * Creates an {@link ImportRewrite} from an AST ({@link CompilationUnit}). The AST has to be created from an
 * {@link ICompilationUnit}, that means {@link ASTParser#setSource(ICompilationUnit)} has been used when creating the
 * AST. If <code>restoreExistingImports</code> is <code>true</code>, all existing imports are kept, and new imports
 * will be inserted at best matching locations. If <code>restoreExistingImports</code> is <code>false</code>, the
 * existing imports will be removed and only the newly added imports will be created.
 * <p>
 * Note that this method is more efficient than using {@link #create(ICompilationUnit, boolean)} if an AST is already available.
 * </p>
 * @param astRoot the AST root node to create the imports for
 * @param restoreExistingImports specifies if the existing imports should be kept or removed.
 * @return the created import rewriter.
 * @throws IllegalArgumentException thrown when the passed AST is null or was not created from a compilation unit.
 */
public static ImportRewrite create(CompilationUnit astRoot, boolean restoreExistingImports) {
    if (astRoot == null) {
        // $NON-NLS-1$
        throw new IllegalArgumentException("AST must not be null");
    }
    List existingImport = null;
    if (restoreExistingImports) {
        existingImport = new ArrayList();
        List imports = astRoot.imports();
        for (int i = 0; i < imports.size(); i++) {
            ImportDeclaration curr = (ImportDeclaration) imports.get(i);
            StringBuffer buf = new StringBuffer();
            buf.append(curr.isStatic() ? STATIC_PREFIX : NORMAL_PREFIX).append(curr.getName().getFullyQualifiedName());
            if (curr.isOnDemand()) {
                if (buf.length() > 1)
                    buf.append('.');
                buf.append('*');
            }
            existingImport.add(buf.toString());
        }
    }
    return new ImportRewrite(astRoot, existingImport);
}
Also used : ArrayList(java.util.ArrayList) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ArrayList(java.util.ArrayList) List(java.util.List)

Example 54 with ImportDeclaration

use of org.eclipse.jdt.core.dom.ImportDeclaration in project sts4 by spring-projects.

the class ImportRewrite method getAddedImportsInsertLocation.

/**
 * Reads the positions of each existing import declaration along with any associated comments,
 * and returns these in a list whose iteration order reflects the existing order of the imports
 * in the compilation unit.
 */
private int getAddedImportsInsertLocation() {
    List<ImportDeclaration> importDeclarations = astRoot.imports();
    if (importDeclarations == null) {
        importDeclarations = Collections.emptyList();
    }
    List<Comment> comments = astRoot.getCommentList();
    int currentCommentIndex = 0;
    // Skip over package and file header comments (see https://bugs.eclipse.org/121428).
    ImportDeclaration firstImport = importDeclarations.get(0);
    PackageDeclaration packageDeclaration = astRoot.getPackage();
    int firstImportStartPosition = packageDeclaration == null ? firstImport.getStartPosition() : astRoot.getExtendedStartPosition(packageDeclaration) + astRoot.getExtendedLength(packageDeclaration);
    while (currentCommentIndex < comments.size() && comments.get(currentCommentIndex).getStartPosition() < firstImportStartPosition) {
        currentCommentIndex++;
    }
    int previousExtendedEndPosition = -1;
    for (ImportDeclaration currentImport : importDeclarations) {
        int extendedEndPosition = astRoot.getExtendedStartPosition(currentImport) + astRoot.getExtendedLength(currentImport);
        int commentAfterImportIndex = currentCommentIndex;
        while (commentAfterImportIndex < comments.size() && comments.get(commentAfterImportIndex).getStartPosition() < extendedEndPosition) {
            commentAfterImportIndex++;
        }
        currentCommentIndex = commentAfterImportIndex;
        previousExtendedEndPosition = extendedEndPosition;
    }
    return previousExtendedEndPosition;
}
Also used : Comment(org.eclipse.jdt.core.dom.Comment) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration)

Example 55 with ImportDeclaration

use of org.eclipse.jdt.core.dom.ImportDeclaration in project jbosstools-hibernate by jbosstools.

the class ProcessEntityInfo method addImport.

public boolean addImport(CompilationUnit node, String importDeclaration) {
    // $NON-NLS-1$
    String[] importDeclarations = importDeclaration.split("\\.");
    if (importDeclarations.length <= 1) {
        return false;
    }
    ImportDeclaration importDecl = rewriter.getAST().newImportDeclaration();
    SimpleName simpleName0 = rewriter.getAST().newSimpleName(importDeclarations[0]);
    SimpleName simpleName1 = rewriter.getAST().newSimpleName(importDeclarations[1]);
    QualifiedName qualifiedName0 = rewriter.getAST().newQualifiedName(simpleName0, simpleName1);
    for (int i = 2; i < importDeclarations.length; i++) {
        SimpleName simpleNameI = rewriter.getAST().newSimpleName(importDeclarations[i]);
        qualifiedName0 = rewriter.getAST().newQualifiedName(qualifiedName0, simpleNameI);
    }
    importDecl.setName(qualifiedName0);
    ListRewrite lrw = rewriter.getListRewrite(node, CompilationUnit.IMPORTS_PROPERTY);
    // insert import declaration in the proper place
    // prefer alphabetic order and package separation
    Iterator<?> it = lrw.getRewrittenList().iterator();
    ASTNode insertBeforeNode = null;
    for (; it.hasNext(); ) {
        Object obj = it.next();
        if (!(obj instanceof ImportDeclaration)) {
            continue;
        }
        ImportDeclaration id = (ImportDeclaration) obj;
        String idName = id.getName().getFullyQualifiedName();
        if (idName.compareTo(importDeclaration) > 0) {
            insertBeforeNode = id;
            break;
        }
    }
    if (insertBeforeNode == null) {
        lrw.insertLast(importDecl, null);
    } else {
        lrw.insertBefore(importDecl, insertBeforeNode, null);
    }
    return true;
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite)

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