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

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

Introduction

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

Prototype

IJavaElement getAncestor(int ancestorType);

Source Link

Document

Returns this Java element or the first ancestor of this element that has the given type.

Usage

From source file:org.grails.ide.eclipse.editor.gsp.search.FindTagReferences.java

License:Open Source License

/**
 * only check for tags if the java element states that 
 * is a field in a taglib/*from w  w  w  .j  av a 2  s. c om*/
 * @param elt
 * @return the tag name if the specification corresponds to a tag, or else null
 */
boolean shouldSearchForTagRefs(IJavaElement elt) {
    // strangely, if the referenced tag is from a class file, then the type is ILocalVariable
    if (elt.getElementType() == IJavaElement.LOCAL_VARIABLE) {
        elt = elt.getParent();
    }
    if (elt.getElementType() == IJavaElement.FIELD) {
        ICompilationUnit unit = (ICompilationUnit) elt.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (unit instanceof GroovyCompilationUnit) {
            if (GrailsWorkspaceCore.isTagLibClass((GroovyCompilationUnit) unit)) {
                tagField = elt;
                tagName = tagField.getElementName();
            }
        } else {
            // could be a built in tag
            IType type = (IType) elt.getAncestor(IJavaElement.TYPE);
            if (type != null && type.isReadOnly() && type.getElementName().endsWith("TagLib")) {
                IPackageFragment frag = (IPackageFragment) elt.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
                if (frag.getElementName().equals("org.codehaus.groovy.grails.plugins.web.taglib")) {
                    tagField = elt;
                    tagName = tagField.getElementName();
                }
            }
        }
    }
    return tagField != null;
}

From source file:org.grails.ide.eclipse.refactoring.rename.ParticipantChangeManager.java

License:Open Source License

public TextChange getTextChangeFor(Object el) {
    if (el instanceof IJavaElement) {
        IJavaElement jel = (IJavaElement) el;
        ICompilationUnit cu = (ICompilationUnit) jel.getAncestor(IJavaElement.COMPILATION_UNIT);
        return getCUChange(cu);
    } else if (el instanceof IFile) {
        return getFileChange((IFile) el);
    }//www . j  ava  2s  .co m
    return null;
}

From source file:org.grails.ide.eclipse.refactoring.rename.type.ServiceReferenceUpdater.java

License:Open Source License

@Override
public void createChanges(final ParticipantChangeManager changes, final RefactoringStatus status,
        IProgressMonitor pm) {//from  ww w  .  j  av  a2  s.com
    Assert.isNotNull(changes);
    try {
        IJavaSearchScope scope = RefactoringUtils.getSearchScope(project.getJavaProject());
        SearchEngine engine = new SearchEngine();

        final String fieldName = GrailsNameUtils.getPropertyName(renaming.getTarget().getFullyQualifiedName());
        final String fieldNewName = GrailsNameUtils.getPropertyName(renaming.getNewName());

        SearchPattern fieldByNamePat = SearchPattern.createPattern(fieldName, IJavaSearchConstants.FIELD,
                IJavaSearchConstants.ALL_OCCURRENCES,
                SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

        SearchRequestor req = new SearchRequestor() {
            @Override
            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                try {
                    if (match instanceof FieldDeclarationMatch || match instanceof FieldReferenceMatch) {
                        Object el = match.getElement();
                        if (el instanceof IJavaElement) {
                            IJavaElement jel = (IJavaElement) el;
                            ICompilationUnit cu = (ICompilationUnit) jel
                                    .getAncestor(IJavaElement.COMPILATION_UNIT);
                            if (cu != null) {
                                TextChange cuChange = changes.getCUChange(cu);
                                final int offset = match.getOffset();
                                final int length = match.getLength();
                                String text = cu.getBuffer().getText(offset, length);
                                if (text.equals(fieldName)) {
                                    //Only perform the edit if the text we are about to replace is what we expect!
                                    cuChange.addEdit(new ReplaceEdit(offset, length, fieldNewName));
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    //Ignore this match and log the exception...
                    //but keep processing other matches!
                    GrailsCoreActivator.log(e);
                }
            }

        };
        engine.search(fieldByNamePat, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                scope, req, pm);
    } catch (CoreException e) {
        GrailsCoreActivator.log(e);
    }
}

From source file:org.grails.ide.eclipse.ui.internal.launch.GrailsTestLaunchShortcut.java

License:Open Source License

@Override
protected String getScriptFor(IResource resource) {
    if (GrailsResourceUtil.isTestFolder(resource)) {
        String script = TEST_APP + " -" + resource.getName();
        System.out.println("grails command = " + script);
        return script;
    } else {//from  w  w  w .jav a  2  s  . co m
        String script = TEST_APP;
        String testType = GrailsResourceUtil.typeOfTest(resource);
        if (testType != null) {
            script += " -" + testType;
        }
        if (GrailsResourceUtil.isSourceFile(resource)) {
            IJavaElement javaElement = JavaCore.create(resource);
            if (javaElement != null) {
                int elementType = javaElement.getElementType();
                switch (elementType) {
                case IJavaElement.PACKAGE_FRAGMENT:
                    IPackageFragment pkg = (IPackageFragment) javaElement;
                    script += " " + pkg.getElementName() + ".*";
                    break;
                case IJavaElement.COMPILATION_UNIT:
                    String pathIncludingSourceFolder = resource.getProjectRelativePath().toString();
                    IPackageFragmentRoot sourceRoot = (IPackageFragmentRoot) javaElement
                            .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
                    String sourceFolderPath = sourceRoot.getResource().getProjectRelativePath().toString();
                    Assert.isTrue(pathIncludingSourceFolder.startsWith(sourceFolderPath + "/"));
                    String pathWithoutSourceFolder = pathIncludingSourceFolder
                            .substring(sourceFolderPath.length() + 1);
                    if (isRecentGrails(resource.getProject())) {
                        pathWithoutSourceFolder = removeSuffix(pathWithoutSourceFolder, ".groovy");
                    } else {
                        pathWithoutSourceFolder = removeSuffix(pathWithoutSourceFolder, "Test.groovy",
                                "Tests.groovy", ".groovy");
                    }
                    if (pathWithoutSourceFolder != null) {
                        String testTarget = pathWithoutSourceFolder.replace('/', '.');
                        script += " " + testTarget;
                    }
                default:
                    break;
                }
            }
        }
        debug("grails command = " + script);
        return script;
    }
}

From source file:org.granite.builder.util.ProjectUtil.java

License:Open Source License

public static JavaClassInfo getJavaClassInfo(IJavaProject project, IFile resource) throws CoreException {
    // classPath = "<project name>/<output folder>/<package>/<file>.class"
    IPath classPath = resource.getFullPath().makeRelative();

    // Find output folder: "<project name>/<output folder>".
    IPath outputFolder = null;// ww  w. ja va 2s .  co m
    if (project.getOutputLocation() != null && project.getOutputLocation().isPrefixOf(classPath))
        outputFolder = project.getOutputLocation();
    else {
        for (IClasspathEntry cpe : project.getRawClasspath()) {
            if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath output = cpe.getOutputLocation();
                if (output != null && output.isPrefixOf(classPath)) {
                    outputFolder = output;
                    break;
                }
            }
        }
    }

    if (outputFolder == null)
        return null;

    // Compute class name.
    IPath relativeClassPath = classPath.removeFirstSegments(outputFolder.segmentCount());
    IPath relativeClassName = relativeClassPath.removeFileExtension();
    String className = relativeClassName.toPortableString().replace('/', '.');

    // Compute java source path: "<package>/<class name>[$<inner class>].java".
    String javaFullPath = relativeClassName.addFileExtension("java").toPortableString();
    String javaFilePath = javaFullPath;
    int iDollar = javaFilePath.indexOf('$');
    if (iDollar != -1)
        javaFilePath = javaFilePath.substring(0, iDollar) + ".java";

    IJavaElement javaElement = project.findElement(new Path(javaFilePath));
    if (javaElement == null)
        return null;

    IJavaElement sourceFolder = javaElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
    if (sourceFolder == null)
        return null;

    IPath folderPath = sourceFolder.getPath().makeRelative();
    if (folderPath.segmentCount() > 0)
        folderPath = folderPath.removeFirstSegments(1);

    // Fix issues with project not in the workspace directory.
    outputFolder = project.getProject().getWorkspace().getRoot().findMember(outputFolder).getLocation();

    return new JavaClassInfo(folderPath.toPortableString(), javaFullPath, className,
            new File(outputFolder.toPortableString(), relativeClassPath.toPortableString()));
}

From source file:org.hibernate.eclipse.console.utils.xpl.SelectionHelper.java

License:Open Source License

static public IType getClassFromElement(IJavaElement element) {
    IType classToTest = null;//  w ww .j  av  a 2  s  .  c o  m
    if (element != null) {
        // evaluate the enclosing type
        IType typeInCompUnit = (IType) element.getAncestor(IJavaElement.TYPE);
        if (typeInCompUnit != null) {
            if (typeInCompUnit.getCompilationUnit() != null) {
                classToTest = typeInCompUnit;
            }
        } else {
            ICompilationUnit cu = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null)
                classToTest = cu.findPrimaryType();
            else {
                if (element instanceof IClassFile) {
                    try {
                        IClassFile cf = (IClassFile) element;
                        if (cf.isStructureKnown())
                            classToTest = cf.getType();
                    } catch (JavaModelException e) {
                        HibernateConsolePlugin.getDefault().log(e);
                    }
                }
            }
        }
    }
    return classToTest;
}

From source file:org.jboss.tools.arquillian.ui.internal.wizards.NewArquillianJUnitTestCasePageOne.java

License:Open Source License

/**
 * Initialized the page with the current selection
 * @param selection The selection// www.  j  ava  2  s.c o  m
 */
public void init(IStructuredSelection selection) {
    IJavaElement element = getInitialJavaElement(selection);

    initContainerPage(element);
    initTypePage(element);
    // put default class to test
    if (element != null) {
        IType classToTest = null;
        // evaluate the enclosing type
        IType typeInCompUnit = (IType) element.getAncestor(IJavaElement.TYPE);
        if (typeInCompUnit != null) {
            if (typeInCompUnit.getCompilationUnit() != null) {
                classToTest = typeInCompUnit;
            }
        } else {
            ICompilationUnit cu = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null)
                classToTest = cu.findPrimaryType();
            else {
                if (element instanceof IClassFile) {
                    try {
                        IClassFile cf = (IClassFile) element;
                        if (cf.isStructureKnown())
                            classToTest = cf.getType();
                    } catch (JavaModelException e) {
                        ArquillianUIActivator.log(e);
                    }
                }
            }
        }
        if (classToTest != null) {
            try {
                if (!CoreTestSearchEngine.isTestImplementor(classToTest)) {
                    setClassUnderTest(classToTest.getFullyQualifiedName('.'));
                }
            } catch (JavaModelException e) {
                ArquillianUIActivator.log(e);
            }
        }
    }

    restoreWidgetValues();
    updateStatus(getStatusList());
}

From source file:org.jboss.tools.vscode.java.internal.handlers.CodeLensHandler.java

License:Open Source License

private List<Location> findReferences(IJavaElement element) throws JavaModelException, CoreException {
    SearchPattern pattern = SearchPattern.createPattern(element, IJavaSearchConstants.REFERENCES);
    final List<Location> result = new ArrayList<>();
    SearchEngine engine = new SearchEngine();
    engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
            createSearchScope(), new SearchRequestor() {

                @Override//from   w ww  .j  av a 2  s.co  m
                public void acceptSearchMatch(SearchMatch match) throws CoreException {
                    Object o = match.getElement();
                    if (o instanceof IJavaElement) {
                        IJavaElement element = (IJavaElement) o;
                        ICompilationUnit compilationUnit = (ICompilationUnit) element
                                .getAncestor(IJavaElement.COMPILATION_UNIT);
                        if (compilationUnit == null) {
                            return;
                        }
                        Location location = JDTUtils.toLocation(compilationUnit, match.getOffset(),
                                match.getLength());
                        result.add(location);

                    }

                }
            }, new NullProgressMonitor());

    return result;
}

From source file:org.jboss.tools.vscode.java.internal.handlers.NavigateToDefinitionHandler.java

License:Open Source License

private Location computeDefinitonNavigation(ITypeRoot unit, int line, int column) {
    try {//from w ww.  j av  a 2  s .c  o m
        IJavaElement[] elements = unit.codeSelect(JsonRpcHelpers.toOffset(unit.getBuffer(), line, column), 0);

        if (elements == null || elements.length != 1)
            return null;
        IJavaElement element = elements[0];
        ICompilationUnit compilationUnit = (ICompilationUnit) element
                .getAncestor(IJavaElement.COMPILATION_UNIT);
        IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
        if (compilationUnit != null || (cf != null && cf.getSourceRange() != null)) {
            return JDTUtils.toLocation(element);
        }
        return null;

    } catch (JavaModelException e) {
        JavaLanguageServerPlugin.logException("Problem with codeSelect for" + unit.getElementName(), e);
    }
    return null;
}

From source file:org.jboss.tools.vscode.java.internal.handlers.ReferencesHandler.java

License:Open Source License

@Override
public List<org.jboss.tools.langs.Location> handle(org.jboss.tools.langs.ReferenceParams param) {
    SearchEngine engine = new SearchEngine();

    String uri = param.getTextDocument().getUri();
    if (MODE_SOURCEGRAPH) {
        // SOURCEGRAPH: URI is expected to be in form file:///foo/bar,
        // but we need to construct absolute file URI
        uri = new File(connection.getWorkpaceRoot(), uri.substring(8)).toURI().toString();
    }//  w w w  .j a v  a  2s  .c  o  m

    ITypeRoot unit = JDTUtils.resolveTypeRoot(uri);

    if (unit == null) {
        return null;
    }

    try {
        IJavaElement elementToSearch = findElementAtSelection(unit, param.getPosition().getLine().intValue(),
                param.getPosition().getCharacter().intValue());

        if (elementToSearch == null)
            return Collections.emptyList();

        SearchPattern pattern = SearchPattern.createPattern(elementToSearch, IJavaSearchConstants.REFERENCES);
        List<org.jboss.tools.langs.Location> locations = new ArrayList<org.jboss.tools.langs.Location>();
        engine.search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                createSearchScope(), new SearchRequestor() {

                    @Override
                    public void acceptSearchMatch(SearchMatch match) throws CoreException {
                        Object o = match.getElement();
                        if (o instanceof IJavaElement) {
                            IJavaElement element = (IJavaElement) o;
                            ICompilationUnit compilationUnit = (ICompilationUnit) element
                                    .getAncestor(IJavaElement.COMPILATION_UNIT);
                            Location location = null;
                            if (compilationUnit != null) {
                                location = JDTUtils.toLocation(compilationUnit, match.getOffset(),
                                        match.getLength());
                            } else {
                                IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
                                if (cf != null && cf.getSourceRange() != null) {
                                    location = JDTUtils.toLocation(cf, match.getOffset(), match.getLength());
                                }
                            }
                            if (location != null)
                                if (MODE_SOURCEGRAPH) {
                                    // SOURCEGRAPH: transforming location's URI back from file://WORKSPACE/foo/bar to file:///foo/bar
                                    File file = new File(URI.create(location.getUri()).getPath());
                                    File root = new File(connection.getWorkpaceRoot());
                                    location.setUri("file:///" + root.toPath().relativize(file.toPath())
                                            .toString().replace(File.separatorChar, '/'));
                                }
                            locations.add(location);

                        }

                    }
                }, new NullProgressMonitor());

        return locations;
    } catch (CoreException e) {
        JavaLanguageServerPlugin.logException("Find references failure ", e);
    }
    return null;
}