Example usage for org.eclipse.jdt.core IJavaElement COMPILATION_UNIT

List of usage examples for org.eclipse.jdt.core IJavaElement COMPILATION_UNIT

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaElement COMPILATION_UNIT.

Prototype

int COMPILATION_UNIT

To view the source code for org.eclipse.jdt.core IJavaElement COMPILATION_UNIT.

Click Source Link

Document

Constant representing a Java compilation unit.

Usage

From source file:org.apache.felix.sigil.ui.eclipse.ui.util.ResourcesDialogHelper.java

License:Apache License

public static BackgroundLoadingSelectionDialog<String> createClassSelectDialog(Shell shell, String title,
        final ISigilProjectModel project, String selected, final String ifaceOrParentClass) {
    final BackgroundLoadingSelectionDialog<String> dialog = new BackgroundLoadingSelectionDialog<String>(shell,
            "Class Name", true);

    IJobRunnable job = new IJobRunnable() {
        public IStatus run(IProgressMonitor monitor) {
            try {
                for (IJavaElement e : JavaHelper.findTypes(project.getJavaModel(),
                        IJavaElement.PACKAGE_FRAGMENT_ROOT)) {
                    IPackageFragmentRoot root = (IPackageFragmentRoot) e;
                    if (project.isInBundleClasspath(root)) {
                        for (IJavaElement e1 : JavaHelper.findTypes(root, IJavaElement.COMPILATION_UNIT,
                                IJavaElement.CLASS_FILE)) {
                            ITypeRoot typeRoot = (ITypeRoot) e1;
                            IType type = (IType) JavaHelper.findType(typeRoot, IJavaElement.TYPE);
                            if (JavaHelper.isAssignableTo(ifaceOrParentClass, type)) {
                                dialog.addElement(type.getFullyQualifiedName());
                            }//from w w  w.java  2  s .c o  m
                        }
                    }
                }

                return Status.OK_STATUS;
            } catch (JavaModelException e) {
                return e.getStatus();
            }
        }

    };

    dialog.addBackgroundJob("Scanning for activators in project", job);

    return dialog;
}

From source file:org.apache.tapestrytools.ui.internal.wizards.NewTapestryComponentPage.java

License:Open Source License

private IPackageFragment getSelectedPackageFragment() {
    IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    if (window == null)
        return null;
    ISelection selection = window.getSelectionService().getSelection();
    if (selection == null)
        return null;
    IJavaElement element = getInitialJavaElement(selection);
    if (element != null) {
        if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
            return (IPackageFragment) element;
        } else if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
            IJavaElement parent = ((ICompilationUnit) element).getParent();
            if (parent.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
                return (IPackageFragment) parent;
            }/*from w w w.j a va2  s .c om*/
        } else if (element.getElementType() == IJavaElement.TYPE) {
            return ((IType) element).getPackageFragment();
        }
    }
    return null;
}

From source file:org.codecover.eclipse.utils.EclipseMASTLinkage.java

License:Open Source License

/**
 * Find the corresponding CodeCover MAST HierarchyLevel to the given
 * Eclipse Java Element./*from  w ww  .ja  v  a  2 s.  co m*/
 * 
 * @param code
 *   root of code (MAST) to search
 * @param element
 *   search key
 * @return
 *   the HierarchyLevel of <i>element</i>, null if not found
 */
public static HierarchyLevel findSource(HierarchyLevel code, IJavaElement element) {
    HierarchyLevel result = null; //null until element is found

    /* check input */
    if (code == null) {
        throw new IllegalArgumentException("code is null"); //$NON-NLS-1$
    }
    if (element == null) {
        throw new IllegalArgumentException("element is null"); //$NON-NLS-1$
    }

    /* get corresponding ICompilationUnit */
    ICompilationUnit compilationUnit;
    if (element.getElementType() == IJavaElement.COMPILATION_UNIT) {
        compilationUnit = (ICompilationUnit) element;
    } else {
        compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
    }

    if (compilationUnit != null) {

        /* Extract fully qualified class name with its package */
        String fileName = compilationUnit.getElementName();
        String className = fileName.split("\\.")[0]; //$NON-NLS-1$
        IPackageFragment pkgF = (IPackageFragment) compilationUnit.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
        if (pkgF != null) {
            String path[];
            if (pkgF.getElementName().equals("")) { //$NON-NLS-1$
                path = new String[] { className };
            } else {
                className = pkgF.getElementName() + "." + className; //$NON-NLS-1$
                path = className.split("\\."); //$NON-NLS-1$
            }

            /* find HierarchyLevel for the class by name */
            HierarchyLevel current = code;
            boolean found = true;

            for (int i = 0; i < path.length && found; ++i) {
                found = false;

                /* find next HierarchyLevel in path */
                for (HierarchyLevel l : current.getChildren()) {
                    if (l.getName().equals(path[i])) {
                        current = l;
                        found = true;
                        break;
                    }
                }
            }
            if (found) {

                /* the whole path was successfully traversed */
                result = current;
            }
        }
    }

    return result;
}

From source file:org.codehaus.groovy.eclipse.astviews.ASTView.java

License:Apache License

private void hookGroovy() {
    partListener = new IPartListener() {
        public void partActivated(IWorkbenchPart part) {
        }//from ww w  .  ja  va2 s . c o m

        public void partBroughtToTop(IWorkbenchPart part) {
            try {
                if (part instanceof IEditorPart) {
                    IFile file = (IFile) ((IEditorPart) part).getEditorInput().getAdapter(IFile.class);
                    if (file != null && ContentTypeUtils.isGroovyLikeFileName(file.getName())) {
                        ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
                        if (unit instanceof GroovyCompilationUnit) {
                            if (editor != part) {
                                editor = (IEditorPart) part;
                                Object[] treePaths = viewer.getExpandedElements();
                                viewer.setInput(((GroovyCompilationUnit) unit).getModuleNode());
                                viewer.setExpandedElements(treePaths);
                            } else {
                                // nothing to do!
                            }
                            return;
                        }
                    }
                }
            } catch (Exception e) {
                GroovyCore.logException("Error updating AST Viewer", e); //$NON-NLS-1$
            }
            editor = null;
            // This is a guard - the content provider should not be null,
            // but sometimes this happens when the
            // part is disposed of for various reasons (unhandled exceptions
            // AFAIK). Without this guard,
            // error message popups continue until Eclipse if forcefully
            // killed.
            if (viewer.getContentProvider() != null) {
                viewer.setInput(null);
            }
        }

        public void partClosed(IWorkbenchPart part) {
        }

        public void partDeactivated(IWorkbenchPart part) {
        }

        public void partOpened(IWorkbenchPart part) {
        }
    };
    getSite().getPage().addPartListener(partListener);

    // Warm the listener up.
    if (getSite().getPage().getActiveEditor() instanceof GroovyEditor) {
        partListener.partBroughtToTop(getSite().getPage().getActiveEditor());
    }

    listener = new IElementChangedListener() {

        public void elementChanged(ElementChangedEvent event) {
            // The editor is currently not a GroovyEditor, so
            // there is not
            // ASTView to refresh.
            if (editor == null) {
                return;
            }
            IJavaElementDelta delta = event.getDelta();

            IFile file = (IFile) editor.getEditorInput().getAdapter(IFile.class);

            final GroovyCompilationUnit unit = (GroovyCompilationUnit) JavaCore.createCompilationUnitFrom(file);

            // determine if the delta contains the ICompUnit under question
            if (isUnitInDelta(delta, unit)) {
                Display.getDefault().asyncExec(new Runnable() {
                    public void run() {
                        Object[] treePaths = viewer.getExpandedElements();
                        viewer.setInput(unit.getModuleNode());
                        viewer.setExpandedElements(treePaths);
                    }
                });
            }
        }

        private boolean isUnitInDelta(IJavaElementDelta delta, GroovyCompilationUnit unit) {

            IJavaElement elt = delta.getElement();
            if (elt.getElementType() == IJavaElement.COMPILATION_UNIT) {
                // comparing with a compilation unit
                // if test fails, no need to go further
                if (elt.getElementName().equals(unit.getElementName())) {
                    return true;
                } else {
                    return false;
                }
            }

            ICompilationUnit candidateUnit = (ICompilationUnit) elt.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (candidateUnit != null) {
                // now if test fails, no need to go further
                if (candidateUnit.getElementName().equals(unit.getElementName())) {
                    return true;
                } else {
                    return false;
                }
            }

            // delta is a potential ancestor of this compilationUnit
            IJavaElementDelta[] deltas = delta.getAffectedChildren();
            if (deltas != null) {
                for (IJavaElementDelta delta2 : deltas) {
                    if (isUnitInDelta(delta2, unit)) {
                        return true;
                    }
                }
            }
            return false;
        }
    };

    JavaCore.addElementChangedListener(listener, ElementChangedEvent.POST_RECONCILE);

}

From source file:org.codehaus.groovy.eclipse.editor.outline.OMethod.java

License:Apache License

public GroovyCompilationUnit getUnit() {
    ICompilationUnit unit = (ICompilationUnit) getAncestor(IJavaElement.COMPILATION_UNIT);
    if (unit instanceof GroovyCompilationUnit) {
        return (GroovyCompilationUnit) unit;
    } else {/*  w w  w . j  a  v a2 s  . c o  m*/
        Assert.isTrue(false, "Expecting GroovyCompilationUnit, but found " + unit);
        return null; // won't get here
    }
}

From source file:org.codehaus.groovy.eclipse.refactoring.core.extract.ExtractGroovyMethodRefactoring.java

License:Apache License

private RefactoringStatus initialize(JavaRefactoringArguments arguments) {
    final String selection = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION);
    if (selection == null) {
        return RefactoringStatus.createFatalErrorStatus(
                Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
                        JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION));
    }// w  ww . j  a  v a  2s. c  o m

    int offset = -1;
    int length = -1;
    final StringTokenizer tokenizer = new StringTokenizer(selection);
    if (tokenizer.hasMoreTokens())
        offset = Integer.valueOf(tokenizer.nextToken()).intValue();
    if (tokenizer.hasMoreTokens())
        length = Integer.valueOf(tokenizer.nextToken()).intValue();
    if (offset < 0 || length < 0)
        return RefactoringStatus.createFatalErrorStatus(
                Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
                        new Object[] { selection, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION }));
    selectedText = new Region(offset, length);

    final String handle = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
    if (handle == null)
        return RefactoringStatus.createFatalErrorStatus(
                Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
                        JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));

    IJavaElement element = JavaRefactoringDescriptorUtil.handleToElement(arguments.getProject(), handle, false);
    if (element == null || !element.exists() || element.getElementType() != IJavaElement.COMPILATION_UNIT
            || !(element instanceof GroovyCompilationUnit))
        return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getName(),
                IJavaRefactorings.EXTRACT_METHOD);
    unit = (GroovyCompilationUnit) element;

    final String name = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME);
    if (name == null || name.length() == 0)
        return RefactoringStatus.createFatalErrorStatus(
                Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
                        JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME));
    newMethodName = name;

    return new RefactoringStatus();
}

From source file:org.codehaus.groovy.eclipse.refactoring.core.rename.renameLocal.GroovyRenameLocalVariableProcessor.java

License:Apache License

/**
 * @param localVariable/*  ww w . j a  v  a  2s  .  c  o m*/
 * @param newName
 * @param status
 */
private void initialize(ILocalVariable localVariable, String newName, RefactoringStatus status) {
    this.localVariable = localVariable;
    ICompilationUnit unit = (ICompilationUnit) localVariable.getAncestor(IJavaElement.COMPILATION_UNIT);
    if (unit instanceof GroovyCompilationUnit) {
        this.unit = (GroovyCompilationUnit) unit;
    } else {
        status.merge(RefactoringStatus.createErrorStatus(
                "Expecting a Groovy compilation unit, but instead found " + unit.getElementName()));
    }
    if (newName != null && newName.length() > 0) {
        if (newName.equals(localVariable.getElementName())) {
            status.merge(RefactoringStatus.createErrorStatus("New name is the same as the old name"));
        }
        setNewElementName(newName);
    } else {
        status.merge(RefactoringStatus.createErrorStatus("Invalid new name"));
    }
}

From source file:org.codehaus.groovy.eclipse.refactoring.test.rename.RenameTypeTests.java

License:Open Source License

private void checkMappers(Refactoring refactoring, IType type, String newCUName,
        IJavaElement[] someClassMembers) {
    RenameTypeProcessor rtp = (RenameTypeProcessor) ((RenameRefactoring) refactoring).getProcessor();

    ICompilationUnit newUnit = (ICompilationUnit) rtp.getRefactoredJavaElement(type.getCompilationUnit());
    assertTrue(newUnit.exists());//ww w . j  av a  2  s  .  c  om
    assertTrue(newUnit.getElementName().equals(newCUName));

    IFile newFile = (IFile) rtp.getRefactoredResource(type.getResource());
    assertTrue(newFile.exists());
    assertTrue(newFile.getName().equals(newCUName));

    if ((type.getParent().getElementType() == IJavaElement.COMPILATION_UNIT)
            && type.getCompilationUnit().getElementName().equals(type.getElementName() + ".groovy")) {
        assertFalse(type.getCompilationUnit().exists());
        assertFalse(type.getResource().exists());
    }

    IPackageFragment oldPackage = (IPackageFragment) type.getCompilationUnit().getParent();
    IPackageFragment newPackage = (IPackageFragment) rtp.getRefactoredJavaElement(oldPackage);
    assertEquals(oldPackage, newPackage);

    for (int i = 0; i < someClassMembers.length; i++) {
        IMember member = (IMember) someClassMembers[i];
        IJavaElement refactoredMember = rtp.getRefactoredJavaElement(member);
        if (member instanceof IMethod && member.getElementName().equals(type.getElementName()))
            continue; // constructor
        assertTrue(refactoredMember.exists());
        assertEquals(member.getElementName(), refactoredMember.getElementName());
        assertFalse(refactoredMember.equals(member));
    }
}

From source file:org.codehaus.jdt.groovy.model.GroovyClassFileWorkingCopy.java

License:Open Source License

/**
 * Translates from the source element of this synthetic compilation unit into a binary element of the underlying classfile.
 * //www  .j  a v  a2  s.com
 * @param source the source element to translate
 * @return the same element, but in binary form, or closest possible match if this element doesn't exist
 */
public IJavaElement convertToBinary(IJavaElement source) {
    if (source.isReadOnly()) {
        // already binary
        return source;
    }
    if (source.getElementType() == IJavaElement.COMPILATION_UNIT) {
        return classFile;
    }
    if (!(source instanceof IMember)) {
        return classFile;
    }

    // get ancestors to type root
    List<IJavaElement> srcAncestors = new ArrayList<IJavaElement>(3);
    IJavaElement srcCandidate = source;
    while (srcCandidate != null && srcCandidate != this) {
        srcAncestors.add(srcCandidate);
        srcCandidate = srcCandidate.getParent();
    }

    // now, traverse the classFile using the ancestor list in reverse order
    IJavaElement binCandidate = classFile;
    try {
        while (srcAncestors.size() > 0) {
            srcCandidate = srcAncestors.remove(srcAncestors.size() - 1);
            if (!(srcCandidate instanceof IParent)) {
                break;
            }

            String candidateName = srcCandidate.getElementName();
            IJavaElement[] binChildren = ((IParent) binCandidate).getChildren();
            boolean found = false;
            for (IJavaElement binChild : binChildren) {
                if (binChild.getElementName().equals(candidateName) ||
                // check for implicit closure class
                        (binChild.getElementType() == IJavaElement.TYPE && binChild.getParent().getElementName()
                                .equals(candidateName + '$' + binChild.getElementName() + ".class"))) {
                    binCandidate = binChild;
                    found = true;
                    break;
                }
            }
            if (!found) {
                break;
            }
        }
    } catch (JavaModelException e) {
        Util.log(e);
    }

    return binCandidate;
}

From source file:org.dawnsci.common.widgets.breadcrumb.ResourceToItemsMapper.java

License:Open Source License

/**
 * Method that decides which elements can have error markers
 * Returns null if an element can not have error markers.
 * @param element The input element//from  w  w w .  j ava  2s.  c o  m
 * @return Returns the corresponding resource or null
 */
private static IResource getCorrespondingResource(Object element) {
    if (element instanceof IJavaElement) {
        IJavaElement elem = (IJavaElement) element;
        IResource res = elem.getResource();
        if (res == null) {
            ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null) {
                // elements in compilation units are mapped to the underlying resource of the original cu
                res = cu.getResource();
            }
        }
        return res;
    } else if (element instanceof IResource) {
        return (IResource) element;
    }
    return null;
}