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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a type. Considers the T_* flags.
 *
 * @param type the element to render//from   w w  w.  j a  v a  2s.c o m
 * @param flags the rendering flags. Flags with names starting with 'T_' are considered.
 */
public void appendTypeLabel(IType type, long flags) {

    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) {
        IPackageFragment pack = type.getPackageFragment();
        if (!pack.isDefaultPackage()) {
            appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
    }
    IJavaElement parent = type.getParent();
    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) {
        IType declaringType = type.getDeclaringType();
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
        int parentType = parent.getElementType();
        if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                || parentType == IJavaElement.INITIALIZER) { // anonymous or local
            appendElementLabel(parent, 0);
            fBuffer.append('.');
        }
    }

    String typeName;
    boolean isAnonymous = false;
    if (type.isLambda()) {
        typeName = "() -> {...}"; //$NON-NLS-1$
        try {
            String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
            if (superInterfaceSignatures.length > 0) {
                typeName = typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]);
            }
        } catch (JavaModelException e) {
            //ignore
        }

    } else {
        typeName = getElementName(type);
        try {
            isAnonymous = type.isAnonymous();
        } catch (JavaModelException e1) {
            // should not happen, but let's play safe:
            isAnonymous = typeName.length() == 0;
        }
        if (isAnonymous) {
            try {
                if (parent instanceof IField && type.isEnum()) {
                    typeName = '{' + JavaElementLabels.ELLIPSIS_STRING + '}';
                } else {
                    String supertypeName = null;
                    String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
                    if (superInterfaceSignatures.length > 0) {
                        supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]);
                    } else {
                        String supertypeSignature = type.getSuperclassTypeSignature();
                        if (supertypeSignature != null) {
                            supertypeName = getSimpleTypeName(type, supertypeSignature);
                        }
                    }
                    if (supertypeName == null) {
                        typeName = JavaUIMessages.JavaElementLabels_anonym;
                    } else {
                        typeName = Messages.format(JavaUIMessages.JavaElementLabels_anonym_type, supertypeName);
                    }
                }
            } catch (JavaModelException e) {
                //ignore
                typeName = JavaUIMessages.JavaElementLabels_anonym;
            }
        }
    }
    fBuffer.append(typeName);

    if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) {
        if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) {
            BindingKey key = new BindingKey(type.getKey());
            if (key.isParameterizedType()) {
                String[] typeArguments = key.getTypeArguments();
                appendTypeArgumentSignaturesLabel(type, typeArguments, flags);
            } else {
                String[] typeParameters = Signature.getTypeParameters(key.toSignature());
                appendTypeParameterSignaturesLabel(typeParameters, flags);
            }
        } else if (type.exists()) {
            try {
                appendTypeParametersLabels(type.getTypeParameters(), flags);
            } catch (JavaModelException e) {
                // ignore
            }
        }
    }

    // category
    if (getFlag(flags, JavaElementLabels.T_CATEGORY) && type.exists()) {
        try {
            appendCategoryLabel(type, flags);
        } catch (JavaModelException e) {
            // ignore
        }
    }

    // post qualification
    if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) {
        int offset = fBuffer.length();
        fBuffer.append(JavaElementLabels.CONCAT_STRING);
        IType declaringType = type.getDeclaringType();
        if (declaringType == null && type.isBinary() && isAnonymous) {
            // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type
            String tqn = type.getTypeQualifiedName();
            int lastDollar = tqn.lastIndexOf('$');
            if (lastDollar != 1) {
                String declaringTypeCF = tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$
                declaringType = type.getPackageFragment().getClassFile(declaringTypeCF).getType();
                try {
                    ISourceRange typeSourceRange = type.getSourceRange();
                    if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) {
                        IJavaElement realParent = declaringType.getTypeRoot()
                                .getElementAt(typeSourceRange.getOffset() - 1);
                        if (realParent != null) {
                            parent = realParent;
                        }
                    }
                } catch (JavaModelException e) {
                    // ignore
                }
            }
        }
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            int parentType = parent.getElementType();
            if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                    || parentType == IJavaElement.INITIALIZER) { // anonymous or local
                fBuffer.append('.');
                appendElementLabel(parent, 0);
            }
        } else {
            appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS);
        }
        //         if (getFlag(flags, JavaElementLabels.COLORIZE)) {
        //            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        //         }
    }
}

From source file:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

/**
 * @param scope/*  w  ww  . j av  a  2  s .  c  o m*/
 * @param monitor
 * @param classSignature
 * @param methodName
 * @param signature
 * @return
 * @throws CoreException
 * @throws InterruptedException
 */
public static IJavaElement searchForMethod(IJavaSearchScope scope, IProgressMonitor monitor,
        String classSignature, String methodName, String signature) throws CoreException, InterruptedException {

    SubProgressMonitor typeMonitor = new SubProgressMonitor(monitor, 100);
    SubProgressMonitor hierarchyMonitor = new SubProgressMonitor(monitor, 100);
    IType foundType = (IType) searchForType(classSignature, scope, typeMonitor);
    if (foundType == null)
        return null;
    boolean isConstructor = false;
    if (methodName.startsWith("<init")) {
        isConstructor = true;
        boolean i = isConstructor;
        boolean isAnonymous = false;
        if (!foundType.exists()) {
            //check anonymity using the dollar sign
            String elementName = foundType.getElementName();
            if (elementName.length() > 0 && Character.isDigit(elementName.charAt(0))) {
                isAnonymous = true;
            }
        } else {
            isAnonymous = foundType.isAnonymous();
        }
        if (isAnonymous) {
            methodName = "";
        } else {
            methodName = foundType.getElementName();
        }
    }
    String[] methodParamTypes = Signature.getParameterTypes(signature);
    IMethod searchMethod = foundType.getMethod(methodName, methodParamTypes);
    IMethod[] methods = foundType.getMethods();
    for (IMethod checkMethod : methods) {
        if (isSimilar(searchMethod, checkMethod)) {
            return checkMethod;
        }
    }
    return searchMethod;
}

From source file:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

private static IJavaElement searchForType(String classSignature, IJavaSearchScope scope,
        IProgressMonitor monitor) throws CoreException, InterruptedException {
    try {//from w w  w.j av  a  2  s  .c  o  m
        synchronized (cachedTypes) {
            IType found = cachedTypes.get(classSignature);
            if (found != null) {
                return found;
            }
            SearchEngine engine = new SearchEngine();
            SearchPattern pattern = null;
            SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
            LocalSearchRequestor requestor = new LocalSearchRequestor();
            pattern = SearchPattern.createPattern(classSignature.replace('$', '.'), IJavaSearchConstants.CLASS,
                    IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

            engine.search(pattern, new SearchParticipant[] { participant }, scope, requestor, monitor);
            if (requestor.matches.size() > 0) {
                found = (IType) requestor.matches.get(0).getElement();
                if (found.getFullyQualifiedName().equals(classSignature)) {
                    cachedTypes.put(classSignature, found);
                    return found;
                }

            }
            String[] className = classSignature.split("\\$");
            found = cachedTypes.get(className[0]);
            if (found == null) {

                //find the class
                pattern = SearchPattern.createPattern(className[0], IJavaSearchConstants.CLASS,
                        IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

                engine.search(pattern, new SearchParticipant[] { participant }, scope, requestor, monitor);
                if (monitor.isCanceled()) {
                    throw new InterruptedException();
                }
                if (requestor.matches.size() > 0) {
                    found = (IType) requestor.matches.get(0).getElement();
                    if (found.getFullyQualifiedName().equals(classSignature)) {
                        for (SearchMatch match : requestor.matches) {
                            IType temp = (IType) match.getElement();
                            if (temp.getTypeRoot() instanceof ICompilationUnit) {
                                //prefer source types.
                                found = temp;
                                break;
                            }
                        }
                        if (cachedTypes.size() > 100) {
                            cachedTypes.clear();
                        }
                        cachedTypes.put(className[0], found);
                    } else {
                        found = null;
                    }
                }
            }
            if (found == null)
                return null;
            StringBuilder childTypeName = new StringBuilder();
            childTypeName.append(className[0]);
            //check each of the indexes for the sub-types
            for (int i = 1; i < className.length; i++) {
                childTypeName.append('$');
                childTypeName.append(className[i]);
                IType parent = found;
                found = cachedTypes.get(childTypeName.toString());

                if (found == null) {
                    boolean isAnonymous = false;
                    Integer occurrenceCount = -1;
                    try {
                        occurrenceCount = Integer.parseInt(className[i]);
                        isAnonymous = true;
                    } catch (NumberFormatException e) {
                        isAnonymous = false;
                    }
                    if (isAnonymous) {
                        if (!parent.isBinary()) {
                            found = parent.getType("", occurrenceCount);
                            if (found != null) {
                                if (found.exists()) {
                                    cachedTypes.put(childTypeName.toString(), found);
                                    continue;
                                } else {
                                    found = null;
                                }
                            }
                        } else {
                            //if it is a binary type, there is no hope for 
                            //finding an anonymous inner class. Use the number
                            //as the type name, and cache the handle.
                            found = parent.getType(className[i]);
                            cachedTypes.put(childTypeName.toString(), found);
                            continue;
                        }
                    }
                    ArrayList<IType> childTypes = new ArrayList<IType>();
                    LinkedList<IJavaElement> children = new LinkedList<IJavaElement>();
                    children.addAll(Arrays.asList(parent.getChildren()));
                    while (children.size() > 0) {
                        IJavaElement child = children.removeFirst();
                        if (child instanceof IType) {
                            childTypes.add((IType) child);
                        } else if (child instanceof IMember) {
                            children.addAll(Arrays.asList(((IMember) child).getChildren()));
                        }
                    }
                    int numIndex = 0;
                    while (numIndex < className[i].length()
                            && Character.isDigit(className[i].charAt(numIndex))) {
                        numIndex++;
                    }
                    String name = className[i];
                    try {
                        //get a number at the beginning to find out if 
                        //there is an occurrence count
                        if (numIndex <= name.length()) {
                            occurrenceCount = parseInt(name.substring(0, numIndex));
                            if (occurrenceCount == null) {
                                occurrenceCount = 1;
                            }
                            if (numIndex < name.length() - 1) {
                                name = name.substring(numIndex);
                            } else {
                                name = "";
                            }
                        }
                        for (IType childType : childTypes) {
                            if ("".equals(name)) {
                                if (childType.getOccurrenceCount() == occurrenceCount) {
                                    found = childType;
                                    break;
                                }
                            } else {
                                if (name.equals(childType.getElementName())
                                        && childType.getOccurrenceCount() == occurrenceCount) {
                                    found = childType;
                                    break;
                                }
                            }
                        }
                        if (found == null) {
                            if ("".equals(name)) {
                                found = parent.getTypeRoot().getJavaProject().findType(classSignature);
                                //found = parent.getType("" + occurrenceCount);
                            } else {
                                found = parent.getType(name, occurrenceCount);
                            }
                        }
                        cachedTypes.put(childTypeName.toString(), found);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
            return found;
        }
    } catch (Exception e) {
        SketchPlugin.getDefault().log(e);
        return null;
    }
}

From source file:ca.uwaterloo.gsd.wpi.code.WpiMappingInterpreter.java

License:Open Source License

public boolean createChildrenForQueryFeature(EObject element, EReference feature, EClass concreteChildType,
        EStructuralFeature queryFeature, IProgressMonitor progressMonitor) throws FSMLMappingException {
    EObject classElement = FSMLEcoreUtil.retrieveContextElement(element, JavaMappingInterpreter.CONTEXT_CLASS);
    IType type = (IType) getContext(classElement, IType.class, true);

    EObject projectElement = FSMLEcoreUtil.retrieveContextElement(classElement,
            JavaMappingInterpreter.CONTEXT_PROJECT);
    IJavaProject project = (IJavaProject) getContext(projectElement, IJavaProject.class, true);

    EAnnotation annotation = queryFeature.getEAnnotation(QUERY_EDITOR_CONTRIBUTOR);
    if (annotation != null) {
        PluginXmlQueryResult result = retrievePluginElement("org.eclipse.ui.editors", "editor", project, type,
                false);//from   w w w .  j a va2  s.co m
        if (result != null) {
            IPluginElement pluginElement = result.getElement();
            IPluginAttribute attr = pluginElement.getAttribute("contributorClass");
            if (attr != null) {
                String contributorName = attr.getValue();

                IType contributorType;
                try {
                    contributorType = project.findType(contributorName);
                } catch (JavaModelException e) {
                    e.printStackTrace();
                    return false;
                }

                if (contributorType != null && contributorType.exists()) {
                    if (!feature.isMany()) {
                        EObject child = EcoreUtil.create(concreteChildType);

                        associateContext(child, contributorType);

                        element.eSet(feature, child);
                        child.eSet(queryFeature, contributorName);

                        if (Queries.INSTANCE.reverseFeatureRepresentedAsClass(child, progressMonitor)) {
                            Stats.INSTANCE.logFeatureInstance(element, feature, annotation);
                            Stats.INSTANCE.logScatteringAndTangling(element, feature, null, "plugin.xml");
                            Stats.INSTANCE.logScatteringAndTangling(element, feature, null, "<editor>()");
                            return true;
                        }
                    }
                }
            }
        }
    }
    return false;
}

From source file:ch.qos.logback.beagle.util.EditorUtil.java

License:Open Source License

private static IType findType(IJavaProject jproject, String fullyQualifiedName) throws JavaModelException {
    IType type = jproject.findType(fullyQualifiedName);
    if (type != null)
        return type;
    IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        IPackageFragmentRoot root = roots[i];
        type = findType(root, fullyQualifiedName);
        if (type != null && type.exists())
            return type;
    }/*from ww  w  .j a  va 2 s  .  c om*/
    return null;
}

From source file:ch.qos.logback.beagle.util.EditorUtil.java

License:Open Source License

private static IType findType(IPackageFragmentRoot root, String fullyQualifiedName) throws JavaModelException {
    IJavaElement[] children = root.getChildren();
    for (int i = 0; i < children.length; i++) {
        IJavaElement element = children[i];
        if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
            IPackageFragment pack = (IPackageFragment) element;
            if (!fullyQualifiedName.startsWith(pack.getElementName()))
                continue;
            IType type = findType(pack, fullyQualifiedName);
            if (type != null && type.exists())
                return type;
        }//w  w w  .  j a v  a  2 s  . co  m
    }
    return null;
}

From source file:ch.qos.logback.beagle.util.EditorUtil.java

License:Open Source License

private static IType findType(IPackageFragment pack, String fullyQualifiedName) throws JavaModelException {
    ICompilationUnit[] cus = pack.getCompilationUnits();
    for (int i = 0; i < cus.length; i++) {
        ICompilationUnit unit = cus[i];/*  w ww  .  j av a2s. c o  m*/
        IType type = findType(unit, fullyQualifiedName);
        if (type != null && type.exists())
            return type;
    }
    return null;
}

From source file:com.amashchenko.eclipse.strutsclipse.ProjectUtil.java

License:Apache License

public static IType findClass(final IDocument document, final String className) {
    IType result = null;//  w ww. java  2  s . c o m
    try {
        IJavaProject javaProject = getCurrentJavaProject(document);
        if (javaProject != null && javaProject.exists()) {
            IType type = javaProject.findType(className);
            if (type != null && type.exists()) {
                result = type;
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.descriptors.CustomViewDescriptorService.java

License:Open Source License

/**
 * Returns the {@link ViewElementDescriptor} for a particular project/class when the
 * fully qualified class name actually matches a class from the given project.
 * <p/>// w ww  . j  av a  2  s.  c  o m
 * Custom descriptors are created as needed.
 * <p/>
 * If it is the first time the {@link ViewElementDescriptor} is requested, the method
 * will check that the specified class is in fact a custom View class. Once this is
 * established, a monitoring for that particular class is initiated. Any change will
 * trigger a notification to the {@link ICustomViewDescriptorListener}.
 *
 * @param project the project containing the class.
 * @param fqcn the fully qualified name of the class.
 * @return a {@link ViewElementDescriptor} or <code>null</code> if the class was not
 *         a custom View class.
 */
public ViewElementDescriptor getDescriptor(IProject project, String fqcn) {
    // look in the map first
    synchronized (mCustomDescriptorMap) {
        HashMap<String, ViewElementDescriptor> map = mCustomDescriptorMap.get(project);

        if (map != null) {
            ViewElementDescriptor descriptor = map.get(fqcn);
            if (descriptor != null) {
                return descriptor;
            }
        }

        // if we step here, it looks like we haven't created it yet.
        // First lets check this is in fact a valid type in the project

        try {
            // We expect the project to be both opened and of java type (since it's an android
            // project), so we can create a IJavaProject object from our IProject.
            IJavaProject javaProject = JavaCore.create(project);

            // replace $ by . in the class name
            String javaClassName = fqcn.replaceAll("\\$", "\\."); //$NON-NLS-1$ //$NON-NLS-2$

            // look for the IType object for this class
            IType type = javaProject.findType(javaClassName);
            if (type != null && type.exists()) {
                // the type exists. Let's get the parent class and its ViewClassInfo.

                // get the type hierarchy
                ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());

                ViewElementDescriptor parentDescriptor = createViewDescriptor(hierarchy.getSuperclass(type),
                        project, hierarchy);

                if (parentDescriptor != null) {
                    // we have a valid parent, lets create a new ViewElementDescriptor.
                    List<AttributeDescriptor> attrList = new ArrayList<AttributeDescriptor>();
                    List<AttributeDescriptor> paramList = new ArrayList<AttributeDescriptor>();
                    Map<ResourceFile, Long> files = findCustomDescriptors(project, type, attrList, paramList);

                    AttributeDescriptor[] attributes = getAttributeDescriptor(type, parentDescriptor);
                    if (!attrList.isEmpty()) {
                        attributes = join(attrList, attributes);
                    }
                    AttributeDescriptor[] layoutAttributes = getLayoutAttributeDescriptors(type,
                            parentDescriptor);
                    if (!paramList.isEmpty()) {
                        layoutAttributes = join(paramList, layoutAttributes);
                    }
                    String name = DescriptorsUtils.getBasename(fqcn);
                    ViewElementDescriptor descriptor = new CustomViewDescriptor(name, fqcn, attributes,
                            layoutAttributes, parentDescriptor.getChildren(), project, files);
                    descriptor.setSuperClass(parentDescriptor);

                    synchronized (mCustomDescriptorMap) {
                        map = mCustomDescriptorMap.get(project);
                        if (map == null) {
                            map = new HashMap<String, ViewElementDescriptor>();
                            mCustomDescriptorMap.put(project, map);
                        }

                        map.put(fqcn, descriptor);
                    }

                    //TODO setup listener on this resource change.

                    return descriptor;
                }
            }
        } catch (JavaModelException e) {
            // there was an error accessing any of the IType, we'll just return null;
        }
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.launch.junit.AndroidJUnitPropertyTester.java

License:Open Source License

/**
 * Return whether the target resource is a JUnit test.
 *//*from   w  w  w  .  ja v  a2 s . c  o  m*/
private boolean isJUnitTest(IJavaElement element) {
    try {
        IType testType = null;
        if (element instanceof ICompilationUnit) {
            testType = (((ICompilationUnit) element)).findPrimaryType();
        } else if (element instanceof IClassFile) {
            testType = (((IClassFile) element)).getType();
        } else if (element instanceof IType) {
            testType = (IType) element;
        } else if (element instanceof IMember) {
            testType = ((IMember) element).getDeclaringType();
        }
        if (testType != null && testType.exists()) {
            return TestSearchEngine.isTestOrTestSuite(testType);
        }
    } catch (CoreException e) {
        // ignore, return false
    }
    return false;
}