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:com.github.parzonka.ccms.handler.BatchProcessingHandler.java

License:Open Source License

/**
 * @param event// ww  w.j ava2s  . c om
 * @param store
 * @param elements
 * @throws ExecutionException
 */
private void sort(IJavaElement[] elements) throws ExecutionException {

    for (IJavaElement iJavaElement : elements) {

        if (iJavaElement instanceof CompilationUnit) {
            sort((CompilationUnit) iJavaElement);

        } else if (iJavaElement instanceof PackageFragmentRoot) {
            sort((PackageFragmentRoot) iJavaElement);

        } else if (iJavaElement instanceof PackageFragment) {
            sort((PackageFragment) iJavaElement);

        } else if (iJavaElement instanceof JavaProject) {
            sort((JavaProject) iJavaElement);

        } else {
            MessageDialog.openInformation(HandlerUtil.getActiveWorkbenchWindow(event).getShell(),
                    "Clean Code Method Sorter",
                    iJavaElement.getClass().getCanonicalName() + "\n" + iJavaElement.getElementName());
        }
    }
}

From source file:com.google.gwt.eclipse.core.modules.ModuleFile.java

License:Open Source License

@Override
protected String doGetPackageName() {
    IFolder moduleFolder = (IFolder) getFile().getParent();
    IJavaElement javaElement = JavaCore.create(moduleFolder);

    // Maven module name - maven 1 or maven 2 plugins
    String mavenModuleName = WebAppProjectProperties.getGwtMavenModuleName(moduleFolder.getProject());

    // not null, then it must be a gwt maven project 2
    String shortName = WebAppProjectProperties.getGwtMavenModuleShortName(moduleFolder.getProject());
    if (mavenModuleName != null && !mavenModuleName.isEmpty() && shortName != null && !shortName.isEmpty()
            && mavenModuleName.contains(".")) {
        String gwtMavenPackage2 = mavenModuleName.replaceAll("(.*)\\..*", "$1");
        return gwtMavenPackage2;
    }/*from   w  w  w  .  j  a v  a2 s .c  o m*/

    if (javaElement != null) {
        if (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
            return javaElement.getElementName();
        }
    } else {
        // TODO: handle super-source case here
    }

    return "";
}

From source file:com.google.gwt.eclipse.core.refactoring.GWTRenameParticipant.java

License:Open Source License

@Override
protected boolean initialize(Object element) {
    if (element instanceof IType || element instanceof IMethod || element instanceof IField) {
        GWTRefactoringSupport support = getRefactoringSupport();

        IMember oldMember = (IMember) element;
        support.setOldElement(oldMember);

        try {//  w  w  w  .j ava2  s.c om
            /*
             * We can't trust our RenameArgument's getNewName() to always return the
             * correct new name. When the user sets the new name in the Rename
             * refactoring dialog, clicks Next to go to the Preview page, then
             * clicks Back and changes the new name, getNewName() returns the
             * original name, not the updated one. This appears to be a bug in the
             * JDT, which affects other built-in rename participants such as
             * BreakpointRenameTypeParticipant. It does not affect the core JDT
             * refactorings, though, since they are executed directly from
             * JavaRenameRefactoring and not as loaded rename participants.
             * 
             * The workaround here is to instead go directly to the refactoring
             * processor and query it for the new element, which will have the right
             * name.
             * 
             * TODO: file this as a JDT bug?
             */
            JavaRenameProcessor processor = getRenameProcessor();
            IJavaElement newElement = (IJavaElement) processor.getNewElement();
            IType declaringType = oldMember.getDeclaringType();
            String newElementName = newElement.getElementName();
            /*
             * Compute the new method by using the declaring type of the old method.
             * Otherwise when a RenameVirtualMethodProcessor instance is passed in,
             * we will end up looking at the topmost declaration of the method
             * instead of the one we actually want because
             * RenameVirtualMethodProcessor.getNewElement() actually points to the
             * topmost declaration.
             */
            if (element instanceof IField) {
                newElement = declaringType.getField(newElementName);
            } else if (element instanceof IMethod) {
                IMethod method = (IMethod) newElement;
                newElement = declaringType.getMethod(newElementName, method.getParameterTypes());
            } else {
                assert (element instanceof IType);
            }

            support.setNewElement(newElement);
            support.setUpdateReferences(getArguments().getUpdateReferences());

            return true;
        } catch (CoreException e) {
            GWTPluginLog.logError(e);
        }
    }

    return false;
}

From source file:com.google.gwt.eclipse.core.search.JavaQueryParticipant.java

License:Open Source License

private Set<IIndexedJavaRef> findMatches(ElementQuerySpecification query, boolean resolveMatches) {
    IJavaElement javaElement = query.getElement();
    JavaRefIndex index = JavaRefIndex.getInstance();
    int elementType = javaElement.getElementType();

    // Type matches are easy: just compare the fully-qualified type name, and if
    // they are equal, then we have a match
    if (elementType == IJavaElement.TYPE) {
        String typeName = ((IType) javaElement).getFullyQualifiedName();
        return index.findTypeReferences(typeName);
    }//from w  ww  .ja  v  a  2s. c  o m

    // Besides types, we only support searching for fields and methods
    if (elementType != IJavaElement.FIELD && elementType != IJavaElement.METHOD) {
        return Collections.emptySet();
    }

    // Get the type that actually declares this member (could be a super type)
    IType declType = ((IMember) javaElement).getDeclaringType();
    assert (declType != null && declType.exists());

    // Search the index for matches based only on the member name and type
    Set<IIndexedJavaRef> nameMatches = (elementType == IJavaElement.METHOD)
            ? index.findMethodReferences(javaElement.getElementName())
            : index.findFieldReferences(javaElement.getElementName());

    // We optionally return the full set of "potential" matches (i.e., index
    // entries that match by name but may not resolve to the query element)
    if (!resolveMatches) {
        return nameMatches;
    }

    Set<IIndexedJavaRef> matches = new HashSet<IIndexedJavaRef>();
    for (IIndexedJavaRef nameMatch : nameMatches) {
        /*
         * Try to resolve each potential match to see if it actually references
         * the target Java element. This takes care of matching the method
         * parameter lists, as well as correctly searching for a super type's
         * members from a reference to one of its subclasses.
         */
        IJavaElement matchElement = nameMatch.resolve();
        if (javaElement.equals(matchElement)) {
            matches.add(nameMatch);
        }
    }

    return matches;
}

From source file:com.google.gwt.eclipse.core.uibinder.model.UiBinderSubtypeToUiXmlIndex.java

License:Open Source License

private static void loadEntry(IMemento memento, UiBinderSubtypeToUiXmlIndex index) throws PersistenceException {
    String uiXmlPath = memento.getString(KEY_UI_XML_PATH);
    if (uiXmlPath == null) {
        throw new PersistenceException("Missing key " + KEY_UI_XML_PATH);
    }// w w w .j av  a2  s. co m

    String uiBinderSubtypeKey = memento.getString(KEY_UIBINDER_SUBTYPE);
    if (uiBinderSubtypeKey == null) {
        throw new PersistenceException("Missing key " + KEY_UIBINDER_SUBTYPE);
    }

    IJavaElement javaElement = JavaCore.create(uiBinderSubtypeKey);
    if (javaElement == null) {
        throw new PersistenceException("Could not create Java element with key " + uiBinderSubtypeKey);
    }

    if (!(javaElement instanceof IType)) {
        throw new PersistenceException("Expecting " + javaElement.getElementName() + " to be a type");
    }

    if (!javaElement.getJavaProject().isOpen()) {
        return;
    }

    if (!JavaModelSearch.isValidElement(javaElement)) {
        throw new PersistenceException(
                ((IType) javaElement).getFullyQualifiedName() + " is not a valid Java type");
    }

    // Add the subtype + ui.xml pair to the index
    index.setUiXmlPath((IType) javaElement, new Path(uiXmlPath));
}

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

License:Open Source License

public void testResolveJavaElement() {
    IJavaProject project = getTestProject();
    assertNotNull(project);//from  www  . ja  v  a2  s.co m

    JsniJavaRef ref;
    IJavaElement element;

    try {
        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest::new()");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IMethod);
        assertTrue(((IMethod) element).isConstructor());

        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest::getNumber()");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IMethod);
        assertEquals(element.getElementName(), "getNumber");

        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest$Inner::new(Ljava/lang/String;)");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IMethod);
        assertTrue(((IMethod) element).isConstructor());

        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest$InnerSub::sayHi([I)");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IMethod);
        assertEquals(element.getElementName(), "sayHi");
        assertEquals(element.getParent().getElementName(), "InnerSub");

        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest$InnerSub::sayHi(*)");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IMethod);
        assertEquals(element.getElementName(), "sayHi");
        assertEquals(element.getParent().getElementName(), "InnerSub");

        ref = JsniJavaRef.parse(
                "@com.hello.client.JsniJavaRefTest$InnerSub::takeInner(Lcom/hello/client/JsniJavaRefTest$Inner;)");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IMethod);
        assertEquals(element.getElementName(), "takeInner");
        assertEquals(element.getParent().getElementName(), "Inner");

        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest$InnerSub::takeT(Ljava/lang/String;I)");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IMethod);
        assertEquals(element.getElementName(), "takeT");
        assertEquals(element.getParent().getElementName(), "InnerSub");

        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest::keith");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IField);
        assertEquals(element.getElementName(), "keith");

        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest.InnerInterface::getKey()");
        element = ref.resolveJavaElement(project);
        assertTrue(element instanceof IMethod);
        assertEquals(element.getElementName(), "getKey");
        assertEquals(element.getParent().getElementName(), "InnerInterface");

    } catch (UnresolvedJsniJavaRefException e) {
        fail(e.getMessage());
    } catch (JavaModelException e) {
        fail(e.getMessage());
    }

    try {
        // unresolved reference
        ref = JsniJavaRef.parse(
                "@com.hello.client.JsniJavaRefTest$InnerSub::takeInner(Lcom/hello/client/JsniJavaRefTest;)");
        element = ref.resolveJavaElement(project);
        fail("resolveElement should have thrown UnresolvedJsniJavaRefException");

    } catch (UnresolvedJsniJavaRefException e) {
        // We're expecting the exception, so do nothing
    }

    try {
        // unresolved interface member reference
        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest.InnerInterface::badRef()");
        element = ref.resolveJavaElement(project);
        fail("resolveElement should have thrown UnresolvedJsniJavaRefException");

    } catch (UnresolvedJsniJavaRefException e) {
        // We're expecting the exception, so do nothing
    }

    try {
        // magic null reference (should be ignored)
        ref = JsniJavaRef.parse("@null::nullMethod()");
        element = ref.resolveJavaElement(project);
        fail("resolveElement should have thrown UnresolvedJsniJavaRefException");

    } catch (UnresolvedJsniJavaRefException e) {
        assertNull(e.getProblemType());
    }

    try {
        // reference to JRE type (should be ignored)
        ref = JsniJavaRef.parse("@java.lang.String::valueOf(J)");
        element = ref.resolveJavaElement(project);
        fail("resolveElement should have thrown UnresolvedJsniJavaRefException");

    } catch (UnresolvedJsniJavaRefException e) {
        assertNull(e.getProblemType());
    }

    try {
        // synthetic Enum::values() reference (should be ignored)
        ref = JsniJavaRef.parse("@com.hello.client.JsniJavaRefTest.MyEnum::values()");
        element = ref.resolveJavaElement(project);
        fail("resolveElement should have thrown UnresolvedJsniJavaRefException");

    } catch (UnresolvedJsniJavaRefException e) {
        assertNull(e.getProblemType());
    }
}

From source file:com.google.test.metric.eclipse.ui.internal.JavaPackageElementContentProvider.java

License:Apache License

public Object[] getChildren(Object element) {
    if (element instanceof IJavaProject) {
        try {/*from  www. j av  a2  s  .c om*/
            return javaProjectHelper.getAllJavaPackageFragmentRoots((IJavaProject) element).toArray();
        } catch (JavaModelException e) {
            logger.logException(e);
        } catch (CoreException e) {
            logger.logException(e);
        }
    } else if (element instanceof IPackageFragmentRoot || element instanceof IPackageFragment) {
        try {
            List<IJavaElement> javaElements = new ArrayList<IJavaElement>();
            IJavaElement[] children = ((IParent) element).getChildren();
            for (IJavaElement javaElement : children) {
                if (javaElement instanceof IPackageFragment && !javaElement.getElementName().equals("")) {
                    javaElements.add(javaElement);
                }
            }
            return javaElements.toArray();
        } catch (JavaModelException e) {
            logger.logException(e);
        }
    }
    return null;
}

From source file:com.halware.nakedide.eclipse.ext.annot.tracker.AstJob.java

License:Open Source License

private static String deriveJobName(EditorContent editorContent) {
    IJavaElement openable = (IJavaElement) editorContent.getOpenable();
    return openable != null ? openable.getElementName() : "NULL";
}

From source file:com.legstar.eclipse.plugin.cixsmap.dialogs.LegacyStructureDialog.java

License:Open Source License

/**
 * Examines packages in a given project and adds segments which contain the
 * .bind suffix to the package list table. ".bind" suffix identify segments
 * that correspond to COXB binding packages.
 * //from   w  w w.  ja v  a 2 s  . c o m
 * @param project the java project to get packages from
 * @return map of java package names to fragments
 * @throws CoreException if the given project is not a Java project
 */
private Map<String, IPackageFragment> createPackageList(final IProject project) throws CoreException {
    Map<String, IPackageFragment> packageMap = new HashMap<String, IPackageFragment>();
    IJavaProject jproject = JavaCore.create(project);
    IPackageFragmentRoot[] pkgRoots = jproject.getPackageFragmentRoots();
    for (int j = 0; j < pkgRoots.length; j++) {
        IPackageFragmentRoot pkgRoot = pkgRoots[j];
        if (pkgRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
            for (int k = 0; k < pkgRoot.getChildren().length; k++) {
                IJavaElement el = pkgRoot.getChildren()[k];
                if (el.getPath().lastSegment().compareTo(BIND_FRAG) == 0) {
                    packageMap.put(el.getElementName(), (IPackageFragment) el);
                }
            }
        }
    }
    return packageMap;
}

From source file:com.liferay.ide.service.ui.editor.ServiceMethodHyperlinkDetector.java

License:Open Source License

private IMethod getServiceImplMethod(final IMethod method) {
    IMethod retval = null;//w ww  .jav a  2s. c  o m

    try {
        final IJavaElement methodClass = method.getParent();
        final IType methodClassType = method.getDeclaringType();
        final String methodClassName = methodClass.getElementName();

        if (methodClassName.endsWith("Util") && JdtFlags.isPublic(method) && JdtFlags.isStatic(method)) {
            final String packageName = methodClassType.getPackageFragment().getElementName();
            final String baseServiceName = methodClassName.substring(0, methodClassName.length() - 4);
            // as per liferay standard real implementation will be in impl package and Impl suffix
            // e.g. com.example.service.FooUtil.getBar() --> com.example.service.impl.FooImpl.getBar()
            final String fullyQualifiedName = packageName + ".impl." + baseServiceName + "Impl";
            final IType implType = findType(methodClass, fullyQualifiedName);

            if (implType != null) {
                IMethod[] methods = implType.findMethods(method);

                if (CoreUtil.isNullOrEmpty(methods)) {
                    final ITypeHierarchy hierarchy = implType.newSupertypeHierarchy(new NullProgressMonitor());
                    IType currentType = implType;

                    while (retval == null && currentType != null) {
                        methods = currentType.findMethods(method);// match name and arguments

                        if (!CoreUtil.isNullOrEmpty(methods)) {
                            retval = methods[0];
                        } else {
                            currentType = hierarchy.getSuperclass(currentType);
                        }
                    }
                } else {
                    retval = methods[0];
                }
            }
        }
    } catch (Exception e) {
    }

    return retval;
}