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

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

Introduction

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

Prototype

String getElementName();

Source Link

Document

Returns the name of this element.

Usage

From source file:org.eclipse.xtend.ide.tests.navigation.DetectImplHyperlinksTest.java

License:Open Source License

@Test
public void testComputeHyperlink_1() throws Exception {
    String content = "package foo class Foo { def b|ar(String a) {} }";
    XtextEditor xtextEditor = openEditor(content.replace("|", ""));
    int offset = content.indexOf("|");

    IHyperlink[] detectHyperlinks = hyperlinkDetector.detectHyperlinks(xtextEditor.getInternalSourceViewer(),
            new Region(offset, 1), true);
    assertEquals(2, detectHyperlinks.length);
    IHyperlink hyperlink = detectHyperlinks[0];
    assertTrue(hyperlink instanceof JdtHyperlink);
    JdtHyperlink casted = (JdtHyperlink) hyperlink;
    assertEquals(offset - 1, casted.getHyperlinkRegion().getOffset());
    assertEquals(3, casted.getHyperlinkRegion().getLength());
    IJavaElement element = ((JdtHyperlink) hyperlink).getJavaElement();
    assertTrue(element instanceof IType);
    assertEquals("Object", element.getElementName());
    assertEquals("Open Inferred Type - Object", casted.getHyperlinkText());
}

From source file:org.eclipse.xtend.ide.tests.navigation.DetectImplHyperlinksTest.java

License:Open Source License

@Test
public void testComputeHyperlink_2() throws Exception {
    String content = "package foo class Foo { def bar(String a) { fo|o() } def foo(){}}";
    XtextEditor xtextEditor = openEditor(content.replace("|", ""));
    int offset = content.indexOf("|");

    IHyperlink[] detectHyperlinks = hyperlinkDetector.detectHyperlinks(xtextEditor.getInternalSourceViewer(),
            new Region(offset, 1), true);
    assertEquals(3, detectHyperlinks.length);
    XbaseImplementatorsHyperlink hyperlink = Iterables
            .filter(Lists.newArrayList(detectHyperlinks), XbaseImplementatorsHyperlink.class).iterator().next();
    assertEquals(offset - 2, hyperlink.getHyperlinkRegion().getOffset());
    assertEquals(3, hyperlink.getHyperlinkRegion().getLength());
    IJavaElement element = hyperlink.getElement();
    assertTrue(element instanceof IMethod);
    assertEquals("foo", element.getElementName());
}

From source file:org.eclipse.xtext.common.types.access.jdt.JdtTypeProviderTest.java

License:Open Source License

@Override
protected JvmOperation getMethodFromParameterizedMethods(String method) {
    JvmOperation result = super.getMethodFromParameterizedMethods(method);
    if (result != null) {
        IJavaElement found = elementFinder.findElementFor(result);
        assertEquals(IJavaElement.METHOD, found.getElementType());
        assertEquals(result.getSimpleName(), found.getElementName());
        IMethod foundMethod = (IMethod) found;
        assertEquals(result.getParameters().size(), foundMethod.getNumberOfParameters());
    }//ww w. j a  va2 s  .  c  o  m
    return result;
}

From source file:org.eclipse.xtext.common.types.access.jdt.JdtTypeProviderTest.java

License:Open Source License

@Override
protected JvmOperation getMethodFromType(EObject context, Class<?> type, String method) {
    JvmOperation result = super.getMethodFromType(context, type, method);
    if (result != null) {
        IJavaElement found = elementFinder.findElementFor(result);
        assertEquals(IJavaElement.METHOD, found.getElementType());
        assertEquals(result.getSimpleName(), found.getElementName());
        IMethod foundMethod = (IMethod) found;
        assertEquals(result.getParameters().size(), foundMethod.getNumberOfParameters());
    }//  w w w .j  ava  2 s.c  om
    return result;
}

From source file:org.eclipse.xtext.common.types.access.jdt.JdtTypeProviderTest.java

License:Open Source License

@Override
protected JvmConstructor getConstructorFromType(EObject context, Class<?> type, String constructor) {
    JvmConstructor result = super.getConstructorFromType(context, type, constructor);
    if (result != null) {
        IJavaElement found = elementFinder.findElementFor(result);
        assertEquals(IJavaElement.METHOD, found.getElementType());
        assertEquals(result.getSimpleName(), found.getElementName());
        IMethod foundMethod = (IMethod) found;
        assertEquals(result.getParameters().size(), foundMethod.getNumberOfParameters());
    }/*w  w w. java  2  s  . c o m*/
    return result;
}

From source file:org.eclipse.xtext.common.types.ui.refactoring.JdtRenameRefactoringProcessorFactory.java

License:Open Source License

public JavaRenameProcessor createRenameProcessor(IJavaElement element) {
    try {//from   w  w w . j a v  a  2 s .  c om
        switch (element.getElementType()) {
        case IJavaElement.TYPE:
            return new RenameTypeProcessor((IType) element);
        case IJavaElement.FIELD:
            if (((IField) element).getDeclaringType().isEnum())
                return new RenameEnumConstProcessor((IField) element);
            else
                return new RenameFieldProcessor((IField) element);
        case IJavaElement.METHOD:
            if (((IMethod) element).isConstructor())
                break;
            if (Flags.isStatic(((IMethod) element).getFlags())
                    || Flags.isPrivate(((IMethod) element).getFlags()))
                return new RenameNonVirtualMethodProcessor((IMethod) element);
            else
                return new RenameVirtualMethodProcessor((IMethod) element);
        case IJavaElement.TYPE_PARAMETER:
            return new RenameTypeParameterProcessor((ITypeParameter) element);
        case IJavaElement.LOCAL_VARIABLE:
            return new RenameLocalVariableProcessor((ILocalVariable) element);

        }
    } catch (JavaModelException exc) {
        LOG.error("Error creating refactoring processor for " + element.getElementName(), exc);
    }
    return null;
}

From source file:org.eclipse.xtext.common.types.ui.refactoring.JvmRenameRefactoringProvider.java

License:Open Source License

@Override
public ProcessorBasedRefactoring getRenameRefactoring(IRenameElementContext renameElementContext) {
    if (renameElementContext instanceof JdtRefactoringContext) {
        IJavaElement javaElement = ((JdtRefactoringContext) renameElementContext).getJavaElement();
        if (isJavaSource(javaElement)) {
            try {
                RenameJavaElementDescriptor renameDescriptor = createRenameDescriptor(javaElement,
                        javaElement.getElementName());
                return (ProcessorBasedRefactoring) renameDescriptor.createRefactoring(new RefactoringStatus());
            } catch (Exception exc) {
                throw new WrappedException(exc);
            }/*from   www.  ja v a 2s  .  c  o  m*/
        }
    }
    return super.getRenameRefactoring(renameElementContext);
}

From source file:org.eclipse.xtext.common.types.util.jdt.JavaElementFinderTest.java

License:Open Source License

protected void doTestFindMethod(Class<?> declaringType, String methodName, int numberOfParameters) {
    JvmOperation foundOperation = findOperation(declaringType, methodName, numberOfParameters);
    assertNotNull(foundOperation);//from   w w  w.  ja  va 2s.c om
    IJavaElement found = elementFinder.findElementFor(foundOperation);
    assertEquals(IJavaElement.METHOD, found.getElementType());
    assertEquals(methodName, found.getElementName());
    IMethod foundMethod = (IMethod) found;
    assertEquals(numberOfParameters, foundMethod.getNumberOfParameters());
}

From source file:org.eclipse.xtext.xbase.ui.navigation.JvmImplementationOpener.java

License:Open Source License

/**
 * Main parts of the logic is taken from {@link org.eclipse.jdt.internal.ui.javaeditor.JavaElementImplementationHyperlink}
 *
 * @param element - Element to show implementations for
 * @param textviewer - Viewer to show hierarchy view on
 * @param region - Region where to show hierarchy view
 *///from  ww  w  .  j a v a2 s  .  c o  m
public void openImplementations(final IJavaElement element, ITextViewer textviewer, IRegion region) {
    if (element instanceof IMethod) {
        ITypeRoot typeRoot = ((IMethod) element).getTypeRoot();
        CompilationUnit ast = SharedASTProvider.getAST(typeRoot, SharedASTProvider.WAIT_YES, null);
        if (ast == null) {
            openQuickHierarchy(textviewer, element, region);
            return;
        }
        try {
            ISourceRange nameRange = ((IMethod) element).getNameRange();
            ASTNode node = NodeFinder.perform(ast, nameRange);
            ITypeBinding parentTypeBinding = null;
            if (node instanceof SimpleName) {
                ASTNode parent = node.getParent();
                if (parent instanceof MethodInvocation) {
                    Expression expression = ((MethodInvocation) parent).getExpression();
                    if (expression == null) {
                        parentTypeBinding = Bindings.getBindingOfParentType(node);
                    } else {
                        parentTypeBinding = expression.resolveTypeBinding();
                    }
                } else if (parent instanceof SuperMethodInvocation) {
                    // Directly go to the super method definition
                    openEditor(element);
                    return;
                } else if (parent instanceof MethodDeclaration) {
                    parentTypeBinding = Bindings.getBindingOfParentType(node);
                }
            }
            final IType type = parentTypeBinding != null ? (IType) parentTypeBinding.getJavaElement() : null;
            if (type == null) {
                openQuickHierarchy(textviewer, element, region);
                return;
            }

            final String earlyExitIndicator = "EarlyExitIndicator";
            final ArrayList<IJavaElement> links = Lists.newArrayList();
            IRunnableWithProgress runnable = new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    if (monitor == null) {
                        monitor = new NullProgressMonitor();
                    }
                    try {
                        String methodLabel = JavaElementLabels.getElementLabel(element,
                                JavaElementLabels.DEFAULT_QUALIFIED);
                        monitor.beginTask(
                                Messages.format("Searching for implementors of  ''{0}''", methodLabel), 100);
                        SearchRequestor requestor = new SearchRequestor() {
                            @Override
                            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                                if (match.getAccuracy() == SearchMatch.A_ACCURATE) {
                                    IJavaElement element = (IJavaElement) match.getElement();
                                    if (element instanceof IMethod && !JdtFlags.isAbstract((IMethod) element)) {
                                        links.add(element);
                                        if (links.size() > 1) {
                                            throw new OperationCanceledException(earlyExitIndicator);
                                        }
                                    }
                                }
                            }
                        };
                        int limitTo = IJavaSearchConstants.DECLARATIONS
                                | IJavaSearchConstants.IGNORE_DECLARING_TYPE
                                | IJavaSearchConstants.IGNORE_RETURN_TYPE;
                        SearchPattern pattern = SearchPattern.createPattern(element, limitTo);
                        Assert.isNotNull(pattern);
                        SearchParticipant[] participants = new SearchParticipant[] {
                                SearchEngine.getDefaultSearchParticipant() };
                        SearchEngine engine = new SearchEngine();
                        engine.search(pattern, participants, SearchEngine.createHierarchyScope(type), requestor,
                                new SubProgressMonitor(monitor, 100));

                        if (monitor.isCanceled()) {
                            throw new InterruptedException();
                        }
                    } catch (OperationCanceledException e) {
                        throw new InterruptedException(e.getMessage());
                    } catch (CoreException e) {
                        throw new InvocationTargetException(e);
                    } finally {
                        monitor.done();
                    }
                }
            };

            try {
                PlatformUI.getWorkbench().getProgressService().busyCursorWhile(runnable);
            } catch (InvocationTargetException e) {
                IStatus status = new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK,
                        Messages.format(
                                "An error occurred while searching for implementations of method ''{0}''. See error log for details.",
                                element.getElementName()),
                        e.getCause());
                JavaPlugin.log(status);
                ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                        "Open Implementation", "Problems finding implementations.", status);
            } catch (InterruptedException e) {
                if (e.getMessage() != earlyExitIndicator) {
                    return;
                }
            }

            if (links.size() == 1) {
                openEditor(links.get(0));
            } else {
                openQuickHierarchy(textviewer, element, region);
            }

        } catch (JavaModelException e) {
            log.error("An error occurred while searching for implementations", e.getCause());
        } catch (PartInitException e) {
            log.error("An error occurred while searching for implementations", e.getCause());
        }
    }
}

From source file:org.eclipseguru.gwt.internal.core.refactoring.GwtRefactoringUtil.java

License:Open Source License

/**
 * Provides a public mechanism for creating the <code>Change</code> for
 * moving a type/*from   w  w w .  j a v  a  2  s. c  o  m*/
 * 
 * @param type
 *            the type being moved
 * @param destination
 *            the destination to move the type to
 * @return the <code>Change</code> for the type move
 * @throws CoreException
 */
public static Change createChangesForTypeMove(final IType type, final IJavaElement destination)
        throws CoreException {
    String newfqname = type.getElementName();
    if (destination instanceof IType) {
        newfqname = ((IType) destination).getFullyQualifiedName() + '$' + type.getElementName();
    } else if (destination instanceof IPackageFragment)
        if (!((IPackageFragment) destination).isDefaultPackage()) {
            newfqname = destination.getElementName() + '.' + type.getElementName();
        }
    return createChangesForTypeChange(type, newfqname);
}