Example usage for org.eclipse.jdt.core ITypeRoot getElementAt

List of usage examples for org.eclipse.jdt.core ITypeRoot getElementAt

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ITypeRoot getElementAt.

Prototype

IJavaElement getElementAt(int position) throws JavaModelException;

Source Link

Document

Returns the smallest element within this Java type root that includes the given source position (that is, a method, field, etc.), or null if there is no element other than the Java type root itself at the given position, or if the given position is not within the source range of the source of this Java type root.

Usage

From source file:ca.uvic.chisel.diver.mylyn.logger.logging.PageSelectionListener.java

License:Open Source License

/**
 * @param selection//from w  w w.  j a  v  a  2 s . com
 * @return
 */
private Object getSelectionObject(IWorkbenchPart part, ISelection selection) {
    if (selection instanceof IStructuredSelection) {
        IStructuredSelection ss = (IStructuredSelection) selection;
        if (!ss.isEmpty()) {
            Object o = ss.getFirstElement();
            if (o instanceof IJavaElement) {
                return o;
            } else if (o instanceof ITraceModel) {
                return o;
            }
        }
    } else if (selection instanceof ITextSelection) {
        ITextSelection ts = (ITextSelection) selection;
        if (part instanceof ITextEditor) {
            ITextEditor editor = (ITextEditor) part;
            ITypeRoot typeRoot = null;
            IEditorInput input = editor.getEditorInput();
            //using internal stuff, but I don't care
            if (input instanceof IClassFileEditorInput) {
                typeRoot = ((IClassFileEditorInput) input).getClassFile();
            } else if (input instanceof IFileEditorInput) {
                IFile file = ((IFileEditorInput) input).getFile();
                IJavaElement element = JavaCore.create(file);
                if (element instanceof ITypeRoot) {
                    typeRoot = (ITypeRoot) element;
                }
            }
            if (typeRoot != null) {
                IType type = typeRoot.findPrimaryType();
                if (type != null) {
                    try {
                        IJavaElement je = typeRoot.getElementAt(ts.getOffset());
                        return je;
                    } catch (JavaModelException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return null;
}

From source file:de.akra.idocit.java.ui.JavaEditorSelectionListener.java

License:Apache License

/**
 * Always it is done a selection within a JavaEditor (mouse click or moving curser by
 * keys) it is tried to find out out the selected JavaMethod. If a JavaMethod were
 * found, the RecommendedGridsView of iDocIt! is updated with the method's properties.
 * /* ww  w .j av a 2 s  . co m*/
 * @param part
 *            [OBJECT] The selected editor.
 * @param selection
 *            [ATTRIBUTE]
 */
@Override
public void selectionChanged(final IWorkbenchPart part, final ISelection selection) {
    if (part instanceof JavaEditor) {
        final JavaEditor javaEditor = (JavaEditor) part;
        final ITypeRoot root = EditorUtility.getEditorInputJavaElement(javaEditor, false);

        final ISelection sel = javaEditor.getSelectionProvider().getSelection();

        if (sel instanceof ITextSelection) {
            // get iDocIt! view for active window
            final IViewPart findView = part.getSite().getPage().findView(RecommendedGridsView.ID);
            if (findView != null && findView instanceof RecommendedGridsView) {
                final RecommendedGridsView view = (RecommendedGridsView) findView;
                final ITextSelection textSel = (ITextSelection) sel;
                RecommendedGridsViewSelection newViewSelection = null;
                try {
                    final IJavaElement elt = root.getElementAt(textSel.getOffset());
                    if (elt != null && elt.getElementType() == IJavaElement.METHOD) {
                        newViewSelection = prepareViewSelection((IMethod) elt);
                    }
                } catch (final JavaModelException e) {
                    LOG.log(Level.WARNING, "Java method not found for \"{0}\" (file offset={1}).",
                            new Object[] { textSel.getText(), textSel.getOffset() });
                } catch (final Exception e) {
                    LOG.log(Level.WARNING, "Failed to collect assigned ThematicRoles.", e);
                }
                view.setSelection(newViewSelection);
            } else {
                LOG.log(Level.WARNING, "RecommendedGridsView not found: " + String.valueOf(findView));
            }
        }
    }
}

From source file:org.eclipse.ajdt.core.model.AJProjectModelFacade.java

License:Open Source License

/**
 * Find the java element corresponding to the handle.  We know that it exists in 
 * as a class file in a binary folder, but it may actually be
 * a source file in a different project//from ww w  .j  ava  2 s . c o m
 */
private IJavaElement findElementInBinaryFolder(HandleInfo handleInfo, IClassFile classFile)
        throws JavaModelException {
    IJavaElement candidate = classFile;
    // we have a class file that is not in a jar.
    // can we find this as a source file in some project?
    IPath path = classFile.getPath();
    IJavaProject otherProject = JavaCore.create(project).getJavaModel().getJavaProject(path.segment(0));
    ITypeRoot typeRoot = classFile;
    if (otherProject.exists()) {
        IType type = otherProject.findType(handleInfo.sourceTypeQualName());
        typeRoot = type.getTypeRoot();
        if (typeRoot instanceof ICompilationUnit) {
            AJCompilationUnit newUnit = CompilationUnitTools
                    .convertToAJCompilationUnit((ICompilationUnit) typeRoot);
            typeRoot = newUnit != null ? newUnit : typeRoot;
        }
    }

    if (handleInfo.isType) {
        switch (typeRoot.getElementType()) {
        case IJavaElement.CLASS_FILE:
            candidate = ((IClassFile) typeRoot).getType();
            break;
        case IJavaElement.COMPILATION_UNIT:
            candidate = CompilationUnitTools.findType((ICompilationUnit) typeRoot,
                    classFile.getType().getElementName(), true);
            break;

        default:
            // shouldn't happen
            break;
        }
    } else if (!handleInfo.isFile && !handleInfo.isType) {
        // program element will exist only if coming from aspect path
        IProgramElement ipe = getProgramElement(handleInfo.origAJHandle);
        if (ipe != IHierarchy.NO_STRUCTURE) {
            candidate = typeRoot.getElementAt(offsetFromLine(typeRoot, ipe.getSourceLocation()));
        } else {
            String newHandle = typeRoot.getHandleIdentifier() + handleInfo.restHandle;
            candidate = AspectJCore.create(newHandle);
        }
    }
    return candidate;
}

From source file:org.eclipse.mylyn.internal.java.ui.editor.BreakpointListener.java

License:Open Source License

public void modelChanged(AnnotationModelEvent event) {
    if (!ContextCore.getContextManager().isContextActive()) {
        return;/*from w  ww.j a v a 2 s  . c o m*/
    }
    IInteractionContext context = ContextCore.getContextManager().getActiveContext();
    if (context == null) {
        return;
    }
    for (Annotation a : event.getAddedAnnotations()) {
        if (a.getType().equals("org.eclipse.debug.core.breakpoint")) { //$NON-NLS-1$
            try {
                ITypeRoot root = EditorUtility.getEditorInputJavaElement(editor, true);
                Position position = model.getPosition(a);
                IJavaElement element = root.getElementAt(position.offset);

                final AbstractContextStructureBridge bridge = ContextCore.getStructureBridge(element);
                final String handleIdentifier = bridge.getHandleIdentifier(element);
                if (handleIdentifier != null) {
                    PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
                        public void run() {
                            ContextCore.getContextManager()
                                    .processInteractionEvent(new InteractionEvent(
                                            InteractionEvent.Kind.SELECTION, bridge.getContentType(),
                                            handleIdentifier, editor.getSite().getId()));
                        }
                    });
                }
            } catch (JavaModelException e) {
                StatusHandler.log(new Status(IStatus.ERROR, JavaUiBridgePlugin.ID_PLUGIN, e.getMessage(), e));
            }
        }
    }
}

From source file:org.eclipse.objectteams.otdt.debug.ui.internal.actions.OTToggleBreakpointAdapter.java

License:Open Source License

/**
 * Returns a selection of the member in the given text selection, or the
 * original selection if none./*from   w  w w .  j  a v  a  2 s  . co m*/
 * 
 * @param part
 * @param selection
 * @return a structured selection of the member in the given text selection,
 *         or the original selection if none
 * @exception CoreException
 *                if an exception occurs
 */
protected ISelection translateToMembers(IWorkbenchPart part, ISelection selection) throws CoreException {
    ITextEditor textEditor = getTextEditor(part);
    if (textEditor != null && selection instanceof ITextSelection) {
        ITextSelection textSelection = (ITextSelection) selection;
        IEditorInput editorInput = textEditor.getEditorInput();
        IDocumentProvider documentProvider = textEditor.getDocumentProvider();
        if (documentProvider == null) {
            throw new CoreException(Status.CANCEL_STATUS);
        }
        IDocument document = documentProvider.getDocument(editorInput);
        int offset = textSelection.getOffset();
        if (document != null) {
            try {
                IRegion region = document.getLineInformationOfOffset(offset);
                int end = region.getOffset() + region.getLength();
                while (Character.isWhitespace(document.getChar(offset)) && offset < end) {
                    offset++;
                }
            } catch (BadLocationException e) {
            }
        }
        IMember m = null;
        ITypeRoot root = getTypeRoot(editorInput);
        if (root instanceof ICompilationUnit) {
            ICompilationUnit unit = (ICompilationUnit) root;
            synchronized (unit) {
                unit.reconcile(ICompilationUnit.NO_AST, false, null, null);
            }
        }
        if (root != null) {
            IJavaElement e = root.getElementAt(offset);
            if (e instanceof IMember) {
                m = (IMember) e;
            }
        }
        if (m != null) {
            return new StructuredSelection(m);
        }
    }
    return selection;
}

From source file:org.evosuite.eclipse.popup.actions.ExtendSuiteEditorAction.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
    ISelection selection = HandlerUtil.getActiveMenuSelection(event);

    String SUT = "";
    IResource target = null;//from   w  ww  .j  a v a2  s .com

    System.out.println("Current selection of type " + selection.getClass().getName() + ": " + selection);
    if (selection instanceof TreeSelection) {
        TreeSelection treeSelection = (TreeSelection) selection;
        IAdaptable firstElement = (IAdaptable) treeSelection.getFirstElement();

        // Relies on an internal API, bad juju
        if (firstElement instanceof org.eclipse.jdt.internal.core.CompilationUnit) {
            try {
                org.eclipse.jdt.internal.core.CompilationUnit compilationUnit = (org.eclipse.jdt.internal.core.CompilationUnit) firstElement;
                String packageName = "";
                if (compilationUnit.getPackageDeclarations().length > 0) {
                    System.out.println(
                            "Package: " + compilationUnit.getPackageDeclarations()[0].getElementName());
                    packageName = compilationUnit.getPackageDeclarations()[0].getElementName();
                }
                String targetSuite = compilationUnit.getElementName().replace(".java", "");
                if (!packageName.isEmpty())
                    targetSuite = packageName + "." + targetSuite;
                System.out.println("Selected class: " + targetSuite);
                SUT = targetSuite;
                target = compilationUnit.getResource();
            } catch (JavaModelException e) {

            }
        }
    } else if (activeEditor instanceof JavaEditor) {
        ITypeRoot root = EditorUtility.getEditorInputJavaElement(activeEditor, false);
        ITextSelection sel = (ITextSelection) ((JavaEditor) activeEditor).getSelectionProvider().getSelection();
        int offset = sel.getOffset();
        IJavaElement element;

        try {
            element = root.getElementAt(offset);
            if (element.getElementType() == IJavaElement.METHOD) {
                IJavaElement pDeclaration = element.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
                IPackageFragment pFragment = (IPackageFragment) pDeclaration;
                String packageName = "";
                if (pFragment.getCompilationUnits()[0].getPackageDeclarations().length > 0) {
                    System.out.println("Package: "
                            + pFragment.getCompilationUnits()[0].getPackageDeclarations()[0].getElementName());
                    packageName = pFragment.getCompilationUnits()[0].getPackageDeclarations()[0]
                            .getElementName();
                }
                String targetSuite = element.getParent().getElementName();
                if (!packageName.isEmpty())
                    targetSuite = packageName + "." + targetSuite;
                System.out.println("Selected class: " + targetSuite);
                SUT = targetSuite;
            } else if (element.getElementType() == IJavaElement.TYPE) {
                IType type = ((IType) element);
                System.out.println("Selected class: " + type.getFullyQualifiedName());
                SUT = type.getFullyQualifiedName();
            }

            IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot();
            target = wroot.findMember(root.getPath());
        } catch (JavaModelException e) {

        }
    }
    if (!SUT.isEmpty() && target != null) {
        IProject proj = target.getProject();
        fixJUnitClassPath(JavaCore.create(proj));
        generateTests(target);
    }

    return null;
}

From source file:org.evosuite.eclipse.popup.actions.GenerateTestsEditorAction.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
    // ISelection selection = HandlerUtil.getCurrentSelection(event);
    ISelection selection = HandlerUtil.getActiveMenuSelection(event);

    String SUT = "";
    IResource target = null;/*from   w ww.j a v a2s .  c  o  m*/
    System.out.println("Current selection of type " + selection.getClass().getName() + ": " + selection);
    if (selection instanceof TreeSelection) {
        TreeSelection treeSelection = (TreeSelection) selection;
        IAdaptable firstElement = (IAdaptable) treeSelection.getFirstElement();

        // Relies on an internal API, bad juju
        if (firstElement instanceof org.eclipse.jdt.internal.core.CompilationUnit) {
            try {
                org.eclipse.jdt.internal.core.CompilationUnit compilationUnit = (org.eclipse.jdt.internal.core.CompilationUnit) firstElement;
                String packageName = "";
                if (compilationUnit.getPackageDeclarations().length > 0) {
                    System.out.println(
                            "Package: " + compilationUnit.getPackageDeclarations()[0].getElementName());
                    packageName = compilationUnit.getPackageDeclarations()[0].getElementName();
                }
                String targetSuite = compilationUnit.getElementName().replace(".java", "");
                if (!packageName.isEmpty())
                    targetSuite = packageName + "." + targetSuite;
                System.out.println("Selected class: " + targetSuite);
                SUT = targetSuite;
                target = compilationUnit.getResource();
            } catch (JavaModelException e) {

            }
        }
    } else if (activeEditor instanceof JavaEditor) {
        ITypeRoot root = EditorUtility.getEditorInputJavaElement(activeEditor, false);
        ITextSelection sel = (ITextSelection) ((JavaEditor) activeEditor).getSelectionProvider().getSelection();
        int offset = sel.getOffset();
        IJavaElement element;

        try {
            element = root.getElementAt(offset);
            if (element == null) {
                ISelection sel2 = HandlerUtil.getCurrentSelection(event);
                System.out.println(
                        "Selected element of type " + sel2.getClass().getName() + ": " + sel2.toString());
            } else if (element.getElementType() == IJavaElement.METHOD) {
                IJavaElement pDeclaration = element.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
                IPackageFragment pFragment = (IPackageFragment) pDeclaration;
                String packageName = "";
                if (pFragment.getCompilationUnits()[0].getPackageDeclarations().length > 0) {
                    System.out.println("Package: "
                            + pFragment.getCompilationUnits()[0].getPackageDeclarations()[0].getElementName());
                    packageName = pFragment.getCompilationUnits()[0].getPackageDeclarations()[0]
                            .getElementName();
                }
                String targetSuite = element.getParent().getElementName();
                if (!packageName.isEmpty())
                    targetSuite = packageName + "." + targetSuite;
                System.out.println("Selected class: " + targetSuite);
                SUT = targetSuite;
            } else if (element.getElementType() == IJavaElement.TYPE) {
                IType type = ((IType) element);
                System.out.println("Selected class: " + type.getFullyQualifiedName());
                SUT = type.getFullyQualifiedName();
            }

            IWorkspaceRoot wroot = ResourcesPlugin.getWorkspace().getRoot();
            target = wroot.findMember(EditorUtility.getEditorInputJavaElement(activeEditor, false).getPath());

        } catch (JavaModelException e) {

        }

    }

    if (!SUT.isEmpty() && target != null) {
        IProject proj = target.getProject();
        fixJUnitClassPath(JavaCore.create(proj));
        generateTests(target);
    }

    return null;
}

From source file:org.jboss.tools.cdi.deltaspike.text.ext.AuthorizerHyperlinkDetector.java

License:Open Source License

public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    this.region = region;
    this.viewer = textViewer;

    ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null || !canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor))
        return null;

    int offset = region.getOffset();

    ITypeRoot input = EditorUtility.getEditorInputJavaElement(textEditor, false);
    if (input == null)
        return null;

    document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
    IRegion wordRegion = JavaWordFinder.findWord(document, offset);
    if (wordRegion == null)
        return null;

    IProject project = null;/*from   www  .j a v a 2  s . c om*/

    project = input.getJavaProject().getProject();

    if (project == null)
        return null;

    CDICoreNature cdiNature = CDIUtil.getCDINatureWithProgress(project);
    if (cdiNature == null)
        return null;

    IJavaElement[] elements = null;
    IType annotationType = null;

    try {
        elements = input.codeSelect(wordRegion.getOffset(), wordRegion.getLength());
        if (elements == null)
            return null;
        if (elements.length != 1)
            return null;

        ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>();
        int position = 0;
        if (elements[0] instanceof IType) {
            annotationType = (IType) elements[0];
            if (!annotationType.isAnnotation()) {
                annotationType = null;
            }
            elements[0] = input.getElementAt(wordRegion.getOffset());
            if (elements[0] == null)
                return null;

            if (elements[0] instanceof IMethod) {
                position = offset;
            }
        }

        findAuthorizerMethods(cdiNature, elements[0], annotationType, position, input.getPath(), hyperlinks);

        if (hyperlinks != null && !hyperlinks.isEmpty()) {
            return (IHyperlink[]) hyperlinks.toArray(new IHyperlink[hyperlinks.size()]);
        }
    } catch (JavaModelException jme) {
        DeltaspikeCorePlugin.getDefault().logError(jme);
    }
    return null;
}

From source file:org.jboss.tools.cdi.seam.text.ext.hyperlink.CDISeamResourceLoadingHyperlinkDetector.java

License:Open Source License

@Override
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null || !(textEditor instanceof JavaEditor))
        return null;

    int offset = region.getOffset();

    ITypeRoot input = EditorUtility.getEditorInputJavaElement(textEditor, false);
    if (input == null)
        return null;

    IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());

    IResource r = input.getResource();//  ww w  .  j  a  va2  s.  com
    if (!(r instanceof IFile) || !r.exists() || r.getName().endsWith(".jar")) {
        return null;
    }
    IFile file = (IFile) r;

    try {

        IJavaElement element = input.getElementAt(offset);
        if (element != null) {
            if (element instanceof IField) {
                IAnnotation annotation = CDIMarkerResolutionUtils.findAnnotation(element,
                        RESOURCE_ANNOTATION_30);
                if (annotation == null || !annotation.exists()) {
                    annotation = CDIMarkerResolutionUtils.findAnnotation(element, RESOURCE_ANNOTATION_31);
                }
                if (annotation != null && annotation.exists()) {
                    IRegion annotationRegion = getAnnotationRegion(document, annotation);
                    String text = getValue(annotation);
                    if (text != null) {
                        return new IHyperlink[] {
                                new CDISeamResourceLoadingHyperlink(file, document, annotationRegion, text) };
                    }
                }
            }
        }
    } catch (CoreException ex) {
        CDISeamExtPlugin.getDefault().logError(ex);
    } catch (BadLocationException ex) {
        CDISeamExtPlugin.getDefault().logError(ex);
    }

    return null;
}

From source file:org.jboss.tools.cdi.seam.text.ext.hyperlink.GenericInjectedPointHyperlinkDetector.java

License:Open Source License

public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
        boolean canShowMultipleHyperlinks) {
    this.region = region;
    this.viewer = textViewer;

    ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null || !canShowMultipleHyperlinks || !(textEditor instanceof JavaEditor))
        return null;

    int offset = region.getOffset();

    ITypeRoot input = EditorUtility.getEditorInputJavaElement(textEditor, false);
    if (input == null)
        return null;

    document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
    IRegion wordRegion = JavaWordFinder.findWord(document, offset);
    if (wordRegion == null)
        return null;

    IProject project = null;//from  w  w  w. ja  va  2s .  c  o m

    project = input.getJavaProject().getProject();

    if (project == null)
        return null;

    CDICoreNature cdiNature = CDIUtil.getCDINatureWithProgress(project);
    if (cdiNature == null)
        return null;

    IJavaElement[] elements = null;

    try {
        elements = input.codeSelect(wordRegion.getOffset(), wordRegion.getLength());
        if (elements == null)
            return null;
        if (elements.length != 1)
            return null;

        ArrayList<IHyperlink> hyperlinks = new ArrayList<IHyperlink>();
        int position = 0;
        if (elements[0] instanceof IType) {
            elements[0] = input.getElementAt(wordRegion.getOffset());
            if (elements[0] == null)
                return null;

            if (elements[0] instanceof IMethod) {
                position = offset;
            }
        }

        findInjectedBeans(cdiNature, elements[0], position, input.getPath(), hyperlinks);

        if (hyperlinks != null && !hyperlinks.isEmpty()) {
            return (IHyperlink[]) hyperlinks.toArray(new IHyperlink[hyperlinks.size()]);
        }
    } catch (JavaModelException jme) {
        CDISeamExtPlugin.getDefault().logError(jme);
    }
    return null;
}