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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.grails.ide.eclipse.test.gsp.GSPHyperlinkTests.java

License:Open Source License

private void assertHyperlink(String contents, int offset, String elementName, boolean isBinary)
        throws Exception {
    String fileName = "grails-app/views/nuthin/foo.gsp";
    IFile file = testProject.getProject().getFile(new Path(fileName));
    if (!file.exists()) {
        file = testProject.createFile(fileName, contents);
        waitForIndexes();/*from  w  w  w .j a  v  a 2 s  .  c  o  m*/
    }
    IEditorPart part = IDE.openEditor(Workbench.getInstance().getActiveWorkbenchWindow().getActivePage(), file);
    try {
        IHyperlink[] links = detector.detectHyperlinks(((StructuredTextEditor) part).getTextViewer(),
                new Region(offset, 0), true);
        assertNotNull("Should have found one hyperlink", links);
        assertEquals("Should have found one hyperlink", 1, links.length);
        JavaElementHyperlink link = (JavaElementHyperlink) links[0];
        IJavaElement element = link.getElement();
        assertEquals(elementName, element.getElementName());
        assertTrue("Element should exist: " + element, element.exists());
        if (isBinary) {
            assertTrue("Should be read only", element.isReadOnly());
        } else {
            assertFalse("Should be not read only", element.isReadOnly());
        }
        assertTrue("Should have structure known", element.isStructureKnown());
    } finally {
        ((StructuredTextEditor) part).close(false);
    }
}

From source file:org.grails.ide.eclipse.test.gsp.GSPSearchTests.java

License:Open Source License

private void assertMatchesInGSP(String gspContent, IJavaElement elementToSearchFor,
        List<ISourceRange> expectedMatches) throws Exception {
    assertTrue("Element to search for does not exits: " + elementToSearchFor, elementToSearchFor.exists());
    IFile file = testProject.createFile("grails-app/views/some.gsp", gspContent);
    TestGSPRequestor requestor = new TestGSPRequestor(file, elementToSearchFor);
    SearchInGSPs search = new SearchInGSPs();
    search.performSearch(requestor, null);

    assertEquals(expectedMatches, new ArrayList<ISourceRange>(requestor.matches));
}

From source file:org.hibernate.eclipse.console.actions.OpenSourceAction.java

License:Open Source License

/**
 * @param consoleConfig//  w  w w  . jav  a 2s.c om
 * @param selection
 * @param fullyQualifiedName
 * @throws JavaModelException
 * @throws PartInitException
 * @throws FileNotFoundException
 */
public static IEditorPart run(ConsoleConfiguration consoleConfig, Object selection, String fullyQualifiedName)
        throws JavaModelException, PartInitException, FileNotFoundException {
    if (fullyQualifiedName == null) {
        return null;
    }
    IJavaProject[] projs = ProjectUtils.findJavaProjects(consoleConfig);
    String remainder = null;
    IType type = null;
    IJavaProject proj = null;
    if (fullyQualifiedName.indexOf("$") > 0) { //$NON-NLS-1$
        remainder = fullyQualifiedName.substring(fullyQualifiedName.indexOf("$") + 1); //$NON-NLS-1$
        fullyQualifiedName = fullyQualifiedName.substring(0, fullyQualifiedName.indexOf("$")); //$NON-NLS-1$
        for (int i = 0; i < projs.length && type == null; i++) {
            proj = projs[i];
            type = ProjectUtils.findType(proj, fullyQualifiedName);
        }
        while (remainder.indexOf("$") > 0) { //$NON-NLS-1$
            String subtype = remainder.substring(0, fullyQualifiedName.indexOf("$")); //$NON-NLS-1$
            type = type.getType(subtype);
            remainder = remainder.substring(fullyQualifiedName.indexOf("$") + 1); //$NON-NLS-1$
        }
        type = type.getType(remainder);
    } else {
        for (int i = 0; i < projs.length && type == null; i++) {
            proj = projs[i];
            type = ProjectUtils.findType(proj, fullyQualifiedName);
        }
    }
    IJavaElement jElement = null;
    if (selection instanceof IProperty) {
        final String selectionName = ((IProperty) selection).getName();
        final IType typeSave = type;
        while (true) {
            jElement = type.getField(selectionName);
            if (jElement != null && jElement.exists()) {
                break;
            }
            String parentClassName = ProjectUtils.getParentTypename(proj, type.getFullyQualifiedName());
            if (parentClassName == null) {
                break;
            }
            type = ProjectUtils.findType(proj, parentClassName);
            for (int i = 0; i < projs.length && type == null; i++) {
                proj = projs[i];
                type = ProjectUtils.findType(proj, fullyQualifiedName);
            }
            if (type == null) {
                break;
            }
        }
        ;
        // do not find element - restore type
        if (jElement == null || !jElement.exists()) {
            type = typeSave;
        }
    }
    if (jElement == null) {
        jElement = type;
    }
    IEditorPart editorPart = JavaUI.openInEditor(type);
    if (editorPart instanceof JavaEditor) {
        JavaEditor jEditor = (JavaEditor) editorPart;
        selectionToEditor(jElement, jEditor);
    }
    if (editorPart == null) {
        String out = NLS.bind(HibernateConsoleMessages.OpenSourceAction_source_file_for_class_not_found,
                fullyQualifiedName);
        throw new FileNotFoundException(out);
    }
    return editorPart;

}

From source file:org.jboss.tools.arquillian.ui.internal.utils.ArquillianUIUtil.java

License:Open Source License

public static IType getActiveType() {
    IWorkbenchPage page = getActivePage();
    if (page == null) {
        return null;
    }/*from   w w  w .j a  va  2 s .c o  m*/
    IEditorPart editor = page.getActiveEditor();
    if (editor instanceof CompilationUnitEditor) {
        CompilationUnitEditor cue = (CompilationUnitEditor) editor;
        IEditorInput editorInput = cue.getEditorInput();
        if (editorInput == null) {
            return null;
        }
        IJavaElement javaElement = (IJavaElement) editorInput.getAdapter(IJavaElement.class);
        if (javaElement != null && !javaElement.exists())
            return null;
        try {
            ITypeRoot rootType = EditorUtility.getEditorInputJavaElement(editor, true);
            if (rootType != null && rootType.isConsistent()) {
                IJavaElement element = SelectionConverter.getElementAtOffset(cue);
                if (element == null) {
                    return null;
                }
                return SelectionConverter.getTypeAtOffset(cue);
            }
        } catch (JavaModelException e) {
            ArquillianUIActivator.log(e);
        }
    }
    return null;
}

From source file:org.jboss.tools.cdi.internal.core.impl.BeanField.java

License:Open Source License

@Override
public boolean isDeclaredFor(IJavaElement element) {
    if (getField() == element) {
        return true;
    }//from  ww  w  .jav  a2 s.  c  om
    if (element instanceof IField && element.exists() && field.exists()) {
        return element.getElementName().equals(getField().getElementName())
                && ((IField) element).getDeclaringType().getFullyQualifiedName()
                        .equals(getField().getDeclaringType().getFullyQualifiedName());
    }
    return false;
}

From source file:org.jboss.tools.cdi.internal.core.refactoring.CDIMarkerResolutionUtils.java

License:Open Source License

public static void addQualifiersToInjectionPoint(List<ValuedQualifier> deployed, IInjectionPoint injectionPoint,
        ICompilationUnit compilationUnit, MultiTextEdit edit) {
    try {// w w  w .j  av  a2s .  c o m
        IJavaElement element = getInjectedJavaElement(compilationUnit, injectionPoint);
        if (element == null || !element.exists())
            return;

        // delete unneeded qualifiers
        List<IQualifier> toDelete = findQualifiersToDelete(injectionPoint, deployed);

        for (IQualifier qualifier : toDelete) {
            deleteAnnotation(qualifier.getSourceType().getFullyQualifiedName(), compilationUnit, element, edit);
        }

        for (ValuedQualifier declaration : deployed) {
            String qualifierName = declaration.getQualifier().getSourceType().getFullyQualifiedName();
            String value = declaration.getValue();
            if (!qualifierName.equals(CDIConstants.ANY_QUALIFIER_TYPE_NAME)
                    && !qualifierName.equals(CDIConstants.DEFAULT_QUALIFIER_TYPE_NAME)) {
                addQualifier(qualifierName, value, compilationUnit, element, edit);
                updateQualifier(qualifierName, value, compilationUnit, element, edit);
            }
        }
    } catch (CoreException ex) {
        CDICorePlugin.getDefault().logError(ex);
    }

}

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  .ja  v  a 2  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.core.jdt.JdtUtils.java

License:Open Source License

/**
 * Resolves the SourceType Argument for the given parameterizedType against the
 * given matchGenericType that is part of the parameterizedTypeHierarchy.
 * Binding information is obtained from the Java model. This means that the
 * compilation unit must be located relative to the Java model. This happens
 * automatically when the source code comes from either
 * setSource(ICompilationUnit) or setSource(IClassFile). When source is
 * supplied by setSource(char[]), the location must be established
 * explicitly by calling setProject(IJavaProject) and setUnitName(String).
 * Note that the compiler options that affect doc comment checking may also
 * affect whether any bindings are resolved for nodes within doc comments.
 * //  ww w  . ja  va2s  . c  o m
 * Note : the binding resolution on IClassFile requires the
 * 'org.eclipse.jdt.launching' bundle, but Eclipse PDE detects it as an
 * unused dependency.
 * 
 * @param parameterizedType
 *            the parameterized type
 * @param compilationUnit
 *            the DOM CompilationUnit returned by the parse() method. This
 *            operation is expensive and should be performed only once for
 *            each type.
 * @param matchGenericType
 *            the super type
 * @param parameterizedTypeHierarchy
 *            the parameterized type hierarchy
 * @param progressMonitor
 *            a progress monitor (or null)
 * @return a list of fully qualified type names
 * @throws CoreException
 *             the underlying CoreException thrown by the manipulated JDT
 *             APIs
 */
@SuppressWarnings("unchecked")
public static List<IType> resolveTypeArguments(final IType parameterizedType,
        final CompilationUnit compilationUnit, final IType matchGenericType,
        final ITypeHierarchy parameterizedTypeHierarchy, final IProgressMonitor progressMonitor)
        throws CoreException {
    if (compilationUnit == null) {
        Logger.warn("Unable to retrieve the Compilation Unit for type '" + parameterizedType
                + "'. Check the library sources attachement.");
        return null;
    }
    // find path to the matchGenericType (class or interface)
    // ITypeHierarchy parameterizedTypeHierarchy =
    // getTypeHierarchy(parameterizedType, false, progressMonitor);
    List<IType> pathToParameterizedType = new ArrayList<IType>(
            Arrays.asList(parameterizedTypeHierarchy.getAllSubtypes(matchGenericType)));
    // skip the last values as they are the parameterized type and its
    // optionally sub types
    int index = pathToParameterizedType.indexOf(parameterizedType);
    // the generic type does not belong to the parameterized type's
    // hierarchy
    if (index < 0) {
        return null;
    }
    pathToParameterizedType = pathToParameterizedType.subList(0, index);
    // add match/target generic type, as by default it is not included
    // in
    // the result
    pathToParameterizedType.add(0, matchGenericType);
    // reverse the path, for easier comprehension of the code below
    Collections.reverse(pathToParameterizedType);
    List<IType> arguments = null;
    for (TypeDeclaration typeDeclaration : (List<TypeDeclaration>) compilationUnit.types()) {
        // ohoh, everything is resolved with bindings :-)
        ITypeBinding typeBinding = typeDeclaration.resolveBinding();
        if (typeBinding.getJavaElement().equals(parameterizedType)) {
            // locate the matchGenericType declaration...
            for (int i = 0; i < pathToParameterizedType.size(); i++) {
                IType superType = pathToParameterizedType.get(i);
                // lookup in the type's interfaces
                if (superType.isInterface()) {
                    for (ITypeBinding superInterfaceBinding : typeBinding.getInterfaces()) {
                        String superInterfaceErasureQName = superInterfaceBinding.getErasure()
                                .getQualifiedName();
                        if (superInterfaceErasureQName.equals(superType.getFullyQualifiedName())) {
                            typeBinding = superInterfaceBinding;
                            break;
                        }
                    }
                } else {
                    // lookup in type's super class
                    typeBinding = typeBinding.getSuperclass();
                }
            }
            // ... then resolve the type parameters using its bindings
            // resolve in the parameterized type's interfaces
            ITypeBinding[] typeArgBindings = typeBinding.getTypeArguments();
            arguments = new ArrayList<IType>(typeArgBindings.length);
            for (ITypeBinding typeArgBinding : typeArgBindings) {
                Logger.trace("Resolving Java ElementKind for type argument '" + typeArgBinding.getName() + "'");
                IJavaElement javaElement = typeArgBinding.getJavaElement();
                if (javaElement.getElementType() == IJavaElement.TYPE && javaElement.exists()) {
                    arguments.add((IType) javaElement);
                }
            }
        }
    }

    return arguments;
}

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

License:Open Source License

/**
 * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TypeDeclaration)
 *///www.j  av a  2  s. c om
@Override
public boolean visit(AnnotationTypeDeclaration node) {
    final IJavaElement ancestor = javaAnnotation.getAncestor(IJavaElement.TYPE);
    if (ancestor != null && ancestor.exists()
            && ancestor.getElementName().equals(node.getName().getFullyQualifiedName())) {
        // keep searching
        return true;
    }
    // wrong path, stop searching from this branch of the AST
    return false;
}

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

License:Open Source License

/**
 * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TypeDeclaration)
 *///from w w w.j  a v  a2  s  .  c o  m
@Override
public boolean visit(TypeDeclaration node) {
    final IJavaElement ancestor = javaAnnotation.getAncestor(IJavaElement.TYPE);
    if (ancestor != null && ancestor.exists()
            && ancestor.getElementName().equals(node.getName().getFullyQualifiedName())) {
        // keep searching
        return true;
    }
    // wrong path, stop searching from this branch of the AST
    return false;
}