Example usage for org.eclipse.jdt.core ITypeHierarchy contains

List of usage examples for org.eclipse.jdt.core ITypeHierarchy contains

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ITypeHierarchy contains.

Prototype

boolean contains(IType type);

Source Link

Document

Returns whether the given type is part of this hierarchy.

Usage

From source file:at.bestsolution.fxide.jdt.corext.util.SuperTypeHierarchyCache.java

License:Open Source License

private static void addTypeHierarchyToCache(ITypeHierarchy hierarchy) {
    synchronized (fgHierarchyCache) {
        int nEntries = fgHierarchyCache.size();
        if (nEntries >= CACHE_SIZE) {
            // find obsolete entries or remove entry that was least recently accessed
            HierarchyCacheEntry oldest = null;
            ArrayList<HierarchyCacheEntry> obsoleteHierarchies = new ArrayList<>(CACHE_SIZE);
            for (int i = 0; i < nEntries; i++) {
                HierarchyCacheEntry entry = fgHierarchyCache.get(i);
                ITypeHierarchy curr = entry.getTypeHierarchy();
                if (!curr.exists() || hierarchy.contains(curr.getType())) {
                    obsoleteHierarchies.add(entry);
                } else {
                    if (oldest == null || entry.getLastAccess() < oldest.getLastAccess()) {
                        oldest = entry;//  w  w  w  . ja v a  2  s.  c  o  m
                    }
                }
            }
            if (!obsoleteHierarchies.isEmpty()) {
                for (int i = 0; i < obsoleteHierarchies.size(); i++) {
                    removeHierarchyEntryFromCache(obsoleteHierarchies.get(i));
                }
            } else if (oldest != null) {
                removeHierarchyEntryFromCache(oldest);
            }
        }
        HierarchyCacheEntry newEntry = new HierarchyCacheEntry(hierarchy);
        fgHierarchyCache.add(newEntry);
    }
}

From source file:at.bestsolution.fxide.jdt.corext.util.SuperTypeHierarchyCache.java

License:Open Source License

private static ITypeHierarchy findTypeHierarchyInCache(IType type) {
    synchronized (fgHierarchyCache) {
        for (int i = fgHierarchyCache.size() - 1; i >= 0; i--) {
            HierarchyCacheEntry curr = fgHierarchyCache.get(i);
            ITypeHierarchy hierarchy = curr.getTypeHierarchy();
            if (!hierarchy.exists()) {
                removeHierarchyEntryFromCache(curr);
            } else {
                if (hierarchy.contains(type)) {
                    curr.markAsAccessed();
                    return hierarchy;
                }// w  ww.j  a  va  2s.co m
            }
        }
    }
    return null;
}

From source file:ca.uvic.chisel.diver.sequencediagrams.sc.java.model.JavaMessage.java

License:Open Source License

/**
 * Returns true if this message was passed within a try block that catches the given
 * type./*from ww  w.j  a v  a  2 s . c  om*/
 * @param type
 * @return
 */
public boolean catches(IType type) {
    if (tries == null) {
        return false;
    }
    for (TryStatement statement : tries) {
        for (Object o : statement.catchClauses()) {
            CatchClause catcher = (CatchClause) o;
            ITypeBinding binding = catcher.getException().getType().resolveBinding();
            if (binding != null) {
                IType caughtType = (IType) binding.getJavaElement();
                if (caughtType != null) {
                    try {
                        ITypeHierarchy hierarchy = caughtType.newSupertypeHierarchy(new NullProgressMonitor());
                        if (caughtType.equals(type) || hierarchy.contains(type)) {
                            return true;
                        }
                    } catch (JavaModelException e) {

                    }
                }
            }
        }
    }
    return false;
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.core.AndroidTypeRenameParticipant.java

License:Open Source License

@Override
protected boolean initialize(Object element) {
    if (sIgnore) {
        return false;
    }//from   w  ww  .  j a  v a2 s .  co  m

    if (element instanceof IType) {
        IType type = (IType) element;
        IJavaProject javaProject = (IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT);
        mProject = javaProject.getProject();
        IResource manifestResource = mProject
                .findMember(AdtConstants.WS_SEP + SdkConstants.FN_ANDROID_MANIFEST_XML);

        if (manifestResource == null || !manifestResource.exists() || !(manifestResource instanceof IFile)) {
            RefactoringUtil.logInfo(String.format("Invalid or missing file %1$s in project %2$s",
                    SdkConstants.FN_ANDROID_MANIFEST_XML, mProject.getName()));
            return false;
        }

        try {
            IType classView = javaProject.findType(CLASS_VIEW);
            if (classView != null) {
                ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
                if (hierarchy.contains(classView)) {
                    mIsCustomView = true;
                }
            }
        } catch (CoreException e) {
            AdtPlugin.log(e, null);
        }

        mManifestFile = (IFile) manifestResource;
        ManifestData manifestData;
        manifestData = AndroidManifestHelper.parseForData(mManifestFile);
        if (manifestData == null) {
            return false;
        }
        mOldSimpleName = type.getElementName();
        mOldDottedName = '.' + mOldSimpleName;
        mOldFqcn = type.getFullyQualifiedName();
        String packageName = type.getPackageFragment().getElementName();
        mNewSimpleName = getArguments().getNewName();
        mNewDottedName = '.' + mNewSimpleName;
        if (packageName != null) {
            mNewFqcn = packageName + mNewDottedName;
        } else {
            mNewFqcn = mNewSimpleName;
        }
        if (mOldFqcn == null || mNewFqcn == null) {
            return false;
        }
        if (!RefactoringUtil.isRefactorAppPackage() && mNewFqcn.indexOf('.') == -1) {
            mNewFqcn = packageName + mNewDottedName;
        }
        return true;
    }
    return false;
}

From source file:com.google.gdt.eclipse.core.JavaUtilities.java

License:Open Source License

/**
 * Returns whether a type is the super of another type.
 * /*from  www.ja  v  a 2  s  . c  om*/
 * @param superType the possible super type. If <code>null</code>, this method
 *          always returns <code>false<code>.
 * @param type the type
 */
public static boolean isSubtype(IType superType, IType type) throws JavaModelException {
    if (superType == null) {
        return false;
    }

    ITypeHierarchy superTypes = type.newSupertypeHierarchy(null);
    return superTypes.contains(superType);
}

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

License:Open Source License

/**
 * Returns <code>true</code> if the type is or extends the RemoteService 
 * interface./*w  w w . jav a 2  s .  c om*/
 */
public static boolean isSyncInterface(IType type) throws JavaModelException {
    IJavaProject javaProject = type.getJavaProject();
    if (!GWTNature.isGWTProject(javaProject.getProject())) {
        return false;
    }

    ITypeHierarchy hierarchy = type.newSupertypeHierarchy(null);
    IType remoteServiceInterface = javaProject.findType(REMOTE_SERVICE_QUALIFIED_NAME);
    return remoteServiceInterface != null && hierarchy.contains(remoteServiceInterface);
}

From source file:com.liferay.ide.project.core.BaseValidator.java

License:Open Source License

protected Map<String, Object> checkClass(IJavaProject javaProject, Node classSpecifier,
        String preferenceNodeQualifier, IScopeContext[] preferenceScopes, String classExistPreferenceKey,
        String classHierarchyPreferenceKey, String superTypeNames) {
    String className = NodeUtil.getTextContent(classSpecifier);

    if (className != null && className.length() > 0) {
        IType type = null;//from   w  w  w .  j av a2s .c  o m

        try {
            type = javaProject.findType(className);

            if (type == null || !type.exists() || className.startsWith(".")) {
                final String msg = MessageFormat.format(MESSAGE_CLASS_NOT_FOUND, new Object[] { className });

                return createMarkerValues(preferenceNodeQualifier, preferenceScopes, classExistPreferenceKey,
                        (IDOMNode) classSpecifier, msg);
            }

            else if (superTypeNames != null) {
                boolean typeFound = false;
                final String[] superTypes = superTypeNames.split(StringPool.COMMA);

                for (String superType : superTypes) {
                    try {
                        IType checkType = javaProject.findType(superType.trim());

                        if (checkType != null) {
                            ITypeHierarchy supertypeHierarchy = type.newSupertypeHierarchy(null);

                            if (supertypeHierarchy.contains(checkType)) {
                                typeFound = true;
                                break;
                            }
                        }
                    } catch (JavaModelException e) {
                        ProjectCore.logError(e);
                    }
                }

                if (typeFound == false) {
                    String msg = MessageFormat.format(MESSAGE_CLASS_INCORRECT_HIERARCHY, className,
                            superTypeNames);

                    if (superTypeNames.contains(StringPool.COMMA)) {
                        msg = msg.replaceAll(Msgs.typeLabel, Msgs.possibleTypes);
                    }

                    return createMarkerValues(preferenceNodeQualifier, preferenceScopes,
                            classHierarchyPreferenceKey, (IDOMNode) classSpecifier, msg);
                }
            }
        } catch (JavaModelException e) {
            return null;
        }
    }

    return null;
}

From source file:edu.clarkson.serl.critic.interpreter.model.ExprCast.java

License:Open Source License

/**
 * Adds the type information in the casted object.
 * Also checks if casting throws an exception, in which case
 * exception will be reported and the path will be marked infeasible.
 *//*from  www .j a va2s.com*/
public ISymbol<? extends Value> execute() {
    Value op = this.getSootValue().getOp();
    StackFrame stackFrame = (StackFrame) Interpreter.instance().peek();
    ISymbol<? extends Value> result = null;
    Type castType = this.getSootValue().getCastType();
    if (op instanceof Local) {
        result = stackFrame.lookup(op);
        if (!(result instanceof Constant)) {
            if (!result.isOpen()) {
                try {
                    IJavaProject project = CriticPlugin.getIJavaProject();
                    IType opIType = project.findType(result.getType().toString());
                    IType castIType = project.findType(castType.toString());
                    ITypeHierarchy typeHierarchy = opIType.newSupertypeHierarchy(null);
                    if (!typeHierarchy.contains(castIType)) {
                        this.exception = Interpreter.CLASS_CAST;
                    }
                } catch (Exception e) {
                }
            } else if (result.isMutable()) {
                ClosedSet<? extends Value> inclusiveTypes = (ClosedSet<? extends Value>) result
                        .get(SymbolicKey.TYPES_IN);
                if (inclusiveTypes == null) {
                    inclusiveTypes = new ClosedSet<Value>(
                            AbstractValue.fromObject("edu.clarkson.serl.critic.adt.ClosedSet"));
                    result.put(SymbolicKey.TYPES_IN, inclusiveTypes);
                }
                inclusiveTypes.add(SymbolicKey.fromObject(castType));
            }
        }
    } else if (op instanceof Constant) {
        // Do nothing related to constant
        result = ExtensionManager.instance().getSymbolicObject(op, false, false);
        result = result.execute();
    } else {
        throw new UnsupportedOperationException("Operand of a cast expression must be a local or a constant");
    }

    this.result = result;
    return result;
}

From source file:edu.clarkson.serl.critic.interpreter.model.ExprInstanceOf.java

License:Open Source License

public ISymbol<? extends Value> execute() {
    Value op = this.getSootValue().getOp();
    if (!(op instanceof Local)) // Sanity check
        throw new UnsupportedOperationException(
                "The operand of instanceof expression must be a local variable");

    ISymbol<? extends Value> operand = Interpreter.instance().peek().lookup(op);
    Type opType = operand.getType();
    Type checkedType = this.getSootValue().getCheckType();

    // Note: Incomplete implementation using Soot's fast hierarchy for future consideration.
    // The FastHierarchy API does not provide required functionalities that ITypeHierarchy provides.      
    //      if(operand.isKnown()) {
    //         FastHierarchy fastHierarchy = Scene.v().getOrMakeFastHierarchy();
    //         if(fastHierarchy.canStoreType(opType, checkedType)) {
    //            this.result = Interpreter.TRUE;
    //            return Interpreter.TRUE;
    //         }//  w  ww .  j av  a 2 s. c  o m
    //         this.result = Interpreter.FALSE;
    //         return Interpreter.FALSE;
    //      }

    IJavaProject project;
    IType opIType;
    IType checkedIType;
    ITypeHierarchy opHierarchy;
    try {
        project = CriticPlugin.getIJavaProject();
        opIType = project.findType(opType.toString());
        checkedIType = project.findType(checkedType.toString());
        opHierarchy = opIType.newSupertypeHierarchy(null);
        if (opHierarchy.contains(checkedIType)) { // For both open and closed this holds
            this.result = Interpreter.TRUE;
            return Interpreter.TRUE;
        } else if (!this.isOpen()) { // For only closed object this holds
            this.result = Interpreter.FALSE;
            return Interpreter.FALSE;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    // At this point we are dealing with open object only and we know that 
    // checkedIType is not a supertype of opIType. So, instead it may hold 
    // that the checkedIType is a subtype of the supplied opType.
    try {
        ITypeHierarchy checkedHierarchy = checkedIType.newSupertypeHierarchy(null);

        if (!checkedHierarchy.contains(opIType)) {
            // At this point neither checkedIType is a parent of opIType, nor opIType is a parent of checkedIType.  
            // This mean that opType and checkedType are in two different sub-hierarchies from a common parent
            this.result = Interpreter.FALSE;
            return Interpreter.FALSE;
        }

        // At this point opIType is a subtype of checkedIType. This may be true because the real type of op is open.
        // Lets check whether any type related information is available.

        // First the inclusive types
        ClosedSet<? extends Value> types = (ClosedSet<? extends Value>) operand.get(SymbolicKey.TYPES_IN);
        if (types != null && !types.isEmpty()) {
            for (ISymbol<? extends Value> t : types) {
                IType tIType = project.findType(t.getType().toString());
                ITypeHierarchy tHierarchy = tIType.newSupertypeHierarchy(null);
                if (tHierarchy.contains(checkedIType)) { // The checked type is a super type of one of the inclusive type
                    this.result = Interpreter.TRUE;
                    return Interpreter.TRUE;
                }
            }
        }

        // Inclusive types could not resolve the instanceof test
        // Now lets try exclusive types
        types = (ClosedSet<? extends Value>) operand.get(SymbolicKey.TYPES_OUT);
        if (types != null && !types.isEmpty()) {
            for (ISymbol<? extends Value> t : types) {
                IType tIType = project.findType(t.getType().toString());
                if (checkedIType.equals(tIType)) { // instaceof test of the excluded type
                    this.result = Interpreter.FALSE;
                    return Interpreter.FALSE;
                }
                ITypeHierarchy tHierarchy = tIType.newTypeHierarchy(project, null);
                IType[] subtypes = tHierarchy.getAllSubtypes(tIType);
                for (IType sub : subtypes) {
                    if (checkedIType.equals(sub)) { // instaceof test of a subtype of the excluded type
                        this.result = Interpreter.FALSE;
                        return Interpreter.FALSE;
                    }
                }

            }
        }

        // Neither inclusive nor exclusive set resolved the instanceof test.
        // Hence, result is set to be open.
        this.result = this;
        return this;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.sarl.eclipse.wizards.elements.AbstractNewSarlElementWizardPage.java

License:Apache License

/** Replies if the given type is a subtype of the expected super-type.
 * The expected super-type is replied by {@link #getRootSuperType()}.
 *
 * @param className - the name of the class to be tested.
 * @return <code>true</code> if the given name is the one of a subtype
 *     of the expected root type.//w ww . j a  v a2s.  c  om
 * @throws JavaModelException if there is a problem for retreiving the Java information.
 */
protected boolean isValidExtendedType(String className) throws JavaModelException {
    // accept the empty field (stands for the default super type)
    if (!Strings.isNullOrEmpty(className)) {
        final IType rootType = getRootSuperType();
        if (rootType == null) {
            final IStatus status = SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR,
                    Messages.AbstractNewSarlElementWizardPage_3);
            throw new JavaModelException(new CoreException(status));
        }
        final IType type = getJavaProject().findType(className);
        if (type == null) {
            final IStatus status = SARLEclipsePlugin.getDefault().createStatus(IStatus.ERROR,
                    MessageFormat.format(Messages.AbstractNewSarlElementWizardPage_4, className));
            throw new JavaModelException(new CoreException(status));
        }
        final ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
        if (hierarchy == null || !hierarchy.contains(rootType)) {
            return false;
        }
    }
    return true;
}