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.jboss.tools.vscode.java.internal.JDTUtils.java

License:Open Source License

/**
 * Given the uri returns a {@link IClassFile}.
 * May return null if it can not resolve the uri to a
 * library.// w  w w  .  j ava2 s.c  om
 *
 * @see #toLocation(IClassFile, int, int)
 * @param uri with 'jdt' scheme
 * @return class file
 */
public static IClassFile resolveClassFile(String uriString) {
    URI uri = null;
    try {
        uri = new URI(uriString);
    } catch (URISyntaxException e) {
        JavaLanguageServerPlugin.logException("Failed to resolve " + uriString, e);
    }
    if (uri != null && "jdt".equals(uri.getScheme()) && "contents".equals(uri.getAuthority())) {
        String handleId = uri.getQuery();
        IJavaElement element = JavaCore.create(handleId);
        IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
        return cf;
    }
    return null;

}

From source file:org.jboss.tools.vscode.java.internal.JDTUtils.java

License:Open Source License

/**
 * Creates a location for a given java element.
 * Element can be a {@link ICompilationUnit} or {@link IClassFile}
 *
 * @param element//from w w w .  j  a  v a 2  s .c om
 * @return location or null
 * @throws JavaModelException
 */
public static Location toLocation(IJavaElement element) throws JavaModelException {
    ICompilationUnit unit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
    IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE);
    if (unit == null && cf == null) {
        return null;
    }
    if (element instanceof ISourceReference) {
        ISourceRange nameRange = ((ISourceReference) element).getNameRange();
        if (cf == null) {
            return toLocation(unit, nameRange.getOffset(), nameRange.getLength());
        } else {
            return toLocation(cf, nameRange.getOffset(), nameRange.getLength());
        }
    }
    return null;
}

From source file:org.jboss.tools.ws.jaxrs.core.internal.metamodel.builder.JavaElementChangedBuildJob.java

License:Open Source License

protected IStatus run(final IProgressMonitor progressMonitor) {
    final long startTime = new Date().getTime();
    IJavaElement element = null;
    try {//from  w ww . j av a 2 s .c  om
        progressMonitor.beginTask("Building JAX-RS Metamodel", 3 * SCALE);
        progressMonitor.worked(SCALE);
        Logger.debug("Building JAX-RS Metamodel after: {}", event);
        if (progressMonitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }
        // scan and filter delta, retrieve a list of java changes
        final List<JavaElementChangedEvent> affectedJavaElements = new JavaElementDeltaScanner()
                .scanAndFilterEvent(event, new SubProgressMonitor(progressMonitor, SCALE));
        if (affectedJavaElements.isEmpty()) {
            Logger.debug("* No relevant affected element to process *");
            return Status.OK_STATUS;
        }
        if (progressMonitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }
        for (JavaElementChangedEvent delta : affectedJavaElements) {
            element = delta.getElement();
            final IJavaProject javaProject = element.getJavaProject();
            final JaxrsMetamodel metamodel = JaxrsMetamodelLocator.get(javaProject, true);
            // prevent NPE when opening a closed project (ie, there's no metamodel yet).
            if (metamodel != null) {
                try {
                    metamodel.processJavaElementChange(delta, progressMonitor);
                    if (progressMonitor.isCanceled()) {
                        return Status.CANCEL_STATUS;
                    }
                } catch (Exception e) {
                    final IStatus status = Logger.error("Failed to build or refresh the JAX-RS metamodel", e);
                    metamodel.setBuildStatus(status);
                    return status;
                } finally {
                    if (Logger.isDebugEnabled()) {
                        Logger.debug(metamodel.getStatus());
                    }
                }
            }
        }
    } catch (Exception e) {
        Logger.error("Failed to process Java element change", e);
        if (element != null) {
            return new Status(IStatus.ERROR, JBossJaxrsCorePlugin.PLUGIN_ID,
                    "Failed to build or refresh the JAX-RS metamodel while processing "
                            + element.getElementName() + " in project "
                            + element.getAncestor(IJavaElement.JAVA_PROJECT).getElementName(),
                    e);
        } else {
            return new Status(IStatus.ERROR, JBossJaxrsCorePlugin.PLUGIN_ID,
                    "Failed to build or refresh the JAX-RS metamodel while processing a change in the Java Model",
                    e);
        }
    } finally {
        progressMonitor.done();
        long endTime = new Date().getTime();
        if (Logger.isDebugEnabled()) {
            Logger.debug("Java element changes processed in {} ms.", (endTime - startTime));
        }

    }
    return Status.OK_STATUS;
}

From source file:org.jboss.tools.ws.jaxrs.core.internal.metamodel.builder.JavaElementChangedBuildTask.java

License:Open Source License

public IStatus execute(final IProgressMonitor progressMonitor) {
    final long startTime = new Date().getTime();
    IJavaElement element = null;
    try {/*from  ww  w  .ja  va2  s .c  o m*/
        progressMonitor.beginTask("Building JAX-RS Metamodel", 3 * SCALE);
        progressMonitor.worked(SCALE);
        Logger.debug("Building JAX-RS Metamodel after: {}", event);
        if (progressMonitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }
        // scan and filter delta, retrieve a list of java changes
        final List<JavaElementChangedEvent> affectedJavaElements = new JavaElementDeltaScanner()
                .scanAndFilterEvent(event, new SubProgressMonitor(progressMonitor, SCALE));
        if (affectedJavaElements.isEmpty()) {
            Logger.debug("* No relevant affected element to process *");
            return Status.OK_STATUS;
        }
        if (progressMonitor.isCanceled()) {
            return Status.CANCEL_STATUS;
        }
        for (JavaElementChangedEvent delta : affectedJavaElements) {
            element = delta.getElement();
            final IJavaProject javaProject = element.getJavaProject();
            final JaxrsMetamodel metamodel = JaxrsMetamodelLocator.get(javaProject, true);
            // prevent NPE when opening a closed project (ie, there's no metamodel yet).
            if (metamodel != null) {
                try {
                    metamodel.processJavaElementChange(delta, progressMonitor);
                    if (progressMonitor.isCanceled()) {
                        return Status.CANCEL_STATUS;
                    }
                } catch (Throwable e) {
                    final IStatus status = Logger.error("Failed to build or refresh the JAX-RS metamodel", e);
                    metamodel.setBuildStatus(status);
                    return status;
                } finally {
                    if (Logger.isDebugEnabled()) {
                        Logger.debug(metamodel.getStatus());
                    }
                }
            }
        }
    } catch (Exception e) {
        if (element != null) {
            return new Status(IStatus.ERROR, JBossJaxrsCorePlugin.PLUGIN_ID,
                    "Failed to build or refresh the JAX-RS metamodel while processing "
                            + element.getElementName() + " in project "
                            + element.getAncestor(IJavaElement.JAVA_PROJECT).getElementName(),
                    e);
        } else {
            return new Status(IStatus.ERROR, JBossJaxrsCorePlugin.PLUGIN_ID,
                    "Failed to build or refresh the JAX-RS metamodel while processing a change in the Java Model",
                    e);
        }
    } finally {
        progressMonitor.done();
        long endTime = new Date().getTime();
        if (Logger.isDebugEnabled()) {
            Logger.debug("Java element changes processed in {} ms.", (endTime - startTime));
        }

    }
    return Status.OK_STATUS;
}

From source file:org.jboss.tools.ws.jaxrs.core.jdt.JdtUtils.java

License:Open Source License

/**
 * Returns the closest Java Element of the expected type that surrounds the
 * given location in the given compilationUnit. This method can return
 * SimpleAnnotation, which the default JDT ICompilationUnit implementation
 * does not support./*from w  w  w  . j  a  v a2 s .  co m*/
 * 
 * @param sourceRange
 * @param location
 * @param type
 * @return
 * @throws JavaModelException
 */
public static IJavaElement getElementAt(ICompilationUnit compilationUnit, int location, int type)
        throws JavaModelException {
    final IJavaElement element = getElementAt(compilationUnit, location);
    if (element != null && element.exists()) {
        return element.getAncestor(type);
    }
    return null;
}

From source file:org.jboss.tools.ws.jaxrs.ui.navigation.JaxrsNameBindingHyperlinkDetector.java

License:Open Source License

/**
 * (non-Javadoc)//  www  .  j a  v a 2  s. c om
 * 
 * @see org.eclipse.jface.text.hyperlink.IHyperlinkDetector#detectHyperlinks(org.eclipse.jface.text.ITextViewer,
 *      org.eclipse.jface.text.IRegion, boolean)
 */
@Override
public IHyperlink[] detectHyperlinks(final ITextViewer textViewer, final IRegion region,
        final boolean canShowMultipleHyperlinks) {
    final ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
    if (region == null || !(textEditor instanceof JavaEditor)) {
        return null;
    }
    final int offset = region.getOffset();
    final IJavaElement input = EditorUtility.getActiveEditorJavaInput();
    if (input == null) {
        return null;
    }
    final JaxrsMetamodel metamodel = getMetamodel(input);
    if (metamodel == null) {
        return null;
    }
    final IRegion wordRegion = getCurrentWordRegion(textEditor, offset);
    if (wordRegion == null || wordRegion.getLength() == 0) {
        return null;
    }
    final IJavaElement[] selectedJavaElements = getSelectedElements(input, wordRegion);

    final List<IJaxrsJavaElement> targets = findTargets(metamodel, selectedJavaElements,
            (ICompilationUnit) input.getAncestor(IJavaElement.COMPILATION_UNIT));
    if (targets != null && !targets.isEmpty()) {
        final IHyperlink[] result = new IHyperlink[targets.size()];
        for (int i = 0; i < targets.size(); i++) {
            result[i] = new JaxrsNameBindingAnnotationHyperlink(targets.get(i), wordRegion);
        }
        return result;
    }
    return null;

}

From source file:org.jboss.tools.ws.jaxrs.ui.navigation.JaxrsNameBindingHyperlinkDetector.java

License:Open Source License

/**
 * If the given selectedJavaElement match a custom Name Binding annotation
 * defined in the given {@link JaxrsMetamodel}, then return the list of
 * associated elements with this name binding.
 * //ww w.  ja v a2s  .  c o  m
 * @param metamodel
 *            the JAX-RS Metamodel associated with the given element in the
 *            current text editor
 * @param selectedJavaElements
 *            the selected java elements
 * @param currentCompilationUnit
 *            the {@link ICompilationUnit} opened in the current text editor
 * @return the list of target {@link IJavaElement} or empty list if none
 *         match.
 */
private List<IJaxrsJavaElement> findTargets(final JaxrsMetamodel metamodel,
        final IJavaElement[] selectedJavaElements, final ICompilationUnit currentCompilationUnit) {
    final List<IJaxrsJavaElement> targetElements = new ArrayList<IJaxrsJavaElement>();
    for (IJavaElement selectedJavaElement : selectedJavaElements) {
        final IJaxrsElement associatedJaxrsElement = metamodel.findElement(selectedJavaElement);
        if (associatedJaxrsElement != null
                && associatedJaxrsElement.getElementKind() == EnumElementKind.NAME_BINDING) {
            final JaxrsNameBinding nameBinding = (JaxrsNameBinding) associatedJaxrsElement;
            final Collection<IJaxrsElement> matchingElements = metamodel
                    .findElementsByAnnotation(nameBinding.getJavaClassName());
            for (IJaxrsElement matchingElement : matchingElements) {
                final IJavaElement matchingJavaElement = ((IJaxrsJavaElement) matchingElement).getJavaElement();
                // skip if the matching/target Java element is part of the current compilation unit
                if (!matchingJavaElement.getAncestor(IJavaElement.COMPILATION_UNIT)
                        .equals(currentCompilationUnit)) {
                    targetElements.add((IJaxrsJavaElement) matchingElement);
                }
            }
        }
    }
    return targetElements;
}

From source file:org.jnario.spec.ui.wizards.NewSpecWizardPageOne.java

License:Open Source License

public void init(IStructuredSelection selection) {
    IJavaElement element = getInitialJavaElement(selection);

    initContainerPage(element);//from w  w  w  .  j  av  a2 s . c  o m
    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) {
                        JUnitPlugin.log(e);
                    }
                }
            }
        }
        if (classToTest != null) {
            try {
                if (!CoreTestSearchEngine.isTestImplementor(classToTest)) {
                    setClassUnderTest(classToTest.getFullyQualifiedName('.'));
                }
            } catch (JavaModelException e) {
                JUnitPlugin.log(e);
            }
        }
    }

    updateStatus(getStatusList());
}

From source file:org.python.pydev.editor.codecompletion.revisited.javaintegration.JavaProjectModulesManager.java

License:Open Source License

/**
 * @param dontSearchInit: not applicable for this method (ignored)
 * @return the module that corresponds to the passed name.
 *//*from  www.j  a v a  2s. c om*/
public IModule getModuleInDirectManager(String name, IPythonNature nature, boolean dontSearchInit) {
    if (DEBUG_GET_MODULE) {
        System.out.println("Trying to get module in java project modules manager: " + name);
    }
    if (name.startsWith(".")) { //this happens when looking for a relative import
        return null;
    }
    try {
        IJavaElement javaElement = this.javaProject.findType(name);
        if (javaElement == null) {
            javaElement = this.javaProject.findElement(new Path(name.replace('.', '/')));
        }

        if (DEBUG_GET_MODULE) {
            System.out.println("Found: " + javaElement);
        }

        if (javaElement != null) {

            //now, there's a catch here, we'll find any class in the project classpath, even if it's in the
            //global classpath (e.g.: rt.jar), and this shouldn't be treated in this project modules manager
            //(that's treated in the Jython system manager)
            IJavaElement ancestor = javaElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
            if (ancestor instanceof IPackageFragmentRoot) {
                IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) ancestor;
                IClasspathEntry rawClasspathEntry = packageFragmentRoot.getRawClasspathEntry();
                if (rawClasspathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                    return null;
                }
            }
            return new JavaModuleInProject(name, this.javaProject);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.seasar.s2junit4plugin.wizard.NewS2JUnit4TestCaseWizardPageOne.java

License:Apache License

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

    try {
        String mainTestPath = PreferenceStoreUtil.getPreferenceStoreOfWorkspace()
                .getString(Constants.PREF_TEST_JAVA_PATH);
        IJavaProject javaProject = element.getJavaProject();
        IFolder folder = javaProject.getProject().getFolder(mainTestPath);
        if (folder.exists()) {
            IPackageFragmentRoot findPackageFragmentRoot = javaProject
                    .findPackageFragmentRoot(folder.getFullPath());
            setPackageFragmentRoot(findPackageFragmentRoot, true);
        } else {
            initContainerPage(element);
        }
    } catch (JavaModelException e) {
        Logger.error(e, this);
    }
    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) {
                        Logger.error(e, this);
                    }
                }
            }
        }
        if (classToTest != null) {
            try {
                if (!TestSearchEngine.isTestImplementor(classToTest)) {
                    setClassUnderTest(classToTest.getFullyQualifiedName('.'));
                }
            } catch (JavaModelException e) {
                Logger.error(e, this);
            }
        }
    }

    restoreWidgetValues();

    boolean isJunit4 = false;
    //      if (element != null && element.getElementType() != IJavaElement.JAVA_MODEL) {
    //         IJavaProject project= element.getJavaProject();
    //         try {
    //            isJunit4= project.findType(JUnitPlugin.JUNIT4_ANNOTATION_NAME) != null;
    //         } catch (JavaModelException e) {
    //            // ignore
    //         }
    //      }
    if (store.getString(Constants.PREF_TEST_GENERATION_TYPE)
            .equals(org.seasar.s2junit4plugin.Messages.getString("Preference.JUnit4"))) {
        isJunit4 = true;
    }
    setJUnit4(isJunit4, true);

    boolean isS2Junit4 = false;
    //      if (element != null && element.getElementType() != IJavaElement.JAVA_MODEL) {
    //         IJavaProject project= element.getJavaProject();
    //         try {
    //            isS2Junit4= project.findType("org.seasar.framework.unit.Seasar2") != null;
    //         } catch (JavaModelException e) {
    //            // ignore
    //         }
    //      }
    if (store.getString(Constants.PREF_TEST_GENERATION_TYPE)
            .equals(org.seasar.s2junit4plugin.Messages.getString("Preference.S2JUnit4"))) {
        isS2Junit4 = true;
    }
    setS2JUnit4(isS2Junit4, true);

    updateStatus(getStatusList());
}