alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                  Sun Public License Notice
 *   
 *  The contents of this file are subject to the Sun Public License
 *  Version 1.0 (the "License"). You may not use this file except in
 *  compliance with the License. A copy of the License is available at
 *  http://www.sun.com/
 *    
 *  The Original Code is NetBeans. The Initial Developer of the Original
 *  Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 *  Microsystems, Inc. All Rights Reserved.
 *  
 */

package org.netbeans.modules.javacore.jmiimpl.javamodel;

import org.netbeans.jmi.javamodel.*;
import org.netbeans.lib.java.parser.Token;
import org.netbeans.api.mdr.MDRepository;
import org.netbeans.mdr.handlers.AttrListWrapper;
import org.netbeans.mdr.handlers.BaseObjectHandler;
import org.netbeans.mdr.persistence.StorageException;
import org.netbeans.mdr.storagemodel.StorableObject;
import org.netbeans.modules.javacore.parser.ASTProvider;
import org.netbeans.modules.javacore.parser.ClassInfo;
import org.netbeans.modules.javacore.parser.ElementInfo;
import org.openide.ErrorManager;
import javax.jmi.reflect.RefObject;
import java.util.*;

import org.netbeans.modules.javacore.parser.NameRef;

import org.openide.util.Utilities;

/**
 * @author Martin Matula
 */
public abstract class ClassDefinitionImpl extends SemiPersistentElement implements ClassDefinition {
    private ReferenceListWrapper interfaces;
    private JavaClass superClass;
    private LightAttrList contents;
    private final List featuresList;

    public ClassDefinitionImpl(StorableObject s) {
        super(s);
        this.featuresList = new FeaturesList(this);
    }

    protected abstract List super_getContents();

    public List getContents() {
        if (!childrenInited) {
            initChildren();
        }
        return contents;
    }

    public List getFeatures() {
        return featuresList;
    }

    public Collection getReferences() {
        return Collections.EMPTY_LIST;
    }
    
    public List getInterfaces() {
        if (interfaces == null) {
            interfaces = initInterfaces(interfaces, this);
        }
        return interfaces;
    }

    public JavaClass getSuperClass() {
        JavaClass result;

        // if the superclass has changed, the superClass variable is
        // initialized -> return its content
        if (isChanged(CHANGED_EXTENDS)) {
            if (superClass == null) {
                superClass = (JavaClass) ((JavaModelPackage) refImmediatePackage()).getType().resolve("java.lang.Object"); // NOI18N
            }
            result = superClass;
        } else {
            NameRef superClassName = ((ClassInfo) getElementInfo()).superclass;
            result = (JavaClass) resolveType(superClassName);
        }
        return result;
    }

    public void setSuperClass(JavaClass newValue) {
        throw new UnsupportedOperationException();
    }

    protected void initChildren() {
        initChildren(false);
    }

    protected void initChildren(boolean rebuild) {
        childrenInited = false;
        contents = createChildrenList(contents, "contents", ((ClassInfo) getElementInfo()).features, CHANGED_FEATURES, rebuild); // NOI18N
        childrenInited = true;
    }

    protected void matchPersistent(ElementInfo info) {
        // do nothing
    }

    protected void matchElementInfo(ElementInfo newInfo) {
        // do nothing
    }

    void setData(List features) {
        contents = createChildrenList("contents", features, CHANGED_FEATURES); // NOI18N
        childrenInited = true;
    }

    protected void _delete() {
        // --- delete components -------------------------------------------
        // delete all contents
        if (childrenInited) {
            for (Iterator it = getContents().iterator(); it.hasNext();) {
                RefObject feature = (RefObject) it.next();
                it.remove();
                feature.refDelete();
            }
        }
        super._delete();
    }

    protected void resetChildren() {
        if (childrenInited) {
            initChildren(true);
        }
        if (interfaces != null) {
            interfaces = ClassDefinitionImpl.initInterfaces(interfaces, this);
        }
    }

    public List getChildren() {
        return new ArrayList(getContents());
    }

    public String getSourceText() {
        String origElem;
        if ((origElem = checkChange()) != null)
            return origElem;
        StringBuffer buf = new StringBuffer();
        formatElementPart(BLOCK_OPEN_CURLY, buf);
        generateNewFeatures(this, buf, false);
        formatElementPart(BLOCK_CLOSE_CURLY, buf);
        return buf.toString();
    }

    public void getDiff(List diffList) {
        ClassInfo astInfo = (ClassInfo) getElementInfo();
        ASTProvider parser = getParser();

        // contents diff
        Token closeBrace = parser.getToken(getASTree().getLastToken());
        Token[] pad = closeBrace.getPadding();
        int endOffset = pad.length > 0 ? pad[0].getStartOffset() : closeBrace.getStartOffset();
        getCollectionDiff(diffList, parser, CHANGED_FEATURES, astInfo.features, getContents(), endOffset, "\n"); // NOI18N
    }

    public void replaceChild(Element oldElement, Element newElement) {
        if (childrenInited) {
            if (replaceObject(getContents(), oldElement, newElement)) return;
        }
    }

    protected ElementInfo getDefaultInfo() {
        return JavaClassImpl.DEFAULT_INFO;
    }

    // --------- Implementation of JMI operations -----------------------------------------------------------

    public Field getField(String name, boolean includeSupertypes) {
        return getField(this, name, includeSupertypes);
    }
    
    public Method getMethod(String name, List parameters, boolean includeSupertypes) {
        return getMethod(this, name, parameters, includeSupertypes);
    }
    
    public JavaClass getInnerClass(String simpleName, boolean includeSupertypes) {
        return getInnerClass(this, simpleName, includeSupertypes);
    }
    
    public Constructor getConstructor(List parameters, boolean includeSupertypes) {
        return getConstructor(this, parameters, includeSupertypes);
    }
        
    // static methods to which we delegate ......................................
    
    static Field getField (ClassDefinition cd, String name, boolean includeSuperTypes) {
        MDRepository repository = ((BaseObjectHandler)cd).repository();
        repository.beginTrans(false);
        try {
            Field field = getField (cd, name);
            if ((field != null) || !includeSuperTypes) {
                return field;
            }
            JavaClass jc = cd.getSuperClass();
            while (jc != null) {
                field = getField (jc, name);
                if (field != null)
                    return field;
                jc = jc.getSuperClass();
            }
            // scan interfaces
            LinkedList supers = new LinkedList();
            supers.addAll (cd.getInterfaces());
            while (supers.size () > 0) {
                ClassDefinition intfc = (ClassDefinition) supers.removeFirst ();
                field = getField (intfc, name);
                if (field != null)
                    return field;
                supers.addAll (intfc.getInterfaces ());
            }
            return null;
        } finally {
            repository.endTrans(false);
        }
    }
    
    static JavaClass getInnerClass (ClassDefinition cd, String name, boolean includeSuperTypes) {
        MDRepository repository = ((BaseObjectHandler)cd).repository();
        repository.beginTrans(false);
        try {
            JavaClass innerCls = getInnerClass (cd, name);
            if ((innerCls != null) || !includeSuperTypes) {
                return innerCls;
            }
            JavaClass jc = cd.getSuperClass();
            while (jc != null) {
                innerCls = getInnerClass (jc, name);
                if (innerCls != null)
                    return innerCls;
                jc = jc.getSuperClass();
            }
            // scan interfaces
            LinkedList supers = new LinkedList();
            supers.addAll (cd.getInterfaces());
            while (supers.size () > 0) {
                ClassDefinition intfc = (ClassDefinition) supers.removeFirst ();
                innerCls = getInnerClass (intfc, name);
                if (innerCls != null)
                    return innerCls;
                supers.addAll (intfc.getInterfaces ());
            }
            return null;
        } finally {
            repository.endTrans(false);
        }
    }
    
    static Method getMethod (ClassDefinition cd, String name, List argTypes, boolean includeSuperTypes) {
        MDRepository repository = ((BaseObjectHandler)cd).repository();
        repository.beginTrans(false);
        try {
            Method method = getMethod (cd, name, argTypes);
            if ((method != null) || !includeSuperTypes) {
                return method;
            }
            JavaClass jc = cd.getSuperClass();        
            while (jc != null) {
                method = getMethod (jc, name, argTypes);
                if (method != null)
                    return method;
                jc = jc.getSuperClass();
            }
            // scan interfaces
            LinkedList supers = new LinkedList();
            supers.addAll (cd.getInterfaces());
            while (supers.size () > 0) {
                ClassDefinition intfc = (ClassDefinition) supers.removeFirst ();
                method = getMethod (intfc, name, argTypes);
                if (method != null)
                    return method;
                supers.addAll (intfc.getInterfaces ());
            }
            return null;
        } finally {
            repository.endTrans();
        }
    }
    
    static Constructor getConstructor (ClassDefinition cd, List argTypes, boolean includeSuperTypes) {
        MDRepository repository = ((BaseObjectHandler)cd).repository();
        repository.beginTrans(false);
        try {
            Constructor constructor = getConstructor (cd, argTypes);
            if ((constructor != null) || !includeSuperTypes) {
                return constructor;
            }
            JavaClass jc = cd.getSuperClass();        
            while (jc != null) {
                constructor = getConstructor (jc, argTypes);
                if (constructor != null)
                    return constructor;
                jc = jc.getSuperClass();
            }        
            return null;
        } finally {
            repository.endTrans(false);
        }
    }
    
    // helper methods ...........................................................
    
    static Method getMethod (ClassDefinition cd, String name, List argTypes) {
        Iterator iter = cd.getFeatures().iterator();
        while (iter.hasNext()) {
            Object obj = iter.next ();
            if (obj instanceof Method) {
                Method method = (Method) obj;
                if (name.equals(method.getName()) && argTypesMatch(method, argTypes))
                    return method;
            }
        } // while
        return null;
    }
    
    static Constructor getConstructor (ClassDefinition cd, List argTypes) {
        Iterator iter = cd.getFeatures().iterator();
        while (iter.hasNext()) {
            Object obj = iter.next ();
            if (obj instanceof Constructor) {
                Constructor constr = (Constructor) obj;
                if (argTypesMatch(constr, argTypes))
                    return constr;
            }
        } // while
        return null;
    }
    
    static JavaClass getInnerClass (ClassDefinition cd, String name) {
        Iterator iter = cd.getFeatures().iterator();
        while (iter.hasNext()) {
            Object obj = iter.next ();
            if (obj instanceof JavaClass) {
                JavaClass jc = (JavaClass) obj;
                if (name.equals(jc.getSimpleName()))
                    return jc;
            }
        } // while
        return null;
    }
    
    static Field getField (ClassDefinition cd, String name) {
        Iterator iter = cd.getFeatures().iterator();
        while (iter.hasNext()) {
            Object obj = iter.next ();
            if (obj instanceof Field) {
                Field field = (Field) obj;
                if (name.equals(field.getName()))
                    return field;
            }
        } // while
        return null;
    }
    
    static boolean argTypesMatch (CallableFeature callable, List argTypes) {
        List pars = callable.getParameters ();
        if (argTypes.size () != pars.size ()) {
            return false;
        }
        Iterator parsIter = pars.iterator ();
        Iterator argsIter = argTypes.iterator ();
        while (parsIter.hasNext ()) {
            Type t1 = TypeClassImpl.getRealType(((Parameter) parsIter.next ()).getType ());
            Type t2 = TypeClassImpl.getRealType((Type) argsIter.next ());                    
            if (!(t1 == t2)) {
                return false;
            }
        } // while
        return true;
    }
    
    /** Initializes interfaces collection */
    static ReferenceListWrapper initInterfaces(ReferenceListWrapper interfaces, SemiPersistentElement javaClass) {
        NameRef[] interfaceNames = ((ClassInfo) javaClass.getElementInfo()).interfaces;
        // list of superinterfaces is transient
        TypeList _interfaces = new TypeList(javaClass);
        for (int i = 0; i return false immediately
        if (!visited.add(thisClass)) {
            return false;
        }
        
        clazz = getRealClassDefinition(clazz);

        // if the names of the classes match, we found the class traversing through supertypes -> it is a subtype
        if (Utilities.compareObjects(thisClass.getName(), clazz.getName())) {
            return true;
        }

        if ((thisClass instanceof JavaClass) && ((JavaClass) thisClass).isInterface()) {
            // if this class is an interface and class that it should be a subtype of is a class, we know the only case
            // where that could be true is if the supertype is java.lang.Object
            if (!((clazz instanceof JavaClass) && ((JavaClass) clazz).isInterface())) { 
                return "java.lang.Object".equals(clazz.getName()); // NOI18N
            }
        } else {
            // check superclasses only if this class is a class (not interface) - for interface it is handled in the condition above
            if (isSubTypeOf(getRealClassDefinition(thisClass.getSuperClass()), clazz, visited)) {
                return true;
            }
            // if clazz is not an interface, we must have found it by traversing through superclasses
            if (!((clazz instanceof JavaClass) && ((JavaClass) clazz).isInterface())) { 
                return false;
            }
        }

        // iterate through the super interfaces
        for (Iterator it = thisClass.getInterfaces().iterator(); it.hasNext();) {
            ClassDefinition ifc = getRealClassDefinition((ClassDefinition) it.next());
            if (isSubTypeOf(ifc, clazz, visited)) {
                return true;
            }
        }
        return false;
    }
    
    public static ClassDefinition getRealClassDefinition(ClassDefinition cls) {
        if (cls instanceof ParameterizedType) {
            return ((ParameterizedType) cls).getDefinition();
        }
        return cls;
    }
    
    public boolean isSubTypeOf(ClassDefinition clazz) {
        return isSubTypeOf(this, clazz);
    }

    protected void hardRefParent(boolean enabled) {
        // do not hardref parent - this object is transient
    }

    protected void parentChanged() {
        // do nothing on parentChanged - this object is transient
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.