Example usage for org.eclipse.jdt.core.dom CompilationUnit getJavaElement

List of usage examples for org.eclipse.jdt.core.dom CompilationUnit getJavaElement

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom CompilationUnit getJavaElement.

Prototype

public IJavaElement getJavaElement() 

Source Link

Document

The Java element (an org.eclipse.jdt.core.ICompilationUnit or an org.eclipse.jdt.core.IClassFile) this compilation unit was created from, or null if it was not created from a Java element.

Usage

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAUtil.java

License:Open Source License

public static void cleanUp(CompilationUnit cu, String requestName) {
    ICompilationUnit icu = (ICompilationUnit) cu.getJavaElement();
    IFile iFile = (IFile) icu.getResource();
    IProject project = iFile.getProject();
    if (project.equals(ResourcesPlugin.getWorkspace().getRoot().getProject(getPPAProjectName(requestName)))) {
        try {/*from ww w  .  ja v  a  2s . c  om*/
            PPAResourceUtil.cleanUp(iFile);
        } catch (CoreException ce) {
            logger.error("Error during file cleanup.", ce);
        } finally {
            PPAUIActivator.getDefault().releaseId(requestName);
        }
    }
}

From source file:changetypes.ASTVisitorAtomicChange.java

License:Open Source License

public boolean visit(CompilationUnit node) {
    IJavaElement thisFile = node.getJavaElement();
    for (Object abstractTypeDeclaration : node.types()) {
        if ((abstractTypeDeclaration instanceof TypeDeclaration)) {
            TypeDeclaration td = (TypeDeclaration) abstractTypeDeclaration;
            this.typeToFileMap_.put(getQualifiedName(td.resolveBinding()), thisFile);
        }/*from  w ww  .ja  va 2  s. c  o m*/
    }
    return true;
}

From source file:coloredide.astview.ASTViewContentProvider.java

License:Open Source License

private Object[] getNodeChildren(ASTNode node) {
    ArrayList res = new ArrayList();

    if (node instanceof Expression) {
        Expression expression = (Expression) node;
        ITypeBinding expressionTypeBinding = expression.resolveTypeBinding();
        res.add(createExpressionTypeBinding(node, expressionTypeBinding));

        // expressions:
        if (expression instanceof Name) {
            IBinding binding = ((Name) expression).resolveBinding();
            if (binding != expressionTypeBinding)
                res.add(createBinding(expression, binding));
        } else if (expression instanceof MethodInvocation) {
            IMethodBinding binding = ((MethodInvocation) expression).resolveMethodBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof SuperMethodInvocation) {
            IMethodBinding binding = ((SuperMethodInvocation) expression).resolveMethodBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof ClassInstanceCreation) {
            IMethodBinding binding = ((ClassInstanceCreation) expression).resolveConstructorBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof FieldAccess) {
            IVariableBinding binding = ((FieldAccess) expression).resolveFieldBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof SuperFieldAccess) {
            IVariableBinding binding = ((SuperFieldAccess) expression).resolveFieldBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof Annotation) {
            IAnnotationBinding binding = ((Annotation) expression).resolveAnnotationBinding();
            res.add(createBinding(expression, binding));
        }//from   w  ww . j  a  v a 2  s  .c om
        // Expression attributes:
        res.add(new GeneralAttribute(expression,
                "Boxing: " + expression.resolveBoxing() + "; Unboxing: " + expression.resolveUnboxing())); //$NON-NLS-1$ //$NON-NLS-2$
        res.add(new GeneralAttribute(expression, "ConstantExpressionValue", //$NON-NLS-1$
                expression.resolveConstantExpressionValue()));

        // references:
    } else if (node instanceof ConstructorInvocation) {
        IMethodBinding binding = ((ConstructorInvocation) node).resolveConstructorBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof SuperConstructorInvocation) {
        IMethodBinding binding = ((SuperConstructorInvocation) node).resolveConstructorBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MethodRef) {
        IBinding binding = ((MethodRef) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MemberRef) {
        IBinding binding = ((MemberRef) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof Type) {
        IBinding binding = ((Type) node).resolveBinding();
        res.add(createBinding(node, binding));

        // declarations:
    } else if (node instanceof AbstractTypeDeclaration) {
        IBinding binding = ((AbstractTypeDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof AnnotationTypeMemberDeclaration) {
        IBinding binding = ((AnnotationTypeMemberDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof EnumConstantDeclaration) {
        IBinding binding = ((EnumConstantDeclaration) node).resolveVariable();
        res.add(createBinding(node, binding));
        IBinding binding2 = ((EnumConstantDeclaration) node).resolveConstructorBinding();
        res.add(createBinding(node, binding2));
    } else if (node instanceof MethodDeclaration) {
        IBinding binding = ((MethodDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof VariableDeclaration) {
        IBinding binding = ((VariableDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof AnonymousClassDeclaration) {
        IBinding binding = ((AnonymousClassDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof ImportDeclaration) {
        IBinding binding = ((ImportDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof PackageDeclaration) {
        IBinding binding = ((PackageDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof TypeParameter) {
        IBinding binding = ((TypeParameter) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MemberValuePair) {
        IBinding binding = ((MemberValuePair) node).resolveMemberValuePairBinding();
        res.add(createBinding(node, binding));
    }

    List list = node.structuralPropertiesForType();
    for (int i = 0; i < list.size(); i++) {
        StructuralPropertyDescriptor curr = (StructuralPropertyDescriptor) list.get(i);
        res.add(new NodeProperty(node, curr));
    }

    if (node instanceof CompilationUnit) {
        CompilationUnit root = (CompilationUnit) node;
        res.add(new JavaElement(root, root.getJavaElement()));
        res.add(new CommentsProperty(root));
        res.add(new ProblemsProperty(root));
    }

    return res.toArray();
}

From source file:com.dforensic.plugin.manal.views.SuspectCodeEd.java

License:Open Source License

public void openJavaSourceEditor(ApiDescriptor api) {
    if (api != null) {
        CompilationUnit cu = api.getCompilatioinUnit();
        if (cu != null) {
            try {
                // According to the guide
                // http://eclipsesnippets.blogspot.kr/2008/06/programmatically-opening-editor.html
                ITextEditor editor = (ITextEditor) JavaUI.openInEditor(cu.getJavaElement());
                int line = api.getLineNumFromSoot();

                if (line > 0) {
                    IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());
                    editor.selectAndReveal(document.getLineOffset(line - 1), document.getLineLength(line - 1));
                } else {
                    System.err.println("Not valid line number. It is not positive.");
                }/*from   w  ww  .  j  a v a 2s .c  o m*/
            } catch (PartInitException | JavaModelException | BadLocationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        System.err.println("Can't open java editor. ApiDescriptor is NULL.");
    }
}

From source file:com.drgarbage.ast.ASTGraphUtil.java

License:Apache License

/**
 * Returns nodes description.//from  w ww  .j  av  a2  s.c  om
 * 
 * @param node the AST-node
 * @return description string
 */
public static String getNodeDescr(ASTNode node) {
    StringBuffer elementDescr = new StringBuffer(node.getClass().getSimpleName());
    elementDescr.append(": ");

    int nodeType = node.getNodeType();
    switch (nodeType) {
    case ASTNode.COMPILATION_UNIT:
        CompilationUnit cu = (CompilationUnit) node;
        elementDescr.append(cu.getJavaElement().getElementName());
        break;

    case ASTNode.PACKAGE_DECLARATION:
        PackageDeclaration pd = (PackageDeclaration) node;
        elementDescr.append(pd.getName());
        break;

    case ASTNode.TYPE_DECLARATION:
        TypeDeclaration td = (TypeDeclaration) node;
        appendModifiers(td.getModifiers(), elementDescr);
        elementDescr.append(" class ");
        elementDescr.append(td.getName());
        break;

    case ASTNode.METHOD_DECLARATION:
        MethodDeclaration md = (MethodDeclaration) node;
        appendModifiers(md.getModifiers(), elementDescr);
        elementDescr.append(md.getReturnType2() == null ? "" : md.getReturnType2().toString());
        elementDescr.append(' ');
        elementDescr.append(md.getName());
        elementDescr.append("()");
        break;

    case ASTNode.BLOCK:
        elementDescr.append("{...}");
        break;

    case ASTNode.IF_STATEMENT:
        IfStatement is = (IfStatement) node;
        elementDescr.append("if( ");
        elementDescr.append(is.getExpression().toString());
        elementDescr.append(")");
        break;

    case ASTNode.FOR_STATEMENT:
        ForStatement fs = (ForStatement) node;
        elementDescr.append("for (...; ");
        elementDescr.append(fs.getExpression().toString());
        elementDescr.append("; ...){...}");
        break;

    case ASTNode.WHILE_STATEMENT:
        WhileStatement ws = (WhileStatement) node;
        elementDescr.append("while ( ");
        elementDescr.append(ws.getExpression().toString());
        elementDescr.append("){...}");
        break;

    case ASTNode.DO_STATEMENT:
        DoStatement ds = (DoStatement) node;
        elementDescr.append("do {...} while (");
        elementDescr.append(ds.getExpression().toString());
        elementDescr.append(")");
        break;

    case ASTNode.LABELED_STATEMENT:
        LabeledStatement ls = (LabeledStatement) node;
        elementDescr.append(ls.getLabel().toString());
        elementDescr.append(":");
        break;

    case ASTNode.CATCH_CLAUSE:
        CatchClause cs = (CatchClause) node;
        elementDescr.append("catch (");
        elementDescr.append(cs.getException().toString());
        elementDescr.append("){...}");
        break;

    case ASTNode.SWITCH_STATEMENT:
        SwitchStatement ss = (SwitchStatement) node;
        elementDescr.append("switch (");
        elementDescr.append(ss.getExpression().toString());
        elementDescr.append("){...}");
        break;

    case ASTNode.SWITCH_CASE:
        SwitchCase sc = (SwitchCase) node;
        elementDescr.append("case ");
        elementDescr.append(sc.getExpression() == null ? "default" : sc.getExpression().toString());
        elementDescr.append(":");
        break;
    case ASTNode.JAVADOC:
    case ASTNode.BLOCK_COMMENT:
    case ASTNode.LINE_COMMENT:
    case ASTNode.TRY_STATEMENT:
        /* nothing to do */
        break;

    default:
        elementDescr.append(node.toString());
    }

    /* cut the string if it is too long */
    String str = elementDescr.toString();
    if (str.length() > 128) {
        str = str.substring(0, 128) + " ... ";
    }
    str = str.replaceAll("\n", "");
    return str;
}

From source file:com.github.parzonka.ccms.engine.CompilationUnitSorter.java

License:Open Source License

/**
 * Reorders the declarations in the given compilation unit according to the
 * specified comparator. The caller is responsible for arranging in advance
 * that the given compilation unit is a working copy, and for applying the
 * returned TextEdit afterwards.//w  ww . j av a  2 s.  c  o m
 * <p>
 * <b>Note:</b> Reordering the members within a type declaration might be
 * more than a cosmetic change and could have potentially serious
 * repercussions. Firstly, the order in which the fields of a type are
 * initialized is significant in the Java language; reordering fields and
 * initializers may result in compilation errors or change the execution
 * behavior of the code. Secondly, reordering a class's members may affect
 * how its instances are serialized. This operation should therefore be used
 * with caution and due concern for potential negative side effects.
 * </p>
 * <p>
 * The <code>compare</code> method of the given comparator is passed pairs
 * of body declarations (subclasses of <code>BodyDeclaration</code>)
 * representing body declarations at the same level. The comparator is
 * called on body declarations of nested classes, including anonymous and
 * local classes, but always at the same level. Clients need to provide a
 * comparator implementation (there is no standard comparator). The
 * <code>RELATIVE_ORDER</code> property attached to these AST nodes affords
 * the comparator a way to preserve the original relative order.
 * </p>
 * <p>
 * The body declarations passed as parameters to the comparator always carry
 * at least the following minimal signature information: <br>
 * <table border="1" width="80%" cellpadding="5">
 * <tr>
 * <td width="20%"><code>TypeDeclaration</code></td>
 * <td width="50%"><code>modifiers, isInterface, name, superclass,
 *        superInterfaces, typeParameters<br>
 *        RELATIVE_ORDER property</code></td>
 * </tr>
 * <tr>
 * <td width="20%"><code>FieldDeclaration</code></td>
 * <td width="50%"><code>modifiers, type, fragments
 *        (VariableDeclarationFragments
 *        with name only)<br>
 *        RELATIVE_ORDER property</code></td>
 * </tr>
 * <tr>
 * <td width="20%"><code>MethodDeclaration</code></td>
 * <td width="50%"><code>modifiers, isConstructor, returnType, name,
 *        typeParameters, parameters
 *        (SingleVariableDeclarations with name, type, and modifiers only),
 *        thrownExceptions<br>
 *        RELATIVE_ORDER property</code></td>
 * </tr>
 * <tr>
 * <td width="20%"><code>Initializer</code></td>
 * <td width="50%"><code>modifiers<br>
 *        RELATIVE_ORDER property</code></td>
 * </tr>
 * <tr>
 * <td width="20%"><code>AnnotationTypeDeclaration</code></td>
 * <td width="50%"><code>modifiers, name<br>
 *        RELATIVE_ORDER property</code></td>
 * </tr>
 * <tr>
 * <td width="20%"><code>AnnotationTypeMemberDeclaration</code></td>
 * <td width="50%"><code>modifiers, name, type, default<br>
 *        RELATIVE_ORDER property</code></td>
 * </tr>
 * <tr>
 * <td width="20%"><code>EnumDeclaration</code></td>
 * <td width="50%"><code>modifiers, name, superInterfaces<br>
 *        RELATIVE_ORDER property</code></td>
 * </tr>
 * <tr>
 * <td width="20%"><code>EnumConstantDeclaration</code></td>
 * <td width="50%"><code>modifiers, name, arguments<br>
 *        RELATIVE_ORDER property</code></td>
 * </tr>
 * </table>
 * </p>
 *
 * @param unit
 *            the CompilationUnit to sort
 * @param comparator
 *            the comparator capable of ordering
 *            <code>BodyDeclaration</code>s; this comparator is passed AST
 *            nodes from an AST of the specified AST level
 * @param options
 *            bitwise-or of option flags; <code>0</code> for default
 *            behavior (reserved for future growth)
 * @param group
 *            the text edit group to use when generating text edits, or
 *            <code>null</code>
 * @param monitor
 *            the progress monitor to notify, or <code>null</code> if none
 * @return a TextEdit describing the required edits to do the sort, or
 *         <code>null</code> if sorting is not required
 * @exception JavaModelException
 *                if the compilation unit could not be sorted. Reasons
 *                include:
 *                <ul>
 *                <li>The given unit was not created from a ICompilationUnit
 *                (INVALID_ELEMENT_TYPES)</li>
 *                </ul>
 * @exception IllegalArgumentException
 *                if the given compilation unit is null or if the given
 *                comparator is null, or if <code>options</code> is not one
 *                of the supported levels.
 * @see org.eclipse.jdt.core.dom.BodyDeclaration
 * @see #RELATIVE_ORDER
 * @since 3.3
 */
public static TextEdit sort(CompilationUnit unit, Comparator comparator, int options, TextEditGroup group,
        IProgressMonitor monitor) throws JavaModelException {
    if (unit == null || comparator == null) {
        throw new IllegalArgumentException();
    }
    final SortElementsOperation operation = new SortElementsOperation(AST.JLS3,
            new IJavaElement[] { unit.getJavaElement() }, null, comparator);
    return operation.calculateEdit(unit, group);
}

From source file:com.google.appengine.eclipse.core.validators.java.JavaCompilationParticipant.java

License:Open Source License

public static List<? extends CategorizedProblem> validateCompilationUnit(ASTNode ast) {
    CompilationUnit root = (CompilationUnit) ast.getRoot();
    ICompilationUnit cu = (ICompilationUnit) root.getJavaElement();

    // If the compilation unit is not on the build classpath, return an empty
    // list of problems.
    if (!cu.getJavaProject().isOnClasspath(cu)) {
        return Collections.emptyList();
    }/*from  w  ww.j  a v  a2  s.co  m*/

    List<IPath> validationExclusionPatterns = GaeProjectProperties
            .getValidationExclusionPatterns(cu.getJavaProject().getProject());
    char[][] exclusionPatterns = null;
    if (!validationExclusionPatterns.isEmpty()) {
        exclusionPatterns = new char[validationExclusionPatterns.size()][];
        for (int i = 0; i < validationExclusionPatterns.size(); ++i) {
            exclusionPatterns[i] = validationExclusionPatterns.get(i).toString().toCharArray();
        }
    }

    // Get the source root relative path, since our exclusion filter does
    // not include the project name, but the compilation unit's path does.
    IPath sourceRelativePath = cu.getPath().removeFirstSegments(1);
    if (Util.isExcluded(sourceRelativePath, null, exclusionPatterns, false)) {
        return Collections.emptyList();
    }

    List<CategorizedProblem> problems = GoogleCloudSqlChecker.check(root, cu.getJavaProject());
    problems.addAll(GaeChecker.check(root, cu.getJavaProject()));

    return problems;
}

From source file:com.google.gdt.eclipse.core.JavaASTUtils.java

License:Open Source License

/**
 * Gets the compilation unit containing a particular Java AST node.
 *//*from ww  w.  j  a v a 2  s.co  m*/
public static ICompilationUnit getCompilationUnit(ASTNode node) {
    CompilationUnit root = (CompilationUnit) node.getRoot();
    ICompilationUnit cu = (ICompilationUnit) root.getJavaElement();
    return cu;
}

From source file:com.google.gwt.eclipse.core.validators.rpc.RemoteServiceValidator.java

License:Open Source License

public ValidationResult validate(ASTNode ast) {
    // TODO: Just pass in a CompilationUnit
    assert (ast.getNodeType() == ASTNode.COMPILATION_UNIT);
    CompilationUnit compilationUnit = (CompilationUnit) ast;
    IJavaProject javaProject = compilationUnit.getJavaElement().getJavaProject();

    RemoteServiceValidationVisitor remoteServiceValidationVisitor = new RemoteServiceValidationVisitor(
            javaProject);/*from  ww w. j a v  a2  s .com*/
    ast.accept(remoteServiceValidationVisitor);
    return new ValidationResult(remoteServiceValidationVisitor.problems,
            remoteServiceValidationVisitor.dependentTypes);
}

From source file:com.siteview.mde.internal.ui.correction.java.QuickFixProcessor.java

License:Open Source License

private void handleImportNotFound(IInvocationContext context, IProblemLocation problemLocation,
        final Collection result) {
    CompilationUnit cu = context.getASTRoot();
    ASTNode selectedNode = problemLocation.getCoveringNode(cu);
    if (selectedNode != null) {
        ASTNode node = getParent(selectedNode);
        String className = null;/*from  w  ww.j ava  2  s .c  o  m*/
        String packageName = null;
        if (node == null) {
            if (selectedNode instanceof SimpleName) {
                ITypeBinding typeBinding = ((SimpleName) selectedNode).resolveTypeBinding();
                className = typeBinding.getBinaryName();
                packageName = typeBinding.getPackage().getName();
            }
        } else if (node instanceof ImportDeclaration) {
            // Find import declaration which is the problem
            className = ((ImportDeclaration) node).getName().getFullyQualifiedName();

            // always add the search repositories proposal
            int lastPeriod = className.lastIndexOf('.'); // if there is no period assume we are importing a single name package
            packageName = className.substring(0, lastPeriod >= 0 ? lastPeriod : className.length());
            result.add(JavaResolutionFactory.createSearchRepositoriesProposal(packageName));
        }

        if (className != null && packageName != null) {
            IProject project = cu.getJavaElement().getJavaProject().getProject();
            // only try to find proposals on Plug-in Projects
            if (!WorkspaceModelManager.isPluginProject(project))
                return;

            // create a collector that will create IJavaCompletionProposals and load them into 'result'
            AbstractClassResolutionCollector collector = createCollector(result);
            IRunnableWithProgress findOperation = new FindClassResolutionsOperation(project, className,
                    collector);
            try {
                findOperation.run(new NullProgressMonitor());
            } catch (InvocationTargetException e) {
            } catch (InterruptedException e) {
            }
        }
    }
}