db-ojb-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From arm...@apache.org
Subject cvs commit: jakarta-ojb/src/java/org/apache/ojb/broker/metadata/torque TorqueRepositoryGenerator.java
Date Tue, 24 Dec 2002 13:14:35 GMT
arminw      2002/12/24 05:14:35

  Modified:    src/java/org/apache/ojb/broker/metadata
                        ObjectReferenceDescriptor.java
                        RepositoryElements.java RepositoryPersistor.java
                        RepositoryTags.java RepositoryXmlHandler.java
                        JdbcConnectionDescriptor.java IndexDescriptor.java
                        FieldDescriptor.java DescriptorRepository.java
                        DescriptorBase.java ConnectionPoolDescriptor.java
                        CollectionDescriptor.java ClassDescriptor.java
                        AttributeDescriptorBase.java
               src/java/org/apache/ojb/broker/metadata/torque
                        TorqueRepositoryGenerator.java
  Added:       src/java/org/apache/ojb/broker/metadata MetadataManager.java
                        MetadataConfiguration.java
                        ConnectionRepository.java
                        ConnectionDescriptorXmlHandler.java
  Log:
  improve metadata handling:
  separate the object stuff (class descriptor, field descriptor, ...)
  from the connection stuff (jdbc descriptor).
  DescriptorRepository now handles only object
  specific properties.
  
  Do some performance improvements
  
  Revision  Changes    Path
  1.19      +143 -257  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/ObjectReferenceDescriptor.java
  
  Index: ObjectReferenceDescriptor.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/ObjectReferenceDescriptor.java,v
  retrieving revision 1.18
  retrieving revision 1.19
  diff -u -r1.18 -r1.19
  --- ObjectReferenceDescriptor.java	20 Oct 2002 15:49:52 -0000	1.18
  +++ ObjectReferenceDescriptor.java	24 Dec 2002 13:14:33 -0000	1.19
  @@ -54,20 +54,23 @@
    * <http://www.apache.org/>.
    */
   
  -import java.util.Hashtable;
  -import java.util.Iterator;
  -import java.util.Vector;
  -
   import org.apache.ojb.broker.PBFactoryException;
   import org.apache.ojb.broker.PersistenceBroker;
   import org.apache.ojb.broker.PersistenceBrokerException;
   import org.apache.ojb.broker.PersistenceBrokerFactory;
   import org.apache.ojb.broker.accesslayer.conversions.FieldConversion;
  -import org.apache.ojb.broker.metadata.fieldaccess.*;
  +import org.apache.ojb.broker.metadata.fieldaccess.PersistentField;
  +import org.apache.commons.lang.builder.ToStringBuilder;
  +
  +import java.util.Hashtable;
  +import java.util.Iterator;
  +import java.util.Vector;
   
   /**
  - *
  - * describes a Field containing a reference to another class. Provides handling for foreign keys etc.
  + * Describes a Field containing a reference to another class. Provides handling for foreign keys etc.
  + * <br>
  + * Note: Be careful when use references of this class or caching instances of this class,
  + * because instances could become invalid (see {@link MetadataManager}).
    *
    * @author <a href="mailto:thma@apache.org">Thomas Mahler<a>
    *
  @@ -75,17 +78,15 @@
   public class ObjectReferenceDescriptor extends AttributeDescriptorBase implements XmlCapable
   {
       private Class m_ClassOfItems = null;
  -    private String itemClassName = null;
       private Vector m_ForeignKeyFields = new Vector();
       private boolean m_CascadeRetrieve = true;
       private boolean m_CascadeStore = false;
       private boolean m_CascadeDelete = false;
  -
  +    private Class m_ProxyOfItems = null;
       /**
        * holds the foreign-key field descriptor array for a specified class
        */
       private Hashtable fkFieldMap = new Hashtable();
  -
       /**
        * define loading strategy of the resulting object
        */
  @@ -96,49 +97,98 @@
       private boolean refresh = false;
   
       /**
  -     * Constructor declaration
  -     *
  -     *
        *
        */
  -    public ObjectReferenceDescriptor()
  +    public ObjectReferenceDescriptor(ClassDescriptor descriptor)
       {
  +        super(descriptor);
       }
   
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @return
        *
  +     */
  +    public Class getItemProxyClass() throws PersistenceBrokerException
  +    {
  +        if (m_ProxyOfItems == null)
  +        {
  +            m_ProxyOfItems = getClassDescriptor().getRepository().
  +                                getDescriptorFor(m_ClassOfItems).getProxyClass();
  +        }
  +        return m_ProxyOfItems;
  +    }
  +
  +    /**
        *
        */
  -    public Class getItemClass()
  +    public FieldDescriptor[] getForeignKeyFieldDescriptors(ClassDescriptor mif)
       {
  -    	if (m_ClassOfItems == null)
  -    	{
  -    		if (itemClassName != null)
  -    		{
  -                try
  +        FieldDescriptor[] foreignKeyFieldDescriptors = null;
  +        if ((foreignKeyFieldDescriptors = (FieldDescriptor[]) fkFieldMap.get(mif)) == null)
  +        {
  +            // 1. collect vector of indices of Fk-Fields
  +            Vector v = getForeignKeyFields();
  +            // 2. get FieldDescriptor for each index from Class-descriptor
  +            // 2A. In a many-to-many relationship foreignkeyfields vector will be null.
  +            if (v != null)
  +            {
  +                Vector ret;
  +                if (mif.isInterface())
                   {
  -                    m_ClassOfItems = Class.forName(itemClassName, true,
  -                                		Thread.currentThread().getContextClassLoader());	
  +                    //exchange interface class descriptor with first concrete
  +                    //class
  +                    Vector extents = mif.getExtentClasses();
  +                    Class firstConcreteClass = (Class) extents.get(0);
  +                    mif = getClassDescriptor().getRepository().getDescriptorFor(firstConcreteClass);
                   }
  -                catch (ClassNotFoundException e)
  +                ret = new Vector();
  +
  +                Iterator iter = v.iterator();
  +                while (iter.hasNext())
                   {
  -                	throw new MetadataException(e);
  +                    Integer index = (Integer) iter.next();
  +                    ret.add(mif.getFieldDescriptorByIndex(index.intValue()));
                   }
  -    		}	
  -    	}    	
  +                foreignKeyFieldDescriptors =
  +                        (FieldDescriptor[]) ret.toArray(new FieldDescriptor[ret.size()]);
  +                fkFieldMap.put(mif, foreignKeyFieldDescriptors);
  +            }
  +        }
  +        return foreignKeyFieldDescriptors;
  +    }
  +
  +    /**
  +     * @throws MetadataException if an error occours while accessing ForeingKey values on obj
  +     */
  +    public Object[] getForeignKeyValues(Object obj, ClassDescriptor mif)
  +            throws PersistenceBrokerException
  +    {
  +        FieldDescriptor[] fks = getForeignKeyFieldDescriptors(mif);
  +        Object[] result = new Object[fks.length];
  +        for (int i = 0; i < result.length; i++)
  +        {
  +            FieldDescriptor fmd = fks[i];
  +            PersistentField f = fmd.getPersistentField();
  +            FieldConversion fc = fmd.getFieldConversion();
  +            Object val = fc.javaToSql(f.get(obj));
  +            result[i] = val;
  +        }
  +        return result;
  +    }
  +
  +    /**
  +     *
  +     */
  +    public Class getItemClass()
  +    {
           return m_ClassOfItems;
       }
  -    
  +
       /**
        * @returns the fully qualified name of the item class for this descriptor.
        */
       public String getItemClassName()
       {
  -        return this.itemClassName;
  +        return this.m_ClassOfItems != null ? this.m_ClassOfItems.getName() : null;
       }
   
       /**
  @@ -148,25 +198,9 @@
       public void setItemClass(Class c)
       {
           m_ClassOfItems = c;
  -        setItemClassName(c.getName());
       }
   
       /**
  -     * sets the name of item class
  -     * @param classname the items class name
  -     */
  -    public void setItemClassName(String classname)
  -    {
  -        itemClassName = classname;
  -    }
  -
  -
  -    /**
  -     * Method declaration
  -     *
  -     *
  -     * @return
  -     *
        *
        */
       public Vector getForeignKeyFields()
  @@ -175,11 +209,6 @@
       }
   
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @param vec
  -     *
        *
        */
       public void setForeignKeyFields(Vector vec)
  @@ -192,244 +221,106 @@
        */
       public void addForeignKeyField(int newId)
       {
  -     	if (m_ForeignKeyFields == null)
  -     	{
  +        if (m_ForeignKeyFields == null)
  +        {
               m_ForeignKeyFields = new Vector();
  -     	}
  -     	m_ForeignKeyFields.add(new Integer(newId));
  +        }
  +        m_ForeignKeyFields.add(new Integer(newId));
       }
   
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @return
  -     *
  -     *
  +     * Gets the refresh.
  +     * @return Returns a boolean
        */
  -    public boolean getCascadeRetrieve()
  +    public boolean isRefresh()
       {
  -        return m_CascadeRetrieve;
  +        return refresh;
       }
   
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @param b
  -     *
  -     *
  +     * Sets the refresh.
  +     * @param refresh The refresh to set
        */
  -    public void setCascadeRetrieve(boolean b)
  +    public void setRefresh(boolean refresh)
       {
  -        m_CascadeRetrieve = b;
  +        this.refresh = refresh;
       }
   
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @return
  -     *
  -     *
  +     * Gets the lazy.
  +     * @return Returns a boolean
        */
  -    public boolean getCascadeStore()
  +    public boolean isLazy()
       {
  -        return m_CascadeStore;
  +        return lazy;
       }
   
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @param b
  -     *
  -     *
  +     * Sets the lazy.
  +     * @param lazy The lazy to set
        */
  -    public void setCascadeStore(boolean b)
  +    public void setLazy(boolean lazy)
       {
  -        m_CascadeStore = b;
  +        this.lazy = lazy;
       }
   
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @return
  -     *
        *
        */
  -    public boolean getCascadeDelete()
  +    public boolean getCascadeRetrieve()
       {
  -        return m_CascadeDelete;
  +        return m_CascadeRetrieve;
       }
   
       /**
  -     * Method declaration
  -     *
        *
  -     * @param b
  -     *
  -     *
  -     */
  -    public void setCascadeDelete(boolean b)
  -    {
  -        m_CascadeDelete = b;
  -    }
  -
  -    private Class m_ProxyOfItems = null;
  -
  -    /**
  -     * Insert the method's description here.
  -     * Creation date: (10.11.2000 22:44:15)
  -     * @return java.lang.Class
        */
  -    public java.lang.Class getItemProxyClass() throws PersistenceBrokerException
  +    public void setCascadeRetrieve(boolean b)
       {
  -        if (m_ProxyOfItems == null)
  -        {
  -            PersistenceBroker broker = null;
  -            try
  -            {
  -                broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -                m_ProxyOfItems = broker.getClassDescriptor(m_ClassOfItems).getProxyClass();
  -            }
  -            catch (Exception ex)
  -            {
  -                throw new PersistenceBrokerException(ex);
  -            }
  -            finally
  -            {
  -            	if (broker != null)
  -            	{
  -            		broker.close();
  -            	}
  -            }
  -        }
  -        return m_ProxyOfItems;
  +        m_CascadeRetrieve = b;
       }
   
  -    //private FieldDescriptor[] foreignKeyFieldDescriptors = null;
  -
       /**
        *
  -     * @param mif
  -     *
  -     * @return
  -     *
  -     */
  -    public FieldDescriptor[] getForeignKeyFieldDescriptors(ClassDescriptor mif)
  -    {
  -        FieldDescriptor[] foreignKeyFieldDescriptors = null;
  -        if ((foreignKeyFieldDescriptors = (FieldDescriptor[]) fkFieldMap.get(mif)) == null)
  -        {
  -            // 1. collect vector of indices of Fk-Fields
  -            Vector v = getForeignKeyFields();
  -            // 2. get FieldDescriptor for each index from Class-descriptor
  -			// 2A. In a many-to-many relationship foreignkeyfields vector will be null.
  -			if (v != null)
  -			{
  -	            PersistenceBroker broker = null;
  -                Vector ret;
  -
  -                try
  -                {
  -                    if (mif.isInterface())
  -                    {
  -                        //exchange interface class descriptor with first concrete
  -                        //class
  -                        Vector extents = mif.getExtentClasses();
  -                        Class firstConcreteClass = (Class) extents.get(0);
  -
  -                        try
  -                        {
  -                            broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -                            mif = broker.getClassDescriptor(firstConcreteClass);
  -                        }
  -                        catch (PBFactoryException e)
  -                        {
  -                        }
  -
  -                    }
  -                    ret = new Vector();
  -
  -                    Iterator iter = v.iterator();
  -                    while (iter.hasNext())
  -                    {
  -                        Integer index = (Integer) iter.next();
  -                        ret.add(mif.getFieldDescriptorByIndex(index.intValue()));
  -                    }
  -                }
  -                finally
  -                {
  -                    if(broker != null)
  -                    {
  -                        broker.close();
  -                    }
  -                }
  -
  -                foreignKeyFieldDescriptors =
  -                    (FieldDescriptor[]) ret.toArray(new FieldDescriptor[ret.size()]);
  -                fkFieldMap.put(mif, foreignKeyFieldDescriptors);
  -			}
  -
  -        }
  -        return foreignKeyFieldDescriptors;
  -    }
  -
  -    /**
  -     * @throws MetadataException if an error occours while accessing ForeingKey values on obj
        */
  -    public Object[] getForeignKeyValues(Object obj, ClassDescriptor mif)
  -        throws PersistenceBrokerException
  +    public boolean getCascadeStore()
       {
  -        FieldDescriptor[] fks = getForeignKeyFieldDescriptors(mif);
  -        Object[] result = new Object[fks.length];
  -        for (int i = 0; i < result.length; i++)
  -        {
  -            FieldDescriptor fmd = fks[i];
  -            PersistentField f = fmd.getPersistentField();
  -            FieldConversion fc = fmd.getFieldConversion();
  -            Object val = fc.javaToSql(f.get(obj));
  -            result[i] = val;
  -        }
  -        return result;
  +        return m_CascadeStore;
       }
   
       /**
  -     * Gets the refresh.
  -     * @return Returns a boolean
  +     *
        */
  -    public boolean isRefresh()
  +    public void setCascadeStore(boolean b)
       {
  -        return refresh;
  +        m_CascadeStore = b;
       }
   
       /**
  -     * Sets the refresh.
  -     * @param refresh The refresh to set
  +     *
        */
  -    public void setRefresh(boolean refresh)
  +    public boolean getCascadeDelete()
       {
  -        this.refresh = refresh;
  +        return m_CascadeDelete;
       }
   
       /**
  -     * Gets the lazy.
  -     * @return Returns a boolean
  +     *
        */
  -    public boolean isLazy()
  +    public void setCascadeDelete(boolean b)
       {
  -        return lazy;
  +        m_CascadeDelete = b;
       }
   
  -    /**
  -     * Sets the lazy.
  -     * @param lazy The lazy to set
  -     */
  -    public void setLazy(boolean lazy)
  +    public String toString()
       {
  -        this.lazy = lazy;
  +        return new ToStringBuilder(this)
  +                .append("cascade delete", m_CascadeDelete)
  +                .append("cascade retrieve", m_CascadeRetrieve)
  +                .append("cascade store", m_CascadeStore)
  +                .append("is lazy", lazy)
  +                .append("class of Items", m_ClassOfItems)
  +                .toString();
       }
   
       /*
  @@ -439,66 +330,61 @@
       {
           RepositoryTags tags = RepositoryTags.getInstance();
           String eol = System.getProperty("line.separator");
  -		
  -		// opening tag
  +
  +        // opening tag
           String result = "      " + tags.getOpeningTagNonClosingById(REFERENCE_DESCRIPTOR) + eol;
  -        
  +
           // attributes
           // name
  -        result       += "        " + tags.getAttribute(FIELD_NAME,this.getAttributeName()) + eol;
  -        
  -        // class-ref
  -        result       += "        " + tags.getAttribute(REFERENCED_CLASS,this.getItemClassName()) + eol;
  +        result += "        " + tags.getAttribute(FIELD_NAME, this.getAttributeName()) + eol;
   
  +        // class-ref
  +        result += "        " + tags.getAttribute(REFERENCED_CLASS, this.getItemClassName()) + eol;
   
           // proxyReference is optional
           if (isLazy())
           {
  -            result       += "        " + tags.getAttribute(PROXY_REFERENCE,"true") + eol;
  +            result += "        " + tags.getAttribute(PROXY_REFERENCE, "true") + eol;
           }
   
           //reference refresh is optional, disabled by default
           if (isRefresh())
           {
  -            result       += "        " + tags.getAttribute(REFRESH_REFERENCE,"true") + eol;
  +            result += "        " + tags.getAttribute(REFRESH_REFERENCE, "true") + eol;
           }
   
           //auto retrieve is optional, enabled by default
           if (!getCascadeRetrieve())
           {
  -            result       += "        " + tags.getAttribute(AUTO_RETRIEVE,"false") + eol;
  +            result += "        " + tags.getAttribute(AUTO_RETRIEVE, "false") + eol;
           }
   
           //auto update is optional, disabled by default
           if (getCascadeStore())
           {
  -            result       += "        " + tags.getAttribute(AUTO_UPDATE,"true") + eol;
  +            result += "        " + tags.getAttribute(AUTO_UPDATE, "true") + eol;
           }
   
           //auto delete is optional, disabled by default
           if (getCascadeDelete())
           {
  -            result       += "        " + tags.getAttribute(AUTO_DELETE,"true") + eol;
  +            result += "        " + tags.getAttribute(AUTO_DELETE, "true") + eol;
           }
   
  -		// close opening tag
  -		result += "      >" + eol;
  +        // close opening tag
  +        result += "      >" + eol;
   
  -		// elements
  +        // elements
           // write foreignkey elements
  -        for (int i=0;i<getForeignKeyFields().size();i++)
  +        for (int i = 0; i < getForeignKeyFields().size(); i++)
           {
               String fkId = getForeignKeyFields().get(i).toString();
               result += "        " + tags.getOpeningTagNonClosingById(FOREIGN_KEY) + " ";
  -            result += tags.getAttribute(FIELD_ID_REF, fkId) + "/>" + eol;           
  +            result += tags.getAttribute(FIELD_ID_REF, fkId) + "/>" + eol;
           }
  -        
   
  -		// closing tag
  -        result       += "      " + tags.getClosingTagById(REFERENCE_DESCRIPTOR) + eol;
  +        // closing tag
  +        result += "      " + tags.getClosingTagById(REFERENCE_DESCRIPTOR) + eol;
           return result;
  -
       }
  -
  -
   }
  
  
  
  1.17      +6 -5      jakarta-ojb/src/java/org/apache/ojb/broker/metadata/RepositoryElements.java
  
  Index: RepositoryElements.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/RepositoryElements.java,v
  retrieving revision 1.16
  retrieving revision 1.17
  diff -u -r1.16 -r1.17
  --- RepositoryElements.java	22 Dec 2002 15:56:41 -0000	1.16
  +++ RepositoryElements.java	24 Dec 2002 13:14:33 -0000	1.17
  @@ -64,10 +64,13 @@
   public interface RepositoryElements
   {
   	public static final int MAPPING_REPOSITORY = 0;
  +    public static final int DATABASE_REPOSITORY = 81;
       public static final int JDBC_CONNECTION_DESCRIPTOR = 1;
       public static final int DBMS_NAME = 2;
       public static final int SORT = 3;
       public static final int SCHEMA_NAME = 5;
  +    public static final int JCD_ALIAS = 82;
  +    public static final int DEFAULT_CONNECTION = 80;
       public static final int DRIVER_NAME = 6;
       public static final int URL_PROTOCOL = 7;
       public static final int URL_SUBPROTOCOL = 8;
  @@ -75,7 +78,7 @@
       public static final int USER_NAME = 10;
       public static final int USER_PASSWD = 11;
       public static final int EAGER_RELEASE = 74;
  -    public static final int BATCH_MODE = 79;
  +    public static final int BATCH_MODE = 83;
       public static final int CLASS_DESCRIPTOR = 12;
       public static final int CLASS_NAME = 13;
       public static final int CLASS_PROXY = 35;
  @@ -128,6 +131,7 @@
       public static final int CON_WHEN_EXHAUSTED_ACTION = 64;
       public static final int CONNECTION_POOL = 65;
       public static final int CONNECTION_FACTORY = 66;
  +    public static final int VALIDATION_QUERY = 79;
       public static final int REPOSITORY_VERSION = 67;
       public static final int CLASS_REF = 68;
       public static final int ID = 69;
  @@ -138,9 +142,6 @@
       public static final int DOCUMENTATION = 75;
       public static final int ACCEPT_LOCKS = 78;
   
  -
  -
       // maintain a last id to keep track where we are
  -    public static final int _LAST = 80;
  -
  +    public static final int _LAST = 84;
   }
  
  
  
  1.9       +171 -170  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/RepositoryPersistor.java
  
  Index: RepositoryPersistor.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/RepositoryPersistor.java,v
  retrieving revision 1.8
  retrieving revision 1.9
  diff -u -r1.8 -r1.9
  --- RepositoryPersistor.java	4 Dec 2002 21:11:59 -0000	1.8
  +++ RepositoryPersistor.java	24 Dec 2002 13:14:33 -0000	1.9
  @@ -54,195 +54,239 @@
    * <http://www.apache.org/>.
    */
   
  -import java.io.*;
  -import java.net.MalformedURLException;
  -import java.net.URL;
  -
  -import javax.xml.parsers.ParserConfigurationException;
  -import javax.xml.parsers.SAXParser;
  -import javax.xml.parsers.SAXParserFactory;
  -import org.apache.ojb.broker.PersistenceBrokerFactory;
  +import org.apache.commons.lang.SerializationUtils;
  +import org.apache.ojb.broker.util.configuration.Configurable;
  +import org.apache.ojb.broker.util.configuration.Configuration;
   import org.apache.ojb.broker.util.configuration.ConfigurationException;
  +import org.apache.ojb.broker.util.configuration.impl.OjbConfigurator;
   import org.apache.ojb.broker.util.logging.Logger;
   import org.apache.ojb.broker.util.logging.LoggerFactory;
  -//import org.apache.ojb.jdo.metadata.OjbJdoXmlHandler;
   import org.xml.sax.ContentHandler;
   import org.xml.sax.SAXException;
   import org.xml.sax.XMLReader;
  -import org.xml.sax.helpers.XMLReaderFactory;
  +import org.xml.sax.InputSource;
  +
  +import javax.xml.parsers.ParserConfigurationException;
  +import javax.xml.parsers.SAXParser;
  +import javax.xml.parsers.SAXParserFactory;
  +import java.io.File;
  +import java.io.FileInputStream;
  +import java.io.FileOutputStream;
  +import java.io.IOException;
  +import java.io.PrintWriter;
  +import java.net.MalformedURLException;
  +import java.net.URL;
   
   /**
  - * This class is responsible for reading and writing DescriptorRepository objects 
  + * This class is responsible for reading and writing DescriptorRepository objects
    * from and to persistent media.
    * Currently only XML file based persistence is supported.
    *
    * @author <a href="mailto:thma@apache.org">Thomas Mahler<a>
  + * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
    * @version $Id$
    */
  -public class RepositoryPersistor
  +public class RepositoryPersistor implements Configurable
   {
  +    private static Logger log = LoggerFactory.getLogger(RepositoryPersistor.class);
  +
  +    private static final String SER_FILE_PERFIX = "ojb_repository";
  +    private static final String SER_FILE_SUFFIX = "serialize";
  +
  +    private boolean useSerializedRepository = false;
  +
  +    public RepositoryPersistor()
  +    {
  +        OjbConfigurator.getInstance().configure(this);
  +    }
  +
  +    public void configure(Configuration pConfig) throws ConfigurationException
  +    {
  +        useSerializedRepository = ((MetadataConfiguration) pConfig).useSerializedRepository();
  +    }
  +
  +    /**
  +     * Write the {@link DescriptorRepository} to the given file name.
  +     */
       public void writeToFile(DescriptorRepository repository, String filename)
       {
  -        String result = repository.toXML();
  -        //System.out.print(result);
           try
           {
  +            if(log.isDebugEnabled()) log.debug("## Write repository file ##"+
  +                    repository.toXML()+
  +                    "## End of repository file ##");
               FileOutputStream fos = new FileOutputStream(filename);
               PrintWriter pw = new PrintWriter(fos);
  -            pw.print(result);
  +            pw.print(repository.toXML());
               pw.flush();
               pw.close();
           }
           catch (Throwable t)
           {
  -            LoggerFactory.getDefaultLogger().fatal("Could not write to file" + filename, t);
  +            log.fatal("Could not write to file" + filename, t);
           }
       }
   
  -    public DescriptorRepository readFromFile(String filename)
  -        throws MalformedURLException, ParserConfigurationException, SAXException, IOException
  +    /**
  +     * Write the {@link ConnectionRepository} to the given file name.
  +     */
  +    public void writeToFile(ConnectionRepository repository, String filename)
       {
  -        DescriptorRepository result;
  -		/** JDO branch added by Travis */
  -		if(filename.endsWith(".jdo")){
  -			result =  buildRepositoryFromJdo(filename);
  -
  -		}
  -
  -        boolean useSerializedFile = false;
           try
           {
  -            useSerializedFile =
  -                PersistenceBrokerFactory.getConfigurator().getConfigurationFor(null).getBoolean(
  -                    "useSerializedRepository",
  -                    false);
  +            if(log.isDebugEnabled()) log.debug("## Write connection repository file ##"+
  +                    repository.toXML()+
  +                    "## End of repository file ##");
  +            FileOutputStream fos = new FileOutputStream(filename);
  +            PrintWriter pw = new PrintWriter(fos);
  +            pw.print(repository.toXML());
  +            pw.flush();
  +            pw.close();
           }
  -        catch (ConfigurationException ex)
  +        catch (Throwable t)
           {
  -            // may be savely ignored
  +            log.fatal("Could not write to file" + filename, t);
           }
  +    }
   
  -        File serFile = new File(filename + ".serialized");
  -        if (useSerializedFile && serFile.exists())
  +    /**
  +     * Read the repository configuration file.
  +     * <br>
  +     * If configuration property <i>useSerializedRepository</i> was <code>true</code>
  +     * all subsequent calls read a serialized version of the repository from the
  +     * system tmp dir (the filename argument will be ignored).
  +     */
  +    public DescriptorRepository readDescriptorRepository(String filename)
  +            throws MalformedURLException, ParserConfigurationException, SAXException, IOException
  +    {
  +        DescriptorRepository result;
  +        File serFile = File.createTempFile(SER_FILE_PERFIX, SER_FILE_SUFFIX);
  +        if (useSerializedRepository && serFile.exists())
           {
               try
               {
   
                   result = deserialize(serFile);
  +                //return result;
               }
  -            catch (Throwable t)
  +            catch (Exception e)
               {
  -                LoggerFactory.getBootLogger().error(
  -                    "error in loading serialized repository. Will try to use XML version.",
  -                    t);
  -                result = buildRepository(filename);
  +                log.error("error in loading serialized repository. Will try to use XML version.", e);
  +                result = (DescriptorRepository) buildRepository(filename, DescriptorRepository.class);
               }
  -
           }
           else
           {
  -            result = buildRepository(filename);
  -            if (useSerializedFile)
  -            {
  -                serialize(result, serFile);
  -            }
  +            result = (DescriptorRepository) buildRepository(filename, DescriptorRepository.class);
           }
  -        
           return result;
  +    }
   
  +    /**
  +     * Read the repository configuration file and extract connection handling information.
  +     */
  +    public ConnectionRepository readConnectionRepository(String filename)
  +            throws MalformedURLException, ParserConfigurationException, SAXException, IOException
  +    {
  +        return (ConnectionRepository) buildRepository(filename, ConnectionRepository.class);
       }
   
  -    private DescriptorRepository deserialize(File serFile) throws IOException, ClassNotFoundException
  +    protected DescriptorRepository deserialize(File serFile)
       {
           DescriptorRepository result = null;
  +        long loadingTime = System.currentTimeMillis();
  +        try
  +        {
  +            FileInputStream fis = new FileInputStream(serFile);
  +            // deserialize repository
  +            result = (DescriptorRepository) SerializationUtils.deserialize(fis);
  +            loadingTime = System.currentTimeMillis() - loadingTime;
  +            log.info("loading serialized took " + loadingTime + " msecs");
  +        }
  +        catch (Exception e)
  +        {
  +            log.error("Deserialisation failed, using input path: " + serFile.getAbsolutePath(), e);
  +        }
  +        return result;
  +    }
   
  -        LoggerFactory.getBootLogger().info("loading serialized repository " + serFile.getAbsolutePath());
  +    protected void serialize(DescriptorRepository repository, File file)
  +    {
  +        try
  +        {
  +            FileOutputStream fos = new FileOutputStream(file);
  +            // serialize repository
  +            SerializationUtils.serialize(repository, fos);
  +        }
  +        catch (Exception e)
  +        {
  +            log.error("Serialization failed, using output path: " + file.getAbsolutePath(), e);
  +        }
  +    }
   
  +    /**
  +     * @todo We should re-design the configuration file reading
  +     */
  +    private Object buildRepository(String repositoryFileName, Class targetRepository)
  +            throws MalformedURLException, ParserConfigurationException, SAXException, IOException
  +    {
  +        URL url = buildURL(repositoryFileName);
           long start = System.currentTimeMillis();
  -        FileInputStream fis = new FileInputStream(serFile);
  -        BufferedInputStream bis = new BufferedInputStream(fis);
   
  -        ObjectInputStream ois = new ObjectInputStream(bis);
  +        // get a xml reader instance:
  +        SAXParser p = SAXParserFactory.newInstance().newSAXParser();
  +        XMLReader reader = null;
  +        Object result = null;
  +
  +        if(DescriptorRepository.class.equals(targetRepository))
  +        {
  +            reader = p.getXMLReader();
  +            reader.setFeature("http://xml.org/sax/features/validation", true);
  +            // create an empty repository:
  +            DescriptorRepository repository = new DescriptorRepository();
  +            // create handler for building the repository structure
  +            ContentHandler handler = new RepositoryXmlHandler(repository);
  +            // tell parser to use our handler:
  +            reader.setContentHandler(handler);
  +            reader.parse(new InputSource(url.openStream()));
  +            long stop = System.currentTimeMillis();
  +            //LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs");
   
  -        result = (DescriptorRepository) ois.readObject();
  -        long stop = System.currentTimeMillis();
  -        LoggerFactory.getBootLogger().info("loading serialized took " + (stop - start) + " msecs");
  +            log.info("...Finished parsing for "+targetRepository+". Took " + (stop - start) + " msecs");
  +
  +            if (useSerializedRepository)
  +            {
  +                File tmp = File.createTempFile(SER_FILE_PERFIX, SER_FILE_SUFFIX);
  +                // remove temp. repository when shutdown
  +                tmp.deleteOnExit();
  +                serialize(repository, tmp);
  +            }
  +            result = repository;
  +        }
  +        else if(ConnectionRepository.class.equals(targetRepository))
  +        {
  +            reader = p.getXMLReader();
  +            reader.setFeature("http://xml.org/sax/features/validation", false);
  +            // create an empty repository:
  +            ConnectionRepository repository = new ConnectionRepository();
  +            // create handler for building the repository structure
  +            ContentHandler handler = new ConnectionDescriptorXmlHandler(repository);
  +            // tell parser to use our handler:
  +            reader.setContentHandler(handler);
  +            reader.parse(new InputSource(url.openStream()));
  +            //LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs");
  +            result = repository;
  +        }
  +        else throw new MetadataException("Could not build a repository instance for "+targetRepository);
           return result;
       }
   
  -	/**
  -	 *
  -	 * Builds the repository from a .jdo file.
  -	 *
  -	 * Travis Reeder - travis@spaceprogram.com
  -	 */
  -	private DescriptorRepository buildRepositoryFromJdo(String repositoryFileName)
  -		   throws MalformedURLException, ParserConfigurationException, SAXException, IOException
  -	   {
  -		   String xmlfile = null;
  -		   Logger logger = LoggerFactory.getDefaultLogger();
  -		   //j2ee compliant lookup of resources
  -		   URL url = Thread.currentThread().getContextClassLoader().getResource(repositoryFileName);
  -
  -		   // don't be too strict: if resource is not on the classpath, try ordinary file lookup
  -		   if (url == null)
  -		   {
  -			   try
  -			   {
  -				   url = new File(repositoryFileName).toURL();
  -			   }
  -			   catch (MalformedURLException ignore)
  -			   {
  -			   }
  -		   }
  -
  -		   if (url != null)
  -		   {
  -			   xmlfile = url.toString();
  -			   logger.info("OJB Descriptor Repository: " + xmlfile);
  -		   }
  -		   else
  -		   {
  -			   throw new MalformedURLException("did not find resource " + repositoryFileName);
  -		   }
  -
  -		   long start = System.currentTimeMillis();
  -
  -		   // get a xml reader instance:
  -		   XMLReader reader = null;
  -		   try
  -		   {
  -			   reader = XMLReaderFactory.createXMLReader();
  -		   }
  -		   catch (SAXException ex)
  -		   {
  -			   reader = XMLReaderFactory.createXMLReader("org.apache.crimson.parser.XMLReaderImpl");
  -		   }
  -
  -		   // create an empty repository:
  -		   DescriptorRepository repository = new DescriptorRepository();
  -		   // create handler for building the repository structure
  -//		   ContentHandler handler = new OjbJdoXmlHandler(repository);
  -		   // tell parser to use our handler:
  -//		   reader.setContentHandler(handler);
  -//		   reader.parse(xmlfile);
  -		   long stop = System.currentTimeMillis();
  -		   LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs");
  -
  -		   logger.info("...Finished parsing");
  -
  -		   return repository;
  -	   }
  -
  -    private DescriptorRepository buildRepository(String repositoryFileName)
  -        throws MalformedURLException, ParserConfigurationException, SAXException, IOException
  -    {
  -        String xmlfile = null;
  -        Logger logger = LoggerFactory.getDefaultLogger();
  -        //j2ee compliant lookup of resources  
  +    private URL buildURL(String repositoryFileName) throws MalformedURLException
  +    {
  +        //j2ee compliant lookup of resources
           URL url = Thread.currentThread().getContextClassLoader().getResource(repositoryFileName);
   
  -        // don't be too strict: if resource is not on the classpath, try ordinary file lookup 
  +        // don't be too strict: if resource is not on the classpath, try ordinary file lookup
           if (url == null)
           {
               try
  @@ -256,55 +300,12 @@
   
           if (url != null)
           {
  -            xmlfile = url.toString();
  -            logger.info("OJB Descriptor Repository: " + xmlfile);
  +            log.info("OJB Descriptor Repository: " + url);
           }
           else
           {
               throw new MalformedURLException("did not find resource " + repositoryFileName);
           }
  -
  -        long start = System.currentTimeMillis();
  -
  -        // get a xml reader instance: 
  -        SAXParser p = SAXParserFactory.newInstance().newSAXParser();
  -        XMLReader reader = null;
  -        reader = p.getXMLReader();
  -        reader.setFeature("http://xml.org/sax/features/validation", true);
  -
  -        // create an empty repository:
  -        DescriptorRepository repository = new DescriptorRepository();
  -        // create handler for building the repository structure        
  -        ContentHandler handler = new RepositoryXmlHandler(repository);
  -        // tell parser to use our handler:
  -        reader.setContentHandler(handler);
  -        reader.parse(xmlfile);
  -        long stop = System.currentTimeMillis();
  -        //LoggerFactory.getBootLogger().info("loading XML took " + (stop - start) + " msecs");
  -
  -        logger.info("...Finished parsing. Took " + (stop - start) + " msecs" );
  -
  -        return repository;
  +        return url;
       }
  -
  -    public void serialize(DescriptorRepository repository, File file)
  -    {
  -        try
  -        {
  -            FileOutputStream fos = new FileOutputStream(file);
  -            ObjectOutputStream oos = new ObjectOutputStream(fos);
  -
  -            oos.writeObject(repository);
  -
  -            oos.flush();
  -            oos.close();
  -            fos.flush();
  -            fos.close();
  -        }
  -        catch (Throwable t)
  -        {
  -            LoggerFactory.getDefaultLogger().error("Could not write to file" + file.getAbsolutePath(), t);
  -        }
  -    }
  -
   }
  
  
  
  1.19      +4 -3      jakarta-ojb/src/java/org/apache/ojb/broker/metadata/RepositoryTags.java
  
  Index: RepositoryTags.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/RepositoryTags.java,v
  retrieving revision 1.18
  retrieving revision 1.19
  diff -u -r1.18 -r1.19
  --- RepositoryTags.java	22 Dec 2002 15:56:41 -0000	1.18
  +++ RepositoryTags.java	24 Dec 2002 13:14:33 -0000	1.19
  @@ -91,12 +91,15 @@
       {
           // construct the mapping table
           table = new DoubleHashtable();
  +        table.put("database-repository", new Integer(DATABASE_REPOSITORY));
           table.put("descriptor-repository", new Integer(MAPPING_REPOSITORY));
           table.put("version", new Integer(REPOSITORY_VERSION));
           table.put("isolation-level", new Integer(ISOLATION_LEVEL));
           table.put("jdbc-connection-descriptor", new Integer(JDBC_CONNECTION_DESCRIPTOR));
           table.put("platform", new Integer(DBMS_NAME));
           table.put("schema", new Integer(SCHEMA_NAME));
  +        table.put("jcd-alias", new Integer(JCD_ALIAS));
  +        table.put("default-connection", new Integer(DEFAULT_CONNECTION));
           table.put("driver", new Integer(DRIVER_NAME));
           table.put("protocol", new Integer(URL_PROTOCOL));
           table.put("subprotocol", new Integer(URL_SUBPROTOCOL));
  @@ -149,7 +152,6 @@
           table.put("locking", new Integer(LOCKING));
           table.put("refresh", new Integer(REFRESH_REFERENCE));
           table.put("proxy", new Integer(PROXY_REFERENCE));
  -
           table.put("sort", new Integer(SORT));
   
           table.put("maxActive", new Integer(CON_MAX_ACTIVE));
  @@ -163,6 +165,7 @@
           table.put("timeBetweenEvictionRunsMillis", new Integer(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
           table.put("whenExhaustedAction", new Integer(CON_WHEN_EXHAUSTED_ACTION));
           table.put("connectionFactory", new Integer(CONNECTION_FACTORY));
  +        table.put("validationQuery", new Integer(VALIDATION_QUERY));
           table.put("connection-pool", new Integer(CONNECTION_POOL));
           table.put("class-ref", new Integer(CLASS_REF));
   		table.put("id", new Integer(ID));
  @@ -272,6 +275,4 @@
           result += getClosingTagById(elementId);
           return result;
       }
  -
  -
   }
  
  
  
  1.25      +108 -239  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/RepositoryXmlHandler.java
  
  Index: RepositoryXmlHandler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/RepositoryXmlHandler.java,v
  retrieving revision 1.24
  retrieving revision 1.25
  diff -u -r1.24 -r1.25
  --- RepositoryXmlHandler.java	22 Dec 2002 15:56:42 -0000	1.24
  +++ RepositoryXmlHandler.java	24 Dec 2002 13:14:33 -0000	1.25
  @@ -57,6 +57,7 @@
   import org.apache.ojb.broker.PersistenceBrokerException;
   import org.apache.ojb.broker.util.logging.Logger;
   import org.apache.ojb.broker.util.logging.LoggerFactory;
  +import org.apache.ojb.broker.util.ClassHelper;
   import org.xml.sax.Attributes;
   import org.xml.sax.SAXException;
   import org.xml.sax.SAXParseException;
  @@ -72,13 +73,12 @@
    * @version $Id$
    */
   public class RepositoryXmlHandler
  -    extends DefaultHandler
  -    implements RepositoryElements, IsolationLevels
  +        extends DefaultHandler
  +        implements RepositoryElements, IsolationLevels
   {
  -    private Logger logger;
  +    private Logger logger = LoggerFactory.getLogger(RepositoryXmlHandler.class);
   
       private DescriptorRepository m_repository;
  -    private JdbcConnectionDescriptor m_CurrentJCD;
       private ClassDescriptor m_CurrentCLD;
       private FieldDescriptor m_CurrentFLD;
       private ObjectReferenceDescriptor m_CurrentORD;
  @@ -106,7 +106,7 @@
        *
        * @throws MetadataException if no literal was found in tags mapping
        */
  -    private int getLiteralId(String literal) throws PersistenceBrokerException
  +    private int getLiteralId(String literal) throws MetadataException
       {
           //logger.debug("lookup: " + literal);
           try
  @@ -115,7 +115,8 @@
           }
           catch (NullPointerException t)
           {
  -            throw new MetadataException("unknown literal: '" + literal + "'",t);
  +            throw new MetadataException("Found Unknown literal '" + literal +
  +                    "' in the repository file. Check repository file or/and RepositoryTags.java", t);
           }
   
       }
  @@ -126,15 +127,14 @@
        */
       public RepositoryXmlHandler(DescriptorRepository dr)
       {
  -    	if (dr != null)
  -    	{
  -        	m_repository = dr;
  -    	}
  +        if (dr != null)
  +        {
  +            m_repository = dr;
  +        }
           else
           {
  -        	m_repository = DescriptorRepository.getDefaultInstance();
  +            throw new MetadataException("Given DescriptorRepository argument was null");
           }
  -        logger = LoggerFactory.getLogger(this.getClass());
       }
   
       /**
  @@ -167,7 +167,7 @@
           {
               switch (getLiteralId(qName))
               {
  -                case MAPPING_REPOSITORY :
  +                case MAPPING_REPOSITORY:
                       {
                           String defIso = atts.getValue(tags.getTagById(ISOLATION_LEVEL));
                           if (defIso != null)
  @@ -182,85 +182,17 @@
                           }
                           else
                           {
  -                        	throw new MetadataException("Repository version does not match. expected " +
  -                        		DescriptorRepository.getVersion() + " but found: " +
  -                        		version);
  +                            throw new MetadataException("Repository version does not match. expected " +
  +                                    DescriptorRepository.getVersion() + " but found: " +
  +                                    version+". Please update your repository.dtd and your repository.xml"+
  +                                    " version attribute entry");
                           }
   
                           if (isDebug) logger.debug(" > " + tags.getTagById(MAPPING_REPOSITORY));
   
                           break;
                       }
  -                case JDBC_CONNECTION_DESCRIPTOR :
  -                    {
  -                        if (isDebug) logger.debug("   > " + tags.getTagById(JDBC_CONNECTION_DESCRIPTOR));
  -                        m_CurrentJCD = new JdbcConnectionDescriptor();
  -                        if (m_CurrentCLD == null)
  -                        {
  -                            m_repository.setDefaultJdbcConnection(m_CurrentJCD);
  -                        }
  -                        else
  -                        {
  -                            m_CurrentCLD.setConnectionDescriptor(m_CurrentJCD);
  -                        }
  -                        // set platform attribute
  -                        String platform = atts.getValue(tags.getTagById(DBMS_NAME));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(DBMS_NAME) + ": " + platform);
  -                        m_CurrentJCD.setDbms(platform);
  -
  -                        // set jdbc-level attribute
  -                        String level = atts.getValue(tags.getTagById(JDBC_LEVEL));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(JDBC_LEVEL) + ": " + level);
  -                        m_CurrentJCD.setJdbcLevel(level);
  -
  -                        // set driver attribute
  -                        String driver = atts.getValue(tags.getTagById(DRIVER_NAME));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(DRIVER_NAME) + ": " + driver);
  -                        m_CurrentJCD.setDriver(driver);
  -
  -                        // set protocol attribute
  -                        String protocol = atts.getValue(tags.getTagById(URL_PROTOCOL));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(URL_PROTOCOL) + ": " + protocol);
  -                        m_CurrentJCD.setProtocol(protocol);
  -
  -                        // set subprotocol attribute
  -                        String subprotocol = atts.getValue(tags.getTagById(URL_SUBPROTOCOL));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(URL_SUBPROTOCOL) + ": " + subprotocol);
  -                        m_CurrentJCD.setSubProtocol(subprotocol);
  -
  -                        // set the dbalias attribute
  -                        String dbalias = atts.getValue(tags.getTagById(URL_DBALIAS));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(URL_DBALIAS) + ": " + dbalias);
  -                        m_CurrentJCD.setDbAlias(dbalias);
  -
  -                        // set the datasource attribute
  -                        String datasource = atts.getValue(tags.getTagById(DATASOURCE_NAME));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(DATASOURCE_NAME) + ": " + datasource);
  -                        m_CurrentJCD.setDatasourceName(datasource);
  -
  -                        // set the user attribute
  -                        String user = atts.getValue(tags.getTagById(USER_NAME));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(USER_NAME) + ": " + user);
  -                        m_CurrentJCD.setUserName(user);
  -
  -                        // set the password attribute
  -                        String password = atts.getValue(tags.getTagById(USER_PASSWD));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(USER_PASSWD) + ": " + password);
  -                        m_CurrentJCD.setPassWord(password);
  -
  -                        // set eager-release attribute
  -                        String eagerRelease = atts.getValue(tags.getTagById(EAGER_RELEASE));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(EAGER_RELEASE) + ": " + eagerRelease);
  -                        m_CurrentJCD.setEagerRelease(Boolean.valueOf(eagerRelease).booleanValue());
  -
  -                        // set batch-mode attribute
  -                        String batchMode = atts.getValue(tags.getTagById(BATCH_MODE));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(BATCH_MODE) + ": " + batchMode);
  -                        m_CurrentJCD.setBatchMode(Boolean.valueOf(batchMode).booleanValue());
  -
  -                        break;
  -                    }
  -                case CLASS_DESCRIPTOR :
  +                case CLASS_DESCRIPTOR:
                       {
                           if (isDebug) logger.debug("  > " + tags.getTagById(CLASS_DESCRIPTOR));
                           m_CurrentCLD = new ClassDescriptor(m_repository);
  @@ -279,13 +211,17 @@
                           m_CurrentCLD.setIsolationLevel(getIsoLevel(isoLevel));
                           try
                           {
  -                            m_CurrentCLD.setClassNameOfObject(classname);
  +                            m_CurrentCLD.setClassOfObject(ClassHelper.getClass(classname));
  +                            // put cld to the metadata repository
                               m_repository.put(classname, m_CurrentCLD);
                           }
  -                        catch (Exception ex)
  +                        catch (ClassNotFoundException e)
                           {
  -                            logger.error(ex);
  -                            throw new PersistenceBrokerException(ex);
  +                            m_CurrentCLD = null;
  +                            throw new MetadataException("Class "+classname+" could not be found"
  +                                    +" in the classpath. This could cause unexpected behaviour of OJB,"+
  +                                    " please remove or comment out this class descriptor" +
  +                                    " in the repository.xml file.", e);
                           }
   
                           // set schema attribute
  @@ -325,11 +261,11 @@
                           if (isDebug) logger.debug("     " + tags.getTagById(ROW_READER) + ": " + rowreader);
                           if (rowreader != null)
                           {
  -                            m_CurrentCLD.setRowReaderClassName(rowreader);
  +                            m_CurrentCLD.setRowReader(rowreader);
                           }
   
                           // set if extends
  -                         // set row-reader attribute
  +                        // set row-reader attribute
                           String extendsAtt = atts.getValue(tags.getTagById(EXTENDS));
                           if (isDebug) logger.debug("     " + tags.getTagById(EXTENDS) + ": " + extendsAtt);
                           if (extendsAtt != null)
  @@ -346,45 +282,45 @@
                           break;
                       }
   
  -                case CLASS_EXTENT :
  +                case CLASS_EXTENT:
                       {
                           String classname = atts.getValue("class-ref");
                           if (isDebug) logger.debug("     " + tags.getTagById(CLASS_EXTENT) + ": " + classname);
                           m_CurrentCLD.addExtentClassName(classname);
                           break;
                       }
  -               /* case EXTENDS :
  -                    {
  -                        String classname = atts.getValue("class-ref");
  -                        if (isDebug) logger.debug("     " + tags.getTagById(EXTENDS) + ": " + classname);
  -                        m_CurrentCLD.setSuperClass(classname);
  -
  -                        // get key for super class
  -                        String fieldref = atts.getValue("field-id-ref");
  -                         try
  -                        {
  -                            int fieldId;
  -                            fieldId = Integer.parseInt(fieldref);
  -                            if (isDebug) logger.debug("     " + tags.getTagById(EXTENDS) + ": " +fieldId);
  -                            m_CurrentCLD.setSuperClassFieldRef(fieldId);
  -                        }
  -                        catch (NumberFormatException rex)
  -                        {
  -                            throw new MetadataException(tags.getTagById(EXTENDS)
  -                                                        + " attribute must be an int. Found: "
  -                                                        + fieldref,rex);
  -                        }
  +                    /* case EXTENDS :
  +                         {
  +                             String classname = atts.getValue("class-ref");
  +                             if (isDebug) logger.debug("     " + tags.getTagById(EXTENDS) + ": " + classname);
  +                             m_CurrentCLD.setSuperClass(classname);
  +
  +                             // get key for super class
  +                             String fieldref = atts.getValue("field-id-ref");
  +                              try
  +                             {
  +                                 int fieldId;
  +                                 fieldId = Integer.parseInt(fieldref);
  +                                 if (isDebug) logger.debug("     " + tags.getTagById(EXTENDS) + ": " +fieldId);
  +                                 m_CurrentCLD.setSuperClassFieldRef(fieldId);
  +                             }
  +                             catch (NumberFormatException rex)
  +                             {
  +                                 throw new MetadataException(tags.getTagById(EXTENDS)
  +                                                             + " attribute must be an int. Found: "
  +                                                             + fieldref,rex);
  +                             }
   
   
  -                        break;
  -                    }*/
  +                             break;
  +                         }*/
   
  -                case FIELD_DESCRIPTOR :
  +                case FIELD_DESCRIPTOR:
                       {
                           if (isDebug) logger.debug("    > " + tags.getTagById(FIELD_DESCRIPTOR));
   
                           int id = Integer.parseInt(atts.getValue("id"));
  -                        m_CurrentFLD = new FieldDescriptor(id);
  +                        m_CurrentFLD = new FieldDescriptor(m_CurrentCLD, id);
                           m_CurrentCLD.addFieldDescriptor(m_CurrentFLD);
   
                           // prepare for custom attributes
  @@ -393,7 +329,7 @@
                           String fieldName = atts.getValue(tags.getTagById(FIELD_NAME));
                           if (isDebug) logger.debug("     " + tags.getTagById(FIELD_NAME) + ": " + fieldName);
                           String classname = m_CurrentCLD.getClassNameOfObject();
  -                        m_CurrentFLD.setPersistentField(classname, fieldName);
  +                        m_CurrentFLD.setPersistentField(ClassHelper.getClass(classname), fieldName);
   
                           String columnName = atts.getValue(tags.getTagById(COLUMN_NAME));
                           if (isDebug) logger.debug("     " + tags.getTagById(COLUMN_NAME) + ": " + columnName);
  @@ -411,9 +347,9 @@
                           String nullable = atts.getValue(tags.getTagById(NULLABLE));
                           if (nullable != null)
                           {
  -                        	if (isDebug) logger.debug("     " + tags.getTagById(NULLABLE) + ": " + nullable);
  -                        	b = ! (new Boolean(nullable)).booleanValue();
  -                        	m_CurrentFLD.setRequired(b);
  +                            if (isDebug) logger.debug("     " + tags.getTagById(NULLABLE) + ": " + nullable);
  +                            b = !(new Boolean(nullable)).booleanValue();
  +                            m_CurrentFLD.setRequired(b);
                           }
   
                           String indexed = atts.getValue(tags.getTagById(INDEXED));
  @@ -474,24 +410,25 @@
   
                           break;
                       }
  -                case REFERENCE_DESCRIPTOR :
  +                case REFERENCE_DESCRIPTOR:
                       {
                           if (isDebug) logger.debug("    > " + tags.getTagById(REFERENCE_DESCRIPTOR));
  -                        m_CurrentORD = new ObjectReferenceDescriptor();
  +                        m_CurrentORD = new ObjectReferenceDescriptor(m_CurrentCLD);
  +                        // now we add the new descriptor
                           m_CurrentCLD.addObjectReferenceDescriptor(m_CurrentORD);
   
  -						// prepare for custom attributes
  +                        // prepare for custom attributes
                           this.m_CurrentAttrContainer = m_CurrentORD;
   
                           // set name attribute
                           name = atts.getValue(tags.getTagById(FIELD_NAME));
                           if (isDebug) logger.debug("     " + tags.getTagById(FIELD_NAME) + ": " + name);
  -                        m_CurrentORD.setPersistentField(m_CurrentCLD.getClassNameOfObject(), name);
  +                        m_CurrentORD.setPersistentField(m_CurrentCLD.getClassOfObject(), name);
   
                           // set class-ref attribute
                           String classRef = atts.getValue(tags.getTagById(REFERENCED_CLASS));
                           if (isDebug) logger.debug("     " + tags.getTagById(REFERENCED_CLASS) + ": " + classRef);
  -						m_CurrentORD.setItemClassName(classRef);
  +                        m_CurrentORD.setItemClass(ClassHelper.getClass(classRef));
   
                           // set proxy attribute
                           String proxy = atts.getValue(tags.getTagById(PROXY_REFERENCE));
  @@ -526,7 +463,7 @@
                           break;
                       }
   
  -                case FOREIGN_KEY :
  +                case FOREIGN_KEY:
                       {
                           if (isDebug) logger.debug("    > " + tags.getTagById(FOREIGN_KEY));
                           String fieldIdRef = atts.getValue(tags.getTagById(FIELD_ID_REF));
  @@ -541,46 +478,45 @@
                           catch (NumberFormatException rex)
                           {
                               throw new MetadataException(tags.getTagById(FIELD_ID_REF)
  -                                                        + " attribute must be an int. Found: "
  -                                                        + fieldIdRef,rex);
  +                                    + " attribute must be an int. Found: "
  +                                    + fieldIdRef + ". Please check your repository file.", rex);
                           }
                           break;
                       }
   
  -                case COLLECTION_DESCRIPTOR :
  +                case COLLECTION_DESCRIPTOR:
                       {
                           if (isDebug) logger.debug("    > " + tags.getTagById(COLLECTION_DESCRIPTOR));
  -                        m_CurrentCOD = new CollectionDescriptor();
  -                        m_CurrentCLD.addCollectionDescriptor(m_CurrentCOD);
  +                        m_CurrentCOD = new CollectionDescriptor(m_CurrentCLD);
   
  -						// prepare for custom attributes
  +
  +                        // prepare for custom attributes
                           this.m_CurrentAttrContainer = m_CurrentCOD;
   
                           // set name attribute
                           name = atts.getValue(tags.getTagById(FIELD_NAME));
                           if (isDebug) logger.debug("     " + tags.getTagById(FIELD_NAME) + ": " + name);
  -                        m_CurrentCOD.setPersistentField(m_CurrentCLD.getClassNameOfObject(), name);
  +                        m_CurrentCOD.setPersistentField(m_CurrentCLD.getClassOfObject(), name);
   
                           // set collection-class attribute
                           String collectionClassName = atts.getValue(tags.getTagById(COLLECTION_CLASS));
                           if (collectionClassName != null)
                           {
  -                        	if (isDebug) logger.debug("     " + tags.getTagById(COLLECTION_CLASS) + ": " + collectionClassName);
  - 	                       	m_CurrentCOD.setCollectionClassName(collectionClassName);
  +                            if (isDebug) logger.debug("     " + tags.getTagById(COLLECTION_CLASS) + ": " + collectionClassName);
  +                            m_CurrentCOD.setCollectionClass(ClassHelper.getClass(collectionClassName));
                           }
                           // set element-class-ref attribute
                           String elementClassRef = atts.getValue(tags.getTagById(ITEMS_CLASS));
                           if (isDebug) logger.debug("     " + tags.getTagById(ITEMS_CLASS) + ": " + elementClassRef);
                           if (elementClassRef != null)
                           {
  -                        	m_CurrentCOD.setItemClassName(elementClassRef);
  +                            m_CurrentCOD.setItemClass(ClassHelper.getClass(elementClassRef));
                           }
   
                           //set orderby and sort attributes:
                           String orderby = atts.getValue(tags.getTagById(ORDERBY));
                           String sort = atts.getValue(tags.getTagById(SORT));
                           if (isDebug) logger.debug("     " + tags.getTagById(SORT) + ": " + orderby + ", " + sort);
  -
                           if (orderby != null)
                           {
                               m_CurrentCOD.addOrderBy(orderby, "ASC".equalsIgnoreCase(sort));
  @@ -621,20 +557,22 @@
                           b = (new Boolean(autoDelete)).booleanValue();
                           m_CurrentCOD.setCascadeDelete(b);
   
  +                        m_CurrentCLD.addCollectionDescriptor(m_CurrentCOD);
  +
                           break;
                       }
                   case ORDERBY :
  -                    {    
  +                    {
                           if (isDebug) logger.debug("    > " + tags.getTagById(ORDERBY));
                           name = atts.getValue(tags.getTagById(FIELD_NAME));
                           if (isDebug) logger.debug("     " + tags.getTagById(FIELD_NAME) + ": " + name);
                           String sort = atts.getValue(tags.getTagById(SORT));
                           if (isDebug) logger.debug("     " + tags.getTagById(SORT) + ": " + name + ", " + sort);
  -                        
  +
                           m_CurrentCOD.addOrderBy(name, "ASC".equalsIgnoreCase(sort));
                           break;
                       }
  -                case INVERSE_FK :
  +                case INVERSE_FK:
                       {
                           if (isDebug) logger.debug("    > " + tags.getTagById(INVERSE_FK));
                           String fieldIdRef = atts.getValue(tags.getTagById(FIELD_ID_REF));
  @@ -649,13 +587,13 @@
                           catch (NumberFormatException rex)
                           {
                               throw new MetadataException(tags.getTagById(FIELD_ID_REF)
  -                                                        + " attribute must be an int. Found: "
  -                                                        + fieldIdRef,rex);
  +                                    + " attribute must be an int. Found: "
  +                                    + fieldIdRef + " Please check your repository file.", rex);
                           }
                           break;
                       }
   
  -                case FK_POINTING_TO_THIS_CLASS :
  +                case FK_POINTING_TO_THIS_CLASS:
                       {
                           if (isDebug) logger.debug("    > " + tags.getTagById(FK_POINTING_TO_THIS_CLASS));
                           String column = atts.getValue("column");
  @@ -664,7 +602,7 @@
                           break;
                       }
   
  -                case FK_POINTING_TO_ITEMS_CLASS :
  +                case FK_POINTING_TO_ITEMS_CLASS:
                       {
                           if (isDebug) logger.debug("    > " + tags.getTagById(FK_POINTING_TO_ITEMS_CLASS));
                           String column = atts.getValue("column");
  @@ -672,74 +610,20 @@
                           m_CurrentCOD.addFkToItemClass(column);
                           break;
                       }
  -                case CONNECTION_POOL :
  +                case ATTRIBUTE:
                       {
  -                        if (isDebug) logger.debug("    > " + tags.getTagById(CONNECTION_POOL));
  -                        ConnectionPoolDescriptor m_CurrentCPD = m_CurrentJCD.getConnectionPoolDescriptor();
  -
  -                        String maxActive = atts.getValue(tags.getTagById(CON_MAX_ACTIVE));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_MAX_ACTIVE) + ": " + maxActive);
  -                        if(checkString(maxActive)) m_CurrentCPD.setMaxActive(new Integer(maxActive).intValue());
  -
  -                        String maxIdle = atts.getValue(tags.getTagById(CON_MAX_IDLE));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_MAX_IDLE) + ": " + maxIdle);
  -                        if(checkString(maxIdle)) m_CurrentCPD.setMaxIdle(new Integer(maxIdle).intValue());
  -
  -                        String maxWait = atts.getValue(tags.getTagById(CON_MAX_WAIT));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_MAX_WAIT) + ": " + maxWait);
  -                        if(checkString(maxWait)) m_CurrentCPD.setMaxWait(new Integer(maxWait).intValue());
  -
  -                        String minEvictableIdleTimeMillis = atts.getValue(tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS) + ": " + minEvictableIdleTimeMillis);
  -                        if(checkString(minEvictableIdleTimeMillis)) m_CurrentCPD.setMinEvictableIdleTimeMillis(new Long(minEvictableIdleTimeMillis).longValue());
  -
  -                        String numTestsPerEvictionRun = atts.getValue(tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN) + ": " + numTestsPerEvictionRun);
  -                        if(checkString(numTestsPerEvictionRun)) m_CurrentCPD.setNumTestsPerEvictionRun(new Integer(numTestsPerEvictionRun).intValue());
  -
  -                        String testOnBorrow = atts.getValue(tags.getTagById(CON_TEST_ON_BORROW));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_TEST_ON_BORROW) + ": " + testOnBorrow);
  -                        if(checkString(testOnBorrow)) m_CurrentCPD.setTestOnBorrow(new Boolean(testOnBorrow).booleanValue());
  -
  -                        String testOnReturn = atts.getValue(tags.getTagById(CON_TEST_ON_RETURN));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_TEST_ON_RETURN) + ": " + testOnReturn);
  -                        if(checkString(testOnReturn)) m_CurrentCPD.setTestOnReturn(new Boolean(testOnReturn).booleanValue());
  -
  -                        String testWhileIdle = atts.getValue(tags.getTagById(CON_TEST_WHILE_IDLE));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_TEST_WHILE_IDLE) + ": " + testWhileIdle);
  -                        if(checkString(testWhileIdle)) m_CurrentCPD.setTestWhileIdle(new Boolean(testWhileIdle).booleanValue());
  -
  -                        String timeBetweenEvictionRunsMillis = atts.getValue(tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS) + ": " + timeBetweenEvictionRunsMillis);
  -                        if(checkString(timeBetweenEvictionRunsMillis)) m_CurrentCPD.setTimeBetweenEvictionRunsMillis(new Long(timeBetweenEvictionRunsMillis).longValue());
  -
  -                        String whenExhaustedAction = atts.getValue(tags.getTagById(CON_WHEN_EXHAUSTED_ACTION));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CON_WHEN_EXHAUSTED_ACTION) + ": " + whenExhaustedAction);
  -                        if(checkString(whenExhaustedAction)) m_CurrentCPD.setWhenExhaustedAction(new Byte(whenExhaustedAction).byteValue());
  -
  -                        String connectionFactoryStr = atts.getValue(tags.getTagById(CONNECTION_FACTORY));
  -                        if (isDebug) logger.debug("     " + tags.getTagById(CONNECTION_FACTORY) + ": " + connectionFactoryStr);
  -                        if(checkString(connectionFactoryStr)) m_CurrentCPD.setConnectionFactory(connectionFactoryStr);
  -                        break;
  -                    }
  -
  -               case ATTRIBUTE :
  -                    {
  -                    	//handle custom attributes
  +                        //handle custom attributes
                           String attributeName = atts.getValue(tags.getTagById(ATTRIBUTE_NAME));
                           String attributeValue = atts.getValue(tags.getTagById(ATTRIBUTE_VALUE));
                           if (isDebug) logger.debug("    > " + tags.getTagById(ATTRIBUTE));
                           if (isDebug) logger.debug("     " + tags.getTagById(ATTRIBUTE_NAME) + ": " + attributeName);
                           if (isDebug) logger.debug("     " + tags.getTagById(ATTRIBUTE_VALUE) + ": " + attributeValue);
                           // If we have a container to store this attribute in, then do so.
  -                        if (this.m_CurrentAttrContainer!=null)
  +                        if (this.m_CurrentAttrContainer != null)
                           {
  -                            this.m_CurrentAttrContainer.addAttribute(attributeName,attributeValue);
  +                            this.m_CurrentAttrContainer.addAttribute(attributeName, attributeValue);
                           }
  -
                       }
  -
  -
                   default :
                       {
                           // nop
  @@ -748,8 +632,10 @@
           }
           catch (Exception ex)
           {
  -            logger.error(ex);
  -            throw new PersistenceBrokerException(ex);
  +            // logger.error(ex);
  +            if(ex instanceof MetadataException) throw (MetadataException)ex;
  +            else throw new MetadataException("Exception when reading metadata information,"+
  +                    " please check your repository.xml file", ex);
           }
       }
   
  @@ -764,89 +650,73 @@
       public void endElement(String uri, String name, String qName)
       {
           boolean isDebug = logger.isDebugEnabled();
  -
           try
           {
               switch (getLiteralId(qName))
               {
  -                case MAPPING_REPOSITORY :
  +                case MAPPING_REPOSITORY:
                       {
                           if (isDebug) logger.debug(" < " + tags.getTagById(MAPPING_REPOSITORY));
                           break;
                       }
  -                case JDBC_CONNECTION_DESCRIPTOR :
  -                    {
  -                        if (isDebug) logger.debug("   < " + tags.getTagById(JDBC_CONNECTION_DESCRIPTOR));
  -                        break;
  -                    }
  -                case CONNECTION_POOL :
  -                    {
  -                        if (isDebug) logger.debug("   < " + tags.getTagById(CONNECTION_POOL));
  -                        break;
  -                    }
  -                case CLASS_DESCRIPTOR :
  +                case CLASS_DESCRIPTOR:
                       {
                           if (isDebug) logger.debug("  < " + tags.getTagById(CLASS_DESCRIPTOR));
                           m_CurrentCLD = null;
                           m_CurrentAttrContainer = null;
                           break;
                       }
  -                case CLASS_EXTENT :
  +                case CLASS_EXTENT:
                       {
                           break;
                       }
  -
  -                case FIELD_DESCRIPTOR :
  +                case FIELD_DESCRIPTOR:
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(FIELD_DESCRIPTOR));
                           m_CurrentFLD = null;
                           m_CurrentAttrContainer = m_CurrentCLD;
                           break;
                       }
  -                case REFERENCE_DESCRIPTOR :
  +                case REFERENCE_DESCRIPTOR:
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(REFERENCE_DESCRIPTOR));
                           m_CurrentORD = null;
                           m_CurrentAttrContainer = m_CurrentCLD;
                           break;
                       }
  -                case FOREIGN_KEY :
  +                case FOREIGN_KEY:
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(FOREIGN_KEY));
                           break;
                       }
  -
  -                case COLLECTION_DESCRIPTOR :
  +                case COLLECTION_DESCRIPTOR:
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(COLLECTION_DESCRIPTOR));
                           m_CurrentCOD = null;
                           m_CurrentAttrContainer = m_CurrentCLD;
                           break;
                       }
  -
  -                case INVERSE_FK :
  +                case INVERSE_FK:
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(INVERSE_FK));
                           break;
                       }
  -
                   case ORDERBY :
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(ORDERBY));
                           break;
                       }
  -
  -                case FK_POINTING_TO_THIS_CLASS :
  +                case FK_POINTING_TO_THIS_CLASS:
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(FK_POINTING_TO_THIS_CLASS));
                           break;
                       }
  -                case FK_POINTING_TO_ITEMS_CLASS :
  +                case FK_POINTING_TO_ITEMS_CLASS:
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(FK_POINTING_TO_ITEMS_CLASS));
                           break;
                       }
  -                case ATTRIBUTE :
  +                case ATTRIBUTE:
                       {
                           if (isDebug) logger.debug("    < " + tags.getTagById(ATTRIBUTE));
                           break;
  @@ -859,14 +729,15 @@
                       // handle failure:
                   default :
                       {
  -                        logger.error("Ignoring unknown Element " + qName);
  +                        logger.info("Ignoring unused Element " + qName);
                       }
               }
           }
           catch (Exception ex)
           {
  -            logger.error(ex);
  -            throw new PersistenceBrokerException(ex);
  +            if(ex instanceof MetadataException) throw (MetadataException) ex;
  +            else throw new MetadataException("Exception when reading metadata information,"+
  +                    " please check your repository.xml file", ex);
           }
       }
   
  @@ -938,6 +809,4 @@
           logger.warn("unknown isolation-level: " + isoLevel + " using RW_UNCOMMITTED as default");
           return defIsoLevel;
       }
  -
  -
   }
  
  
  
  1.17      +73 -56    jakarta-ojb/src/java/org/apache/ojb/broker/metadata/JdbcConnectionDescriptor.java
  
  Index: JdbcConnectionDescriptor.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/JdbcConnectionDescriptor.java,v
  retrieving revision 1.16
  retrieving revision 1.17
  diff -u -r1.16 -r1.17
  --- JdbcConnectionDescriptor.java	22 Dec 2002 15:56:41 -0000	1.16
  +++ JdbcConnectionDescriptor.java	24 Dec 2002 13:14:33 -0000	1.17
  @@ -58,6 +58,9 @@
   
   import org.apache.ojb.broker.util.logging.Logger;
   import org.apache.ojb.broker.util.logging.LoggerFactory;
  +import org.apache.commons.lang.builder.ToStringBuilder;
  +import org.apache.commons.lang.builder.ToStringStyle;
  +import org.apache.commons.lang.SystemUtils;
   
   /**
    * JdbcConnectionDescriptor describes all relevant parameters of
  @@ -68,32 +71,60 @@
    */
   public class JdbcConnectionDescriptor implements Serializable, XmlCapable
   {
  -    protected Logger logger;
  +    private Logger logger = LoggerFactory.getLogger(JdbcConnectionDescriptor.class);
   
  -    protected String m_Dbms = null;
  -    protected String m_Driver = null;
  -    protected String m_Protocol = null;
  -    protected String m_SubProtocol = null;
  -    protected String m_DbAlias = null;
  -    protected String m_DatasourceName = null;
  -    protected String m_UserName = null;
  -    protected String m_Password = null;
  -    protected double m_JdbcLevel = 2.0;
  -    protected Integer descriptorKey;
  -    protected ConnectionPoolDescriptor cpd;
  -    protected boolean m_eagerRelease = false;
  -    protected boolean m_batchMode = false;
  +    private String m_jcdAlias;
  +    private String m_Dbms;
  +    private String m_Driver;
  +    private String m_Protocol;
  +    private String m_SubProtocol;
  +    private String m_DbAlias;
  +    private String m_DatasourceName;
  +    private String m_UserName;
  +    private String m_Password;
  +    private double m_JdbcLevel = 2.0;
  +    private boolean m_eagerRelease = false;
  +    private boolean m_batchMode = false;
  +    private boolean m_defaultConnection = false;
  +    private Integer descriptorKey;
  +    private ConnectionPoolDescriptor cpd;
   
       /**
        * Constructor declaration
        */
       public JdbcConnectionDescriptor()
       {
  -        logger = LoggerFactory.getLogger(this.getClass());
           cpd = new ConnectionPoolDescriptor();
       }
   
       /**
  +     * Get the alias name for this descriptor.
  +     */
  +    public String getJcdAlias()
  +    {
  +        return m_jcdAlias;
  +    }
  +
  +    /**
  +     * Set an alias name for this descriptor.
  +     */
  +    public void setJcdAlias(String jcdAlias)
  +    {
  +        this.clearDescriptorKey();
  +        this.m_jcdAlias = jcdAlias;
  +    }
  +
  +    public boolean isDefaultConnection()
  +    {
  +        return m_defaultConnection;
  +    }
  +
  +    public void setDefaultConnection(boolean defaultConnection)
  +    {
  +        this.m_defaultConnection = defaultConnection;
  +    }
  +
  +    /**
        * Returns the connection pool descriptor.
        */
       public ConnectionPoolDescriptor getConnectionPoolDescriptor()
  @@ -116,16 +147,9 @@
       {
           if (descriptorKey == null)
           {
  -            StringBuffer buf = new StringBuffer();
  -            buf.append(m_Dbms);
  -            buf.append(m_DbAlias);
  -            buf.append(m_DatasourceName);
  -            buf.append(m_UserName);
  -            buf.append(m_Password);
  -            buf.append(m_Protocol);
  -            buf.append(m_SubProtocol);
  -            buf.append(m_eagerRelease);
  -            buf.append(m_batchMode);
  +            StringBuffer buf = new StringBuffer(m_jcdAlias);
  +            buf.append(getUserName());
  +            buf.append(getPassWord());
               descriptorKey = new Integer(buf.toString().hashCode());
           }
           return descriptorKey;
  @@ -137,29 +161,26 @@
       }
   
       /**
  -     * Method declaration
  -     * @return
  +     * Returns a String representation of this class.
        */
       public String toString()
       {
  -        return "JdbcConnectionDescriptor\n"
  -            + "DBMS:" + m_Dbms
  -            + "\n"
  -            + "DRIVER: " + m_Driver
  -            + "\n"
  -            + "PROTOCOL: " + m_Protocol
  -            + "\n"
  -            + "SUBPROTOCOL: " + m_SubProtocol
  -            + "\n"
  -            + "DBALIAS: " + m_DbAlias
  -            + "\n"
  -            + "USERNAME: " + m_UserName
  -            + "\n"
  -            + "PASSWORD: " + m_Password
  -            + "\n"
  -            + "EAGER RELEASE: " + m_eagerRelease
  -            + "\n"
  -            + "BATCH MODE: " + m_batchMode;
  +        ToStringBuilder buf = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE);
  +        buf.
  +        append("jcd-alias", m_jcdAlias).
  +        append("default-connection", m_defaultConnection).
  +        append("dbms", m_Dbms).
  +        append("jdbc-level", m_JdbcLevel).
  +        append("driver", m_Driver).
  +        append("protocol", m_Protocol).
  +        append("sub-protocol", m_SubProtocol).
  +        append("db-alias", m_DbAlias).
  +        append("user", m_UserName).
  +        append("password", m_Password).
  +        append("eager-release", m_eagerRelease).
  +        append("ConnectionPoolDescriptor", cpd).
  +        append("batchMode", cpd);
  +        return buf.toString();
       }
   
       /**
  @@ -177,7 +198,6 @@
        */
       public void setDbms(String str)
       {
  -        this.clearDescriptorKey();
           m_Dbms = str;
       }
   
  @@ -214,7 +234,6 @@
        */
       public void setProtocol(String str)
       {
  -        this.clearDescriptorKey();
           m_Protocol = str;
       }
   
  @@ -233,7 +252,6 @@
        */
       public void setSubProtocol(String str)
       {
  -        this.clearDescriptorKey();
           m_SubProtocol = str;
       }
   
  @@ -252,7 +270,6 @@
        */
       public void setDbAlias(String str)
       {
  -        this.clearDescriptorKey();
           m_DbAlias = str;
       }
   
  @@ -428,7 +445,6 @@
        */
       public void setDatasourceName(String datasourceName)
       {
  -        this.clearDescriptorKey();
           m_DatasourceName = datasourceName;
       }
   
  @@ -447,7 +463,6 @@
        */
       public void setJdbcLevel(String jdbcLevel)
       {
  -        this.clearDescriptorKey();
           if (jdbcLevel != null)
           {
               try
  @@ -469,11 +484,12 @@
               logger.info("set to default of jdbc level of 2.0 ");
           }
       }
  +
       public void setJdbcLevel(double jdbcLevel)
       {
           m_JdbcLevel = jdbcLevel;
       }
  -    
  +
       public boolean getEagerRelease()
       {
       	return m_eagerRelease;
  @@ -481,7 +497,6 @@
   
       public void setEagerRelease(boolean flag)
       {
  -        this.clearDescriptorKey();
       	m_eagerRelease = flag;
       }
   
  @@ -503,11 +518,13 @@
       public String toXML()
       {
           RepositoryTags tags = RepositoryTags.getInstance();
  -        String eol = System.getProperty("line.separator");
  +        String eol = SystemUtils.LINE_SEPARATOR;
   
           String strReturn = eol + "  <!-- Descriptor for Connection " + getProtocol() + ":" + getSubProtocol() + ":" + getDbAlias() + " -->" + eol;
   
           strReturn += "  " + tags.getOpeningTagNonClosingById(JDBC_CONNECTION_DESCRIPTOR) + eol;
  +        strReturn += "    " + tags.getAttribute(JCD_ALIAS, this.getJcdAlias())  + eol;
  +        strReturn += "    " + tags.getAttribute(DEFAULT_CONNECTION, ""+this.isDefaultConnection())  + eol;
           strReturn += "    " + tags.getAttribute(DBMS_NAME, this.getDbms())  + eol;
           strReturn += "    " + tags.getAttribute(JDBC_LEVEL, "" + this.getJdbcLevel()) + eol;
   
  @@ -524,7 +541,7 @@
           	strReturn += "    " + tags.getAttribute(URL_SUBPROTOCOL, this.getSubProtocol()) + eol;
           	strReturn += "    " + encode(tags.getAttribute(URL_DBALIAS, this.getDbAlias())) + eol;
           	strReturn += "    " + tags.getAttribute(EAGER_RELEASE, "" + this.getEagerRelease()) + eol;
  -        	strReturn += "    " + tags.getAttribute(BATCH_MODE, "" + this.getBatchMode()) + eol;
  +            strReturn += "    " + tags.getAttribute(BATCH_MODE, "" + this.getBatchMode()) + eol;
           }
           //username is optional
           String user = getUserName();
  @@ -577,4 +594,4 @@
           }
           return retval.toString();
       }
  -}
  +}
  \ No newline at end of file
  
  
  
  1.3       +19 -7     jakarta-ojb/src/java/org/apache/ojb/broker/metadata/IndexDescriptor.java
  
  Index: IndexDescriptor.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/IndexDescriptor.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- IndexDescriptor.java	17 Jun 2002 19:34:09 -0000	1.2
  +++ IndexDescriptor.java	24 Dec 2002 13:14:33 -0000	1.3
  @@ -56,34 +56,46 @@
   
   import java.util.Vector;
   
  -public class IndexDescriptor {
  +/**
  + *
  + *
  + * @version $Id$
  + */
  +public class IndexDescriptor
  +{
   
       private int id = 0;
       private String name;
       private boolean unique;
       private Vector indexColumns = new Vector();
   
  -    public boolean isUnique() {
  +    public boolean isUnique()
  +    {
           return unique;
       }
   
  -    public void setUnique(boolean unique) {
  +    public void setUnique(boolean unique)
  +    {
           this.unique = unique;
       }
   
  -    public String getName() {
  +    public String getName()
  +    {
           return name;
       }
   
  -    public void setName(String name) {
  +    public void setName(String name)
  +    {
           this.name = name;
       }
   
  -    public Vector getIndexColumns() {
  +    public Vector getIndexColumns()
  +    {
           return this.indexColumns;
       }
   
  -    public void setIndexColumns(Vector indexColumns) {
  +    public void setIndexColumns(Vector indexColumns)
  +    {
           this.indexColumns = indexColumns;
       }
   }
  
  
  
  1.14      +189 -195  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/FieldDescriptor.java
  
  Index: FieldDescriptor.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/FieldDescriptor.java,v
  retrieving revision 1.13
  retrieving revision 1.14
  diff -u -r1.13 -r1.14
  --- FieldDescriptor.java	21 Nov 2002 22:54:25 -0000	1.13
  +++ FieldDescriptor.java	24 Dec 2002 13:14:33 -0000	1.14
  @@ -54,18 +54,25 @@
    * <http://www.apache.org/>.
    */
   
  -import java.sql.Types;
  -import java.util.Comparator;
  -
  +import org.apache.commons.lang.builder.ToStringBuilder;
  +import org.apache.ojb.broker.OJBRuntimeException;
   import org.apache.ojb.broker.accesslayer.conversions.FieldConversion;
   import org.apache.ojb.broker.accesslayer.conversions.FieldConversionDefaultImpl;
  -import org.apache.ojb.broker.util.logging.LoggingHelper;
  +import org.apache.ojb.broker.util.ClassHelper;
  +
  +import java.sql.Types;
  +import java.util.Comparator;
   
   /**
    * A FieldDescriptor holds the mapping information for a specific member-variable
  + * of a persistent object.
  + * <br>
  + * Note: Be careful when use references of this class or caching instances of this class,
  + * because instances could become invalid (see {@link MetadataManager}).
  + *
    * @author <a href="mailto:thma@apache.org">Thomas Mahler<a>
    */
  -public class FieldDescriptor extends AttributeDescriptorBase implements XmlCapable
  +public final class FieldDescriptor extends AttributeDescriptorBase implements XmlCapable
   {
       private int m_ColNo;
       private String m_ColumnName;
  @@ -84,10 +91,8 @@
       private boolean precisionSpecified = false;
       private boolean lengthSpecified = false;
       private FieldConversion fieldConversion = null;
  -    private String fieldConversionClassName = null;
  -	// true if field is used for optimistic locking BRJ
  -	private boolean locking = false;
  -
  +    // true if field is used for optimistic locking BRJ
  +    private boolean locking = false;
   
       /**
        * returns a comparator that allows to sort a Vector of FieldMappingDecriptors
  @@ -114,59 +119,22 @@
                       return 0;
                   }
               }
  -
           };
       }
   
       /**
        * Constructor declaration
  -     * @param id
  +     *
  +     * @param cld The parent {@link ClassDescriptor}
  +     * @param id A field id - unique against all other fields in the {@link ClassDescriptor}
        */
  -    public FieldDescriptor(int id)
  +    public FieldDescriptor(ClassDescriptor cld, int id)
       {
  +        super(cld);
           m_ColNo = id;
       }
   
  -    public boolean isIndexed()
  -    {
  -        return indexed;
  -    }
  -
  -    public void setIndexed(boolean indexed)
  -    {
  -        this.indexed = indexed;
  -    }
  -
  -    public boolean isAutoIncrement()
  -    {
  -        return autoIncrement;
  -    }
  -
  -    public void setAutoIncrement(boolean autoIncrement)
  -    {
  -        this.autoIncrement = autoIncrement;
  -    }
  -
  -    public String getSequenceName()
  -    {
  -        return sequenceName;
  -    }
  -
  -    public void setSequenceName(String sequenceName)
  -    {
  -        this.sequenceName = sequenceName;
  -    }
  -
  -
  -
  -
  -
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @return
  -     *
        *
        */
       public String getColumnName()
  @@ -201,18 +169,26 @@
           return m_ColumnType;
       }
   
  -	/**
  -	 * returns the JDBC type (represented as an int value as specified
  +    /**
  +     *
  +     */
  +    public void setColumnType(String str)
  +    {
  +        m_ColumnType = str;
  +    }
  +
  +    /**
  +     * returns the JDBC type (represented as an int value as specified
        * by java.sql.Types) of a FIELDDESCRIPTOR.
  -	 */
  -	public int getColumnJdbcType()
  -	{
  -	    if (m_ColumnTypeId == -99999)
  -	    {
  -	     	m_ColumnTypeId = getJdbcType();
  -	    }
  -	    return m_ColumnTypeId;
  -	}
  +     */
  +    public int getColumnJdbcType()
  +    {
  +        if (m_ColumnTypeId == -99999)
  +        {
  +            m_ColumnTypeId = getJdbcType();
  +        }
  +        return m_ColumnTypeId;
  +    }
   
   
       /**
  @@ -271,13 +247,13 @@
           else if (type.equals("longvarbinary"))
               result = Types.LONGVARBINARY;
   
  -		else if (type.equals("clob"))
  -     		result = Types.CLOB;
  -		else if (type.equals("blob"))
  -			result = Types.BLOB;
  +        else if (type.equals("clob"))
  +            result = Types.CLOB;
  +        else if (type.equals("blob"))
  +            result = Types.BLOB;
           else
  -            throw new RuntimeException(
  -                "The type "
  +            throw new OJBRuntimeException(
  +                    "The type "
                       + getColumnType()
                       + " for attribute "
                       + getColumnName()
  @@ -285,14 +261,84 @@
           return result;
       }
   
  +    /**
  +     * Returns a string representation of this class.
  +     */
  +    public String toString()
  +    {
  +        // here we got value of all fields
  +        return ToStringBuilder.reflectionToString(this);
  +    }
  +
  +    /**
  +     * Gets the fieldConversion.
  +     * @return Returns a FieldConversion
  +     */
  +    public FieldConversion getFieldConversion()
  +    {
  +        // if no conversion is specified use the default conversion
  +        if (fieldConversion == null)
  +        {
  +            setFieldConversion(new FieldConversionDefaultImpl());
  +        }
  +        return fieldConversion;
  +    }
   
  +    /**
  +     * Sets the fieldConversion.
  +     * @param fieldConversion The fieldConversion to set
  +     * @deprecated use setFieldConversionClassName instead
  +     */
  +    public void setFieldConversion(FieldConversion fieldConversion)
  +    {
  +        this.fieldConversion = fieldConversion;
  +    }
   
       /**
  -     *
  +     * Sets the fieldConversion.
  +     * @param fieldConversion The fieldConversion to set
        */
  -    public void setColumnType(String str)
  +    public void setFieldConversionClassName(String fieldConversionClassName)
       {
  -        m_ColumnType = str;
  +        try
  +        {
  +            this.fieldConversion = (FieldConversion) ClassHelper.newInstance(fieldConversionClassName);
  +        }
  +        catch (Exception e)
  +        {
  +            throw new MetadataException(
  +                    "Could not instantiate FieldConversion class using default constructor",e);
  +        }
  +    }
  +
  +    public boolean isIndexed()
  +    {
  +        return indexed;
  +    }
  +
  +    public void setIndexed(boolean indexed)
  +    {
  +        this.indexed = indexed;
  +    }
  +
  +    public boolean isAutoIncrement()
  +    {
  +        return autoIncrement;
  +    }
  +
  +    public void setAutoIncrement(boolean autoIncrement)
  +    {
  +        this.autoIncrement = autoIncrement;
  +    }
  +
  +    public String getSequenceName()
  +    {
  +        return sequenceName;
  +    }
  +
  +    public void setSequenceName(String sequenceName)
  +    {
  +        this.sequenceName = sequenceName;
       }
   
       /**
  @@ -320,93 +366,93 @@
       }
   
       /**
  -     * Returns a string representation of this class.
  +     * Gets the locking.
  +     * @return Returns a boolean
        */
  -    public String toString()
  +    public boolean isLocking()
       {
  -//        return "\n\n" + getPersistentField().toString() + "\n" + m_ColumnName + "\n" + m_ColumnType
  -//                + "\n" + m_IsKeyField + "\n" + m_ColNo;
  -
  -         // here we got value of all fields
  -         return LoggingHelper.traceObject(this);
  +        return locking;
       }
   
  +    /**
  +     * Sets the locking.
  +     * @param locking The locking to set
  +     */
  +    public void setLocking(boolean locking)
  +    {
  +        this.locking = locking;
  +    }
   
  -	/**
  -	 * Gets the locking.
  -	 * @return Returns a boolean
  -	 */
  -	public boolean isLocking()
  -	{
  -		return locking;
  -	}
  -
  -	/**
  -	 * Sets the locking.
  -	 * @param locking The locking to set
  -	 */
  -	public void setLocking(boolean locking)
  -	{
  -		this.locking = locking;
  -	}
  -
  -    public void setLength(int length) {
  +    public void setLength(int length)
  +    {
           this.length = length;
       }
   
  -    public int getLength() {
  +    public int getLength()
  +    {
           return this.length;
       }
   
  -    public void setPrecision(int precision) {
  +    public void setPrecision(int precision)
  +    {
           this.precision = precision;
       }
   
  -    public int getPrecision() {
  +    public int getPrecision()
  +    {
           return this.precision;
       }
   
  -    public void setScale(int scale) {
  +    public void setScale(int scale)
  +    {
           this.scale = scale;
       }
   
  -    public int getScale() {
  +    public int getScale()
  +    {
           return this.scale;
       }
   
  -    public boolean isRequired() {
  +    public boolean isRequired()
  +    {
           return required;
       }
   
  -    public void setRequired(boolean required) {
  +    public void setRequired(boolean required)
  +    {
           this.required = required;
       }
   
  -    public boolean isScaleSpecified() {
  +    public boolean isScaleSpecified()
  +    {
           return scaleSpecified;
       }
   
  -    public void setScaleSpecified(boolean scaleSpecified) {
  +    public void setScaleSpecified(boolean scaleSpecified)
  +    {
           this.scaleSpecified = scaleSpecified;
       }
   
  -    public boolean isPrecisionSpecified() {
  +    public boolean isPrecisionSpecified()
  +    {
           return precisionSpecified;
       }
   
  -    public void setPrecisionSpecified(boolean precisionSpecified) {
  +    public void setPrecisionSpecified(boolean precisionSpecified)
  +    {
           this.precisionSpecified = precisionSpecified;
       }
   
  -    public boolean isLengthSpecified() {
  +    public boolean isLengthSpecified()
  +    {
           return lengthSpecified;
       }
   
  -    public void setLengthSpecified(boolean lengthSpecified) {
  +    public void setLengthSpecified(boolean lengthSpecified)
  +    {
           this.lengthSpecified = lengthSpecified;
       }
   
  -
       /*
        * @see XmlCapable#toXML()
        */
  @@ -428,116 +474,64 @@
           // table not yet implemented
   
           // column
  - 		result += "        " + tags.getAttribute(COLUMN_NAME,this.getColumnName()) + eol;
  +        result += "        " + tags.getAttribute(COLUMN_NAME, this.getColumnName()) + eol;
   
  - 		// jdbc-type
  - 		result += "        " + tags.getAttribute(JDBC_TYPE, this.getColumnType()) + eol;
  +        // jdbc-type
  +        result += "        " + tags.getAttribute(JDBC_TYPE, this.getColumnType()) + eol;
   
  -		// primarykey
  - 		if (this.isPrimaryKey())
  - 		{
  - 		    result += "        " + tags.getAttribute(PRIMARY_KEY,"true") + eol;
  - 		}
  -
  -		// nullable
  - 		if (this.isRequired())
  - 		{
  - 		    result += "        " + tags.getAttribute(NULLABLE,"false") + eol;
  - 		}
  -
  -		// indexed not yet implemented
  -
  -		// autoincrement
  - 		if (this.isAutoIncrement())
  - 		{
  - 		 	result   += "        " + tags.getAttribute(AUTO_INCREMENT, "true") + eol;
  - 		}
  -
  -		// locking
  - 		if (this.isLocking())
  - 		{
  - 		 	result   += "        " + tags.getAttribute(LOCKING, "true") + eol;
  - 		}
  +        // primarykey
  +        if (this.isPrimaryKey())
  +        {
  +            result += "        " + tags.getAttribute(PRIMARY_KEY, "true") + eol;
  +        }
  +
  +        // nullable
  +        if (this.isRequired())
  +        {
  +            result += "        " + tags.getAttribute(NULLABLE, "false") + eol;
  +        }
  +
  +        // indexed not yet implemented
  +
  +        // autoincrement
  +        if (this.isAutoIncrement())
  +        {
  +            result += "        " + tags.getAttribute(AUTO_INCREMENT, "true") + eol;
  +        }
  +
  +        // locking
  +        if (this.isLocking())
  +        {
  +            result += "        " + tags.getAttribute(LOCKING, "true") + eol;
  +        }
   
           // default-fetch not yet implemented
   
           // conversion
           if (this.getFieldConversion().getClass() != FieldConversionDefaultImpl.class)
           {
  -        	result   += "        " + tags.getAttribute(FIELD_CONVERSION, getFieldConversion().getClass().getName()) + eol;
  +            result += "        " + tags.getAttribute(FIELD_CONVERSION, getFieldConversion().getClass().getName()) + eol;
           }
   
           // length
           if (this.isLengthSpecified())
           {
  -        	result   += "        " + tags.getAttribute(LENGTH, "" + getLength()) + eol;
  +            result += "        " + tags.getAttribute(LENGTH, "" + getLength()) + eol;
           }
   
           // precision
           if (this.isPrecisionSpecified())
           {
  -        	result   += "        " + tags.getAttribute(PRECISION, "" + getPrecision()) + eol;
  +            result += "        " + tags.getAttribute(PRECISION, "" + getPrecision()) + eol;
           }
   
           // scale
           if (this.isScaleSpecified())
           {
  -        	result   += "        " + tags.getAttribute(SCALE, "" + getScale()) + eol;
  +            result += "        " + tags.getAttribute(SCALE, "" + getScale()) + eol;
           }
   
  -
           result += "      />" + eol;
           return result;
  -
  -    }
  -
  -    /**
  -     * Gets the fieldConversion.
  -     * @return Returns a FieldConversion
  -     */
  -    public FieldConversion getFieldConversion()
  -    {
  -        // if no conversion is specified use the default conversion
  -        if (fieldConversion == null)
  -        {
  -        	if (fieldConversionClassName == null)
  -        	{
  -         		setFieldConversion(new FieldConversionDefaultImpl());
  -        	}
  -        	else
  -        	{
  -                try
  -                {
  -                    Class clazz = Class.forName(fieldConversionClassName, true,
  -                                		Thread.currentThread().getContextClassLoader());
  -                    setFieldConversion((FieldConversion)clazz.newInstance());
  -                }
  -                catch (Exception e)
  -                {
  -                	throw new MetadataException(e);
  -                }
  -        	}
  -        }
  -        return fieldConversion;
       }
  -
  -    /**
  -     * Sets the fieldConversion.
  -     * @param fieldConversion The fieldConversion to set
  -     * @deprecated use setFieldConversionClassName instead
  -     */
  -    public void setFieldConversion(FieldConversion fieldConversion)
  -    {
  -        this.fieldConversion = fieldConversion;
  -    }
  -
  -    /**
  -     * Sets the fieldConversion.
  -     * @param fieldConversion The fieldConversion to set
  -     */
  -    public void setFieldConversionClassName(String fieldConversionClassName)
  -    {
  -        this.fieldConversionClassName = fieldConversionClassName;
  -    }
  -
   }
  
  
  
  1.27      +173 -327  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/DescriptorRepository.java
  
  Index: DescriptorRepository.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/DescriptorRepository.java,v
  retrieving revision 1.26
  retrieving revision 1.27
  diff -u -r1.26 -r1.27
  --- DescriptorRepository.java	28 Nov 2002 22:19:25 -0000	1.26
  +++ DescriptorRepository.java	24 Dec 2002 13:14:33 -0000	1.27
  @@ -54,11 +54,9 @@
    * <http://www.apache.org/>.
    */
   
  -import org.apache.ojb.broker.PBKey;
  +import org.apache.commons.lang.builder.ToStringBuilder;
  +import org.apache.commons.lang.SystemUtils;
   import org.apache.ojb.broker.PersistenceBrokerException;
  -import org.apache.ojb.broker.singlevm.PersistenceBrokerConfiguration;
  -import org.apache.ojb.broker.util.configuration.impl.OjbConfigurator;
  -import org.apache.ojb.broker.util.logging.LoggerFactory;
   
   import java.io.Serializable;
   import java.util.ArrayList;
  @@ -73,79 +71,41 @@
   import java.util.Vector;
   
   /**
  - * The repository containing all mapping information of the PersistenceBroker.
  - * The data is stored in a xml file "repository.xml" in the directory of the main class.
  + * The repository containing all object mapping and manipulation information of
  + * all used persistent objects.
  + * <br>
  + * Note: Be careful when use references of this class or caching instances of this class,
  + * because instances could become invalid (see {@link MetadataManager}).
    *
    * @author <a href="mailto:thma@apache.org">Thomas Mahler<a>
    * @author <a href="mailto:leandro@ibnetwork.com.br">Leandro Rodrigo Saad Cruz<a>
    * @version $Id$
  - *
  - * @todo
  - * check for better solution! One DR per PBKey or one DR per repository file?
  - * When doing DR changes at runtime, how should we handle that?
    */
  -public class DescriptorRepository implements Serializable, XmlCapable, IsolationLevels
  +public final class DescriptorRepository implements Serializable, XmlCapable, IsolationLevels
   {
       /**
  -     * Map manage all descriptor repository instances.
  -     */
  -    private static Map repositories = Collections.synchronizedMap(new HashMap());
  -
  -    /**
        * The version identifier of the Repository.
        * Used to validate repository.xml against the dtd.
        */
       private static final String VERSION = "0.9.8";
  -
  -    /**
  -     * Default used PBKey.
  -     */
  -    private static PBKey defaultPBKey;
  -
  -    static
  -    {
  -        /* @todo better solution for init */
  -        getDefaultInstance();
  -    }
  -
  -    //*****************************************************
  -
       /**
  -     * Key to identify this repository instance.
  +     * the default isolation level used for this repository
        */
  -    private PBKey pbKey;
  -
  +    private int defaultIsolationLevel = IsolationLevels.IL_DEFAULT;
       /**
        * This table holds all known Mapping descriptions.
        * Key values are the respective Class objects
        */
       private Hashtable descriptorTable = new Hashtable();
  -
       /**
        * We need a lot the extent, to which a class belongs
        * (@see DescriptorRepository#getExtentClass). To speed up the costy
        * evaluation, we use this tiny hash map.
        */
       private HashMap extentTable = new HashMap();
  -
  -    /**
  -     * The Descriptor of a default JDBC connection, to be used when no
  -     * individual descriptor is given for a certain class
  -     */
  -    private JdbcConnectionDescriptor defaultConnectionDescriptor;
  -
  -    /**
  -     * the default siolation level used for this repository
  -     */
  -    private int defaultIsolationLevel = IsolationLevels.IL_DEFAULT;
  -
       private Map m_multiMappedTableMap = new HashMap();
  -
       private Map m_extentClassTable = new HashMap();
   
  -    //*****************************************************
  -    // constructor
  -
       /**
        * Constructor declaration
        */
  @@ -153,164 +113,11 @@
       {
       }
   
  -    //*****************************************************
  -    // static methods
  -
  -    /**
  -     * Returns the repository associated with the given
  -     * {@link org.apache.ojb.broker.PBKey}.
  -     */
  -    public static DescriptorRepository getInstance(PBKey pbKey)
  -            throws MetadataException
  -    {
  -        DescriptorRepository ret = (DescriptorRepository) repositories.get(pbKey);
  -        if (ret == null)
  -        {
  -            RepositoryPersistor persistor = new RepositoryPersistor();
  -            try
  -            {
  -                ret = persistor.readFromFile(pbKey.getRepositoryFile());
  -                prepareJdbcConnectionDescriptor(pbKey, ret.getDefaultJdbcConnection());
  -                ret.setPBKey(pbKey);
  -                repositories.put(pbKey, ret);
  -            }
  -            catch (Throwable t)
  -            {
  -                LoggerFactory.getDefaultLogger().fatal(t);
  -                throw new MetadataException(t);
  -            }
  -        }
  -        return ret;
  -    }
  -
  -    /**
  -     * Returns the 'default' repository, specified in the OJB.properties file.
  -     */
  -    public static DescriptorRepository getDefaultInstance() throws MetadataException
  -    {
  -        if (defaultPBKey == null)
  -        {
  -            String defaultRepositoryName = ((PersistenceBrokerConfiguration) OjbConfigurator.getInstance()
  -                    .getConfigurationFor(null)).getRepositoryFilename();
  -            String user = null;
  -            String password = null;
  -            DescriptorRepository ret = readFromRepository(new PBKey(defaultRepositoryName));
  -            JdbcConnectionDescriptor jcd = ret.getDefaultJdbcConnection();
  -            user = jcd.getUserName();
  -            password = jcd.getPassWord();
  -            defaultPBKey = new PBKey(defaultRepositoryName, user, password);
  -        }
  -        return getInstance(defaultPBKey);
  -    }
  -
  -    public static void setDefaultPBKey(PBKey key)
  -    {
  -        defaultPBKey = key;
  -    }
  -
  -    public static PBKey getDefaultPBKey()
  -    {
  -        return defaultPBKey;
  -    }
  -
  -    public static DescriptorRepository readFromRepository(PBKey pbKey) throws MetadataException
  -    {
  -        DescriptorRepository desRep = null;
  -        RepositoryPersistor persistor = new RepositoryPersistor();
  -        try
  -        {
  -            desRep = persistor.readFromFile(pbKey.getRepositoryFile());
  -            prepareJdbcConnectionDescriptor(pbKey, desRep.getDefaultJdbcConnection());
  -            desRep.setPBKey(pbKey);
  -        }
  -        catch (Exception e)
  -        {
  -            LoggerFactory.getDefaultLogger().error(e);
  -            throw new MetadataException(e);
  -        }
  -        return desRep;
  -    }
  -
  -    /**
  -     * Helper method: Because it's allowed to pass user/password with the PBKey
  -     * without declare it in the repository file, we had take care of it
  -     * and replace the dummies from the repository.
  -     */
  -    private static void prepareJdbcConnectionDescriptor(PBKey key, JdbcConnectionDescriptor jcd)
  -    {
  -        if (key.getUser() != null)
  -        {
  -            jcd.setUserName(key.getUser());
  -            jcd.setPassWord(key.getPassword());
  -        }
  -    }
  -
  -
  -    //*****************************************************
  -    // methods
  -
  -
  -    private void setPBKey(PBKey key)
  -    {
  -        this.pbKey = key;
  -    }
  -
  -    public PBKey getPBkey()
  -    {
  -        return this.pbKey;
  -    }
  -
  -    /**
  -     * returns a string representation
  -     */
  -    public String toString()
  -    {
  -        //return "DescriptorRepository\n" + defaultConnectionDescriptor + "\n" + descriptorTable + "\n" + "";
  -        return DescriptorRepository.class.getName() + " associated with PBKey " + pbKey;
  -    }
  -
  -    /**
  -     * Method declaration
  -     * @param jcd
  -     */
  -    public void setDefaultJdbcConnection(JdbcConnectionDescriptor jcd)
  -    {
  -        defaultConnectionDescriptor = jcd;
  -    }
  -
  -    /**
  -     * Return the {@link JdbcConnectionDescriptor} of the repository.
  -     */
  -    public JdbcConnectionDescriptor getDefaultJdbcConnection()
  -    {
  -        return defaultConnectionDescriptor;
  -    }
  -
  -    /**
  -     * Add a ClassDescriptor to the internal Hashtable<br>
  -     * Set the Repository for ClassDescriptor
  -     */
  -    public void put(Class c, ClassDescriptor cld)
  -    {
  -        this.put(c.getName(), cld);
  -    }
  -
  -    /**
  -     * Add a ClassDescriptor to the internal Hashtable<br>
  -     * Set the Repository for ClassDescriptor
  -     */
  -    public void put(String classname, ClassDescriptor cld)
  +    public static String getVersion()
       {
  -        cld.setRepository(this); // BRJ
  -        descriptorTable.put(classname, cld);
  -        Vector extentClasses = cld.getExtentClasses();
  -        for (int i = 0; i < extentClasses.size(); ++i)
  -        {
  -            addExtent(((Class) extentClasses.get(i)).getName(), cld);
  -        }
  +        return VERSION;
       }
   
  -
       /**
        * Add a pair of extent/classdescriptor to the extentTable to gain speed
        * while retrieval of extents.
  @@ -325,38 +132,6 @@
           }
       }
   
  -
  -    /**
  -     * lookup a ClassDescriptor in the internal Hashtable
  -     */
  -    public ClassDescriptor getDescriptorFor(Class c) throws ClassNotPersistenceCapableException
  -    {
  -        return this.getDescriptorFor(c.getName());
  -    }
  -
  -    /**
  -     * lookup a ClassDescriptor in the internal Hashtable
  -     * @param strClassName a fully qualified class name as it is returned by Class.getName().
  -     */
  -    public ClassDescriptor getDescriptorFor(String strClassName) throws ClassNotPersistenceCapableException
  -    {
  -        ClassDescriptor result = (ClassDescriptor) descriptorTable.get(strClassName);
  -        if (result == null)
  -        {
  -            throw new ClassNotPersistenceCapableException(strClassName + " not found in OJB Repository");
  -        }
  -        else
  -        {
  -            return result;
  -        }
  -    }
  -
  -    public boolean hasDescriptorFor(Class c)
  -    {
  -        ClassDescriptor result = (ClassDescriptor) descriptorTable.get(c.getName());
  -        return (result != null);
  -    }
  -
       /**
        * returns the Extent to which the class clazz belongs.
        * This may be a baseclass,an interface or clazz itself, if no Extent
  @@ -393,80 +168,9 @@
           return retval;
       }
   
  -    public Iterator iterator()
  -    {
  -        return descriptorTable.values().iterator();
  -    }
  -
  -    /*
  -     * @see XmlCapable#toXML()
  -     */
  -    public String toXML()
  -    {
  -        RepositoryTags tags = RepositoryTags.getInstance();
  -        String eol = System.getProperty("line.separator");
  -
  -        // 1. write XML header
  -        String strReturn = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + eol;
  -
  -        strReturn += "<!DOCTYPE descriptor-repository SYSTEM \"repository.dtd\" [" + eol;
  -        strReturn += "<!ENTITY user SYSTEM \"repository_user.xml\">" + eol;
  -        strReturn += "<!ENTITY junit SYSTEM \"repository_junit.xml\">" + eol;
  -        strReturn += "<!ENTITY internal SYSTEM \"repository_internal.xml\"> ]>" + eol + eol;
  -
  -        strReturn += "<!-- OJB RepositoryPersistor generated this file on " + new Date().toString() + " -->" + eol;
   
   
  -        // 1a. write opening tab and attributes
  -        strReturn += tags.getOpeningTagNonClosingById(MAPPING_REPOSITORY) + eol;
  -        strReturn += "  " + tags.getAttribute(REPOSITORY_VERSION, getVersion()) + eol;
  -        strReturn += "  " + tags.getAttribute(ISOLATION_LEVEL, this.getDefaultIsolationLevelAsString()) + eol;
   
  -        strReturn += ">" + eol;
  -
  -        // 2. write default JdbcConnectionDescriptor
  -        strReturn += this.getDefaultJdbcConnection().toXML();
  -
  -        // 3. write all ClassDescriptors
  -        Iterator i = this.iterator();
  -        while (i.hasNext())
  -        {
  -            strReturn += ((XmlCapable) i.next()).toXML() + eol;
  -        }
  -        // 4. write closing tag
  -        return strReturn + tags.getClosingTagById(MAPPING_REPOSITORY);
  -
  -    }
  -
  -    /**
  -     * returns IsolationLevel literal as matching
  -     * to the corresponding id
  -     * @return the IsolationLevel literal
  -     */
  -    private String getDefaultIsolationLevelAsString()
  -    {
  -        if (defaultIsolationLevel == IL_READ_UNCOMMITTED)
  -        {
  -            return LITERAL_IL_READ_UNCOMMITTED;
  -        }
  -        else if (defaultIsolationLevel == IL_READ_COMMITTED)
  -        {
  -            return LITERAL_IL_READ_COMMITTED;
  -        }
  -        else if (defaultIsolationLevel == IL_REPEATABLE_READ)
  -        {
  -            return LITERAL_IL_REPEATABLE_READ;
  -        }
  -        else if (defaultIsolationLevel == IL_SERIALIZABLE)
  -        {
  -            return LITERAL_IL_SERIALIZABLE;
  -        }
  -        else if (defaultIsolationLevel == IL_OPTIMISTIC)
  -        {
  -            return LITERAL_IL_OPTIMISTIC;
  -        }
  -        return LITERAL_IL_READ_UNCOMMITTED;
  -    }
   
   
       /**
  @@ -501,7 +205,8 @@
                   {
                       /**
                        * MBAIRD
  -                     * hashmap will only allow one entry per unique key, so no need to check contains(fields[i].getColumnName()).
  +                     * hashmap will only allow one entry per unique key,
  +                     * so no need to check contains(fields[i].getColumnName()).
                        */
                       map.put(fields[i].getColumnName(), fields[i]);
                   }
  @@ -542,23 +247,6 @@
           return descriptorTable;
       }
   
  -    public void printDescriptorTable()
  -    {
  -        Enumeration enum = descriptorTable.keys();
  -        Enumeration enum2 = descriptorTable.elements();
  -        while (enum.hasMoreElements())
  -        {
  -            Object cl = enum.nextElement();
  -            ClassDescriptor descriptor = (ClassDescriptor) enum2.nextElement();
  -            System.out.println(cl + " - " + descriptor.getFullTableName());
  -        }
  -    }
  -
  -    public static String getVersion()
  -    {
  -        return VERSION;
  -    }
  -
       /**
        *
        * Utility method to discover all concrete subclasses of a given super class. <br>
  @@ -592,6 +280,78 @@
           return concreteSubclasses;
       }
   
  +    /**
  +     * Checks if repository contains given class.
  +     */
  +    public boolean hasDescriptorFor(Class c)
  +    {
  +        return descriptorTable.containsKey(c.getName());
  +    }
  +
  +    /**
  +     * lookup a ClassDescriptor in the internal Hashtable
  +     * @param strClassName a fully qualified class name as it is returned by Class.getName().
  +     */
  +    public ClassDescriptor getDescriptorFor(String strClassName) throws ClassNotPersistenceCapableException
  +    {
  +        ClassDescriptor result = (ClassDescriptor) descriptorTable.get(strClassName);
  +        if (result == null)
  +        {
  +            throw new ClassNotPersistenceCapableException(strClassName + " not found in OJB Repository");
  +        }
  +        else
  +        {
  +            return result;
  +        }
  +    }
  +
  +    /**
  +     * lookup a ClassDescriptor in the internal Hashtable
  +     */
  +    public ClassDescriptor getDescriptorFor(Class c) throws ClassNotPersistenceCapableException
  +    {
  +        return this.getDescriptorFor(c.getName());
  +    }
  +
  +    /**
  +     * Convenience for {@link #put(Class c, ClassDescriptor cld)}
  +     */
  +    public void setClassDescriptor(ClassDescriptor cld)
  +    {
  +        this.put(cld.getClassNameOfObject(), cld);
  +    }
  +
  +    /**
  +     * Add a ClassDescriptor to the internal Hashtable<br>
  +     * Set the Repository for ClassDescriptor
  +     */
  +    public void put(Class c, ClassDescriptor cld)
  +    {
  +        this.put(c.getName(), cld);
  +    }
  +
  +    /**
  +     * Add a ClassDescriptor to the internal Hashtable<br>
  +     * Set the Repository for ClassDescriptor
  +     */
  +    public void put(String classname, ClassDescriptor cld)
  +    {
  +        cld.setRepository(this); // BRJ
  +        descriptorTable.put(classname, cld);
  +        Vector extentClasses = cld.getExtentClasses();
  +        for (int i = 0; i < extentClasses.size(); ++i)
  +        {
  +            addExtent(((Class) extentClasses.get(i)).getName(), cld);
  +        }
  +    }
  +
  +    /**
  +     * Returns an iterator over all managed {@link ClassDescriptor}.
  +     */
  +    public Iterator iterator()
  +    {
  +        return descriptorTable.values().iterator();
  +    }
   
       /**
        * Returns the defaultIsolationLevel.
  @@ -611,4 +371,90 @@
           this.defaultIsolationLevel = defaultIsolationLevel;
       }
   
  +    /**
  +     * returns a string representation
  +     */
  +    public String toString()
  +    {
  +        Enumeration enum = descriptorTable.keys();
  +        Enumeration enum2 = descriptorTable.elements();
  +        ToStringBuilder buf = new ToStringBuilder(this);
  +        while (enum.hasMoreElements())
  +        {
  +            Object cl = enum.nextElement();
  +            ClassDescriptor descriptor = (ClassDescriptor) enum2.nextElement();
  +            buf.append(cl.toString(), descriptor.getFullTableName());
  +        }
  +        return buf.toString();
  +    }
  +
  +    /*
  +     * @see XmlCapable#toXML()
  +     */
  +    public String toXML()
  +    {
  +        RepositoryTags tags = RepositoryTags.getInstance();
  +        String eol = SystemUtils.LINE_SEPARATOR;
  +
  +        // 1. write XML header
  +        String strReturn = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + eol;
  +
  +        strReturn += "<!DOCTYPE descriptor-repository SYSTEM \"repository.dtd\" [" + eol;
  +        strReturn += "<!ENTITY database-metadata SYSTEM \""+ConnectionRepository.DATABASE_METADATA_FILENAME+"\">" + eol;
  +        strReturn += "<!ENTITY user SYSTEM \"repository_user.xml\">" + eol;
  +        strReturn += "<!ENTITY junit SYSTEM \"repository_junit.xml\">" + eol;
  +        strReturn += "<!ENTITY internal SYSTEM \"repository_internal.xml\"> ]>" + eol + eol;
  +
  +        strReturn += "<!-- OJB RepositoryPersistor generated this file on " + new Date().toString() + " -->" + eol;
  +
  +        // 1a. write opening tab and attributes
  +        strReturn += tags.getOpeningTagNonClosingById(MAPPING_REPOSITORY) + eol;
  +        strReturn += "  " + tags.getAttribute(REPOSITORY_VERSION, getVersion()) + eol;
  +        strReturn += "  " + tags.getAttribute(ISOLATION_LEVEL, this.getIsolationLevelAsString()) + eol;
  +
  +        strReturn += ">" + eol;
  +
  +        // 2. Connection stuff was separated in ConnectionRepository, use ENTITY 'database' attribute
  +        strReturn +=eol+"<!-- include ojb database mapping -->"+eol;
  +        strReturn +="&database-metadata;"+eol+eol;
  +
  +        // 3. write all ClassDescriptors
  +        Iterator i = this.iterator();
  +        while (i.hasNext())
  +        {
  +            strReturn += ((XmlCapable) i.next()).toXML() + eol;
  +        }
  +        // 4. write closing tag
  +        return strReturn + tags.getClosingTagById(MAPPING_REPOSITORY);
  +    }
  +
  +    /**
  +     * returns IsolationLevel literal as matching
  +     * to the corresponding id
  +     * @return the IsolationLevel literal
  +     */
  +    private String getIsolationLevelAsString()
  +    {
  +        if (defaultIsolationLevel == IL_READ_UNCOMMITTED)
  +        {
  +            return LITERAL_IL_READ_UNCOMMITTED;
  +        }
  +        else if (defaultIsolationLevel == IL_READ_COMMITTED)
  +        {
  +            return LITERAL_IL_READ_COMMITTED;
  +        }
  +        else if (defaultIsolationLevel == IL_REPEATABLE_READ)
  +        {
  +            return LITERAL_IL_REPEATABLE_READ;
  +        }
  +        else if (defaultIsolationLevel == IL_SERIALIZABLE)
  +        {
  +            return LITERAL_IL_SERIALIZABLE;
  +        }
  +        else if (defaultIsolationLevel == IL_OPTIMISTIC)
  +        {
  +            return LITERAL_IL_OPTIMISTIC;
  +        }
  +        return LITERAL_IL_READ_UNCOMMITTED;
  +    }
   }
  
  
  
  1.2       +5 -11     jakarta-ojb/src/java/org/apache/ojb/broker/metadata/DescriptorBase.java
  
  Index: DescriptorBase.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/DescriptorBase.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- DescriptorBase.java	6 Oct 2002 12:54:54 -0000	1.1
  +++ DescriptorBase.java	24 Dec 2002 13:14:33 -0000	1.2
  @@ -67,29 +67,25 @@
   	/** holds user defined attributes */
       private Map attributeList = null;
   
  -
       /**
        * Constructor for DescriptorBase.
        */
       public DescriptorBase()
       {
  -        super();
       }
   
  -
   	/**
   	 * @see org.apache.ojb.broker.metadata.AttributeContainer#addAttribute(String, String)
   	 */
      public void addAttribute(String attributeName, String attributeValue)
      {
  -
           // Don't allow null attribute names.
  -        if (attributeName==null) 
  +        if (attributeName==null)
           {
               return;
           }
           // Set up the attribute list
  -        if (attributeList==null) 
  +        if (attributeList==null)
           {
               attributeList=new HashMap();
           }
  @@ -103,17 +99,17 @@
       public String getAttribute(String attributeName, String defaultValue)
       {
           String result = null;
  -        if (attributeList!=null) 
  +        if (attributeList!=null)
           {
               result = (String)attributeList.get(attributeName);
  -            if (result==null) 
  +            if (result==null)
               {
                   result = defaultValue;
               }
           }
           return result;
       }
  -    
  +
   	/**
   	 * @see org.apache.ojb.broker.metadata.AttributeContainer#getAttribute(String)
   	 */
  @@ -121,6 +117,4 @@
       {
           return this.getAttribute(attributeName,null);
       }
  -
  -
   }
  
  
  
  1.7       +6 -13     jakarta-ojb/src/java/org/apache/ojb/broker/metadata/ConnectionPoolDescriptor.java
  
  Index: ConnectionPoolDescriptor.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/ConnectionPoolDescriptor.java,v
  retrieving revision 1.6
  retrieving revision 1.7
  diff -u -r1.6 -r1.7
  --- ConnectionPoolDescriptor.java	28 Nov 2002 22:19:25 -0000	1.6
  +++ ConnectionPoolDescriptor.java	24 Dec 2002 13:14:33 -0000	1.7
  @@ -62,6 +62,7 @@
   import org.apache.ojb.broker.util.configuration.impl.OjbConfigurator;
   import org.apache.ojb.broker.util.logging.LoggerFactory;
   import org.apache.ojb.broker.util.pooling.PoolConfiguration;
  +import org.apache.ojb.broker.util.ClassHelper;
   
   import java.io.Serializable;
   
  @@ -102,21 +103,13 @@
   
       public Class getConnectionFactory()
       {
  -        return connectionFactory;
  +        return this.connectionFactory;
       }
   
  -    public void setConnectionFactory(String connectionFactory)
  +    public void setConnectionFactory(Class connectionFactory)
       {
  -        if (connectionFactory == null) return;
  -        try
  -        {
  -            this.connectionFactory = Class.forName(connectionFactory);
  -        }
  -        catch (ClassNotFoundException e)
  -        {
  -            LoggerFactory.getDefaultLogger().error("Enlisted ConnectionFactory name " +
  -                    connectionFactory + " could not be found, check repository files and OJB property file", e);
  -        }
  +        if (connectionFactory == null) throw new MetadataException("Given ConnectionFactory was null");
  +        this.connectionFactory = connectionFactory;
       }
   }
   
  
  
  
  1.14      +53 -95    jakarta-ojb/src/java/org/apache/ojb/broker/metadata/CollectionDescriptor.java
  
  Index: CollectionDescriptor.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/CollectionDescriptor.java,v
  retrieving revision 1.13
  retrieving revision 1.14
  diff -u -r1.13 -r1.14
  --- CollectionDescriptor.java	16 Dec 2002 18:18:57 -0000	1.13
  +++ CollectionDescriptor.java	24 Dec 2002 13:14:33 -0000	1.14
  @@ -54,47 +54,60 @@
    * <http://www.apache.org/>.
    */
   
  -import java.util.ArrayList;
  -import java.util.Collection;
  -import java.util.Vector;
  +import org.apache.ojb.broker.util.ClassHelper;
  +import org.apache.commons.lang.SystemUtils;
   
  +import java.util.Vector;
  +import java.util.Collection;
  +import java.util.ArrayList;
   
   
   /**
    * mapping Description for member fields that are Collections
  + * <br>
  + * Note: Be careful when use references of this class or caching instances of this class,
  + * because instances could become invalid (see {@link MetadataManager}).
  + *
    * @author <a href="mailto:thma@apache.org">Thomas Mahler<a>
    * @version $Id$
    */
   public class CollectionDescriptor extends ObjectReferenceDescriptor
   {
  -
       /**
        * Represents the type of the collection, if set to null,
        * a java.util.Vector will be used.
        * If set to a valid collection type it will be used to build typed collections.
        */
       private Class collectionClass = null;
  -    
       /**
  -     * the name of the collection class
  -     */
  -    private String collectionClassName = null;
  -
  -    /**
  -     * the Collection of orderby Fields 
  +     * the Collection of orderby Fields
        */
       private Collection m_orderby = new ArrayList();
  -
  -
       /**
        * For m:n related Classes this is the indirection table.
        */
       private String indirectionTable = null;
  +    private Vector fksToItemClass = null;
  +    private Vector fksToThisClass = null;
  +//    /**
  +//     * define the order of the resulting collection BRJ
  +//     */
  +//    private String orderBy;
  +//	private boolean ascending = true;
  +    /**
  +     * define loading strategy of the resulting collection BRJ
  +     */
  +	private boolean lazy = false;
   
       /**
  -     *
  +     * if true relationship is refreshed when owner is found in cache
        */
  -    private Vector fksToItemClass = null;
  +	private boolean refresh = false;
  +
  +    public CollectionDescriptor(ClassDescriptor descriptor)
  +    {
  +        super(descriptor);
  +    }
   
       public Object[] getFksToThisClass()
       {
  @@ -105,7 +118,7 @@
       {
           this.fksToThisClass = fksToThisClass;
       }
  -    
  +
       /**
        * add a FK column pointing to This Class
        */
  @@ -113,7 +126,7 @@
       {
         	if (fksToThisClass == null)
         	{
  -      	 	fksToThisClass = new Vector();   
  +      	 	fksToThisClass = new Vector();
         	}
         	fksToThisClass.add(column);
       }
  @@ -125,57 +138,17 @@
       {
         	if (fksToItemClass == null)
         	{
  -      	 	fksToItemClass = new Vector();   
  +      	 	fksToItemClass = new Vector();
         	}
         	fksToItemClass.add(column);
       }
   
  -
  -    /**
  -     *
  -     */
  -    private Vector fksToThisClass = null;
  -
  -    /**
  -     * define the order of the resulting collection BRJ
  -     */
  -    private String orderBy;
  -	private boolean ascending = true;
  -    /**
  -     * define loading strategy of the resulting collection BRJ
  -     */
  -	private boolean lazy = false;
  -	
       /**
  -     * if true relationship is refreshed when owner is found in cache
  -     */
  -	private boolean refresh = false;
  -	
  -    /**
  -     *
        * returns the type of the collection.
  -     *
        * @return java.lang.Class
  -     *
        */
       public Class getCollectionClass()
       {
  -    	if (collectionClass == null)
  -    	{
  -    		if (collectionClassName != null)
  -    		{
  -            	try
  -            	{
  -                	collectionClass = Class.forName(collectionClassName, true,
  -             	                   		Thread.currentThread().getContextClassLoader());	
  -            	}
  -            	catch (Exception e)
  -            	{
  -            		throw new MetadataException(e);
  -            	}
  -    		}
  -    	}
  -    	
           return collectionClass;
       }
   
  @@ -186,28 +159,16 @@
       public void setCollectionClass(Class c)
       {
           collectionClass = c;
  -        collectionClassName = collectionClass.getName();
       }
   
       /**
  -     * set the type of the collection
  -     * @param classname the name of collection type
  -     */
  -    public void setCollectionClassName(String  classname)
  -    {
  -        collectionClassName  = classname;
  -    }
  -    
  -    
  -    /**
        * Retrieve the classname of the collection.
        */
       public String getCollectionClassName()
       {
  -        return collectionClassName;
  +        return collectionClass != null ? collectionClass.getName() : null;
       }
   
  -
       public String getIndirectionTable()
       {
           return indirectionTable;
  @@ -245,7 +206,7 @@
               m_orderby.add(new FieldHelper(fieldName, sortAscending));
           }
       }
  -    
  +
       /**
        * Returns the orderby Collection of Fields.
        * @return Collection
  @@ -254,7 +215,7 @@
       {
           return m_orderby;
       }
  -        
  +
   	/**
   	 * returns true if this is a lazy Collection.
   	 * @return Returns a boolean
  @@ -297,13 +258,13 @@
       public String toXML()
       {
           RepositoryTags tags = RepositoryTags.getInstance();
  -        String eol = System.getProperty("line.separator");
  -        
  +        String eol = SystemUtils.LINE_SEPARATOR;
  +
           // write opening tag
   		String result = "      " + tags.getOpeningTagNonClosingById(COLLECTION_DESCRIPTOR) + eol;
  -		
  +
   		// write attributes
  -		// name 
  +		// name
   		result       += "        " + tags.getAttribute(FIELD_NAME,this.getAttributeName()) + eol;
   
   		// collection class is optional
  @@ -314,11 +275,11 @@
   
   		// element-class-ref
    		result       += "        " + tags.getAttribute(ITEMS_CLASS,this.getItemClassName()) + eol;
  - 		
  +
   		// indirection-table is optional
   		if (isMtoNRelation())
   		{
  -		 	result += "        " + tags.getAttribute(INDIRECTION_TABLE,getIndirectionTable()) + eol;   
  +		 	result += "        " + tags.getAttribute(INDIRECTION_TABLE,getIndirectionTable()) + eol;
   		}
   
   		// proxyReference is optional, disabled by default
  @@ -330,39 +291,39 @@
   		//reference refresh is optional, disabled by default
   		if (isRefresh())
   		{
  -		 	result       += "        " + tags.getAttribute(REFRESH_REFERENCE,"true") + eol;   
  +		 	result       += "        " + tags.getAttribute(REFRESH_REFERENCE,"true") + eol;
   		}
  -		
  +
   		//auto retrieve is optional, enabled by default
   		if (!getCascadeRetrieve())
   		{
  -		 	result       += "        " + tags.getAttribute(AUTO_RETRIEVE,"false") + eol;   
  +		 	result       += "        " + tags.getAttribute(AUTO_RETRIEVE,"false") + eol;
   		}
   
   		//auto update is optional, disabled by default
   		if (getCascadeStore())
   		{
  -		 	result       += "        " + tags.getAttribute(AUTO_UPDATE,"true") + eol;   
  +		 	result       += "        " + tags.getAttribute(AUTO_UPDATE,"true") + eol;
   		}
  -	
  +
   		//auto delete is optional, disabled by default
   		if (getCascadeDelete())
   		{
  -		 	result       += "        " + tags.getAttribute(AUTO_DELETE,"true") + eol;   
  +		 	result       += "        " + tags.getAttribute(AUTO_DELETE,"true") + eol;
   		}
  -				
  +
   		// close opening tag
   		result       += "      >" + eol;
  -		
  +
   		// write elements
    		// inverse fk elements
           for (int i=0;i<getForeignKeyFields().size();i++)
           {
               String fkId = getForeignKeyFields().get(i).toString();
               result += "        " + tags.getOpeningTagNonClosingById(INVERSE_FK) + " ";
  -            result += tags.getAttribute(FIELD_ID_REF, fkId) + "/>" + eol;           
  +            result += tags.getAttribute(FIELD_ID_REF, fkId) + "/>" + eol;
           }
  -        
  +
           // write optional M:N elements
   		// m:n relationship settings, optional
   		if (isMtoNRelation())
  @@ -372,23 +333,20 @@
    			{
   	            String fkId = getFksToThisClass()[i].toString();
   	            result += "        " + tags.getOpeningTagNonClosingById(FK_POINTING_TO_THIS_CLASS) + " ";
  -	            result += tags.getAttribute(COLUMN_NAME, fkId) + "/>" + eol;           
  +	            result += tags.getAttribute(COLUMN_NAME, fkId) + "/>" + eol;
    			}
  -   
  +
   			// foreign keys to item class
    			for (int i=0;i<getFksToItemClass().length;i++)
    			{
   	            String fkId = getFksToItemClass()[i].toString();
   	            result += "        " + tags.getOpeningTagNonClosingById(FK_POINTING_TO_ITEMS_CLASS) + " ";
  -	            result += tags.getAttribute(COLUMN_NAME, fkId) + "/>" + eol;           
  +	            result += tags.getAttribute(COLUMN_NAME, fkId) + "/>" + eol;
    			}
   		}
  -        
  -        
   
   		// closing tag
           result       += "      " + tags.getClosingTagById(COLLECTION_DESCRIPTOR) + eol;
           return result;
       }
  -
   }
  
  
  
  1.48      +399 -829  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/ClassDescriptor.java
  
  Index: ClassDescriptor.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/ClassDescriptor.java,v
  retrieving revision 1.47
  retrieving revision 1.48
  diff -u -r1.47 -r1.48
  --- ClassDescriptor.java	17 Dec 2002 18:23:25 -0000	1.47
  +++ ClassDescriptor.java	24 Dec 2002 13:14:33 -0000	1.48
  @@ -54,6 +54,15 @@
    * <http://www.apache.org/>.
    */
   
  +import org.apache.commons.lang.builder.ToStringBuilder;
  +import org.apache.ojb.broker.PersistenceBrokerException;
  +import org.apache.ojb.broker.accesslayer.RowReader;
  +import org.apache.ojb.broker.accesslayer.RowReaderDefaultImpl;
  +import org.apache.ojb.broker.metadata.fieldaccess.PersistentField;
  +import org.apache.ojb.broker.util.ClassHelper;
  +import org.apache.ojb.broker.util.SqlHelper;
  +import org.apache.ojb.broker.util.logging.LoggerFactory;
  +
   import java.io.Serializable;
   import java.lang.reflect.Constructor;
   import java.lang.reflect.Modifier;
  @@ -67,17 +76,6 @@
   import java.util.Map;
   import java.util.Vector;
   
  -import org.apache.ojb.broker.OJBRuntimeException;
  -import org.apache.ojb.broker.PersistenceBroker;
  -import org.apache.ojb.broker.PersistenceBrokerException;
  -import org.apache.ojb.broker.PersistenceBrokerFactory;
  -import org.apache.ojb.broker.VirtualProxy;
  -import org.apache.ojb.broker.accesslayer.IndirectionHandler;
  -import org.apache.ojb.broker.accesslayer.RowReader;
  -import org.apache.ojb.broker.accesslayer.RowReaderDefaultImpl;
  -import org.apache.ojb.broker.metadata.fieldaccess.PersistentField;
  -import org.apache.ojb.broker.util.logging.LoggerFactory;
  -
   //#ifdef JDK13
   import java.lang.reflect.Proxy;
   //#else
  @@ -89,113 +87,83 @@
   /**
    * A ClassDescriptor contains all information for mapping objects of a
    * given class to database tables.
  + * <br>
  + * Note: Be careful when use ClassDescriptor variables or caching
  + * ClassDescriptor instances, because instances could become invalid
  + * during runtime (see {@link MetadataManager}).
    *
    * @author <a href="mailto:thma@apache.org">Thomas Mahler<a>
    * @version $Id$
    */
  -public class ClassDescriptor extends DescriptorBase implements Serializable, XmlCapable, IsolationLevels
  +public final class ClassDescriptor extends DescriptorBase implements Serializable, XmlCapable, IsolationLevels
   {
  -
       public static final String OJB_CONCRETE_CLASS = "ojbConcreteClass";
   
  -    private transient DescriptorRepository m_repository;
  -
  +    private DescriptorRepository m_repository;
       /**
        * transaction isolation level specified for this class, used in the ODMG server
        */
       private int m_IsolationLevel = IsolationLevels.IL_READ_UNCOMMITTED;
  -
       /**
        * the SQL SCHEMA of the underlying table of this class
        */
       private String schema = null;
  -
       /**
        * the described class
        */
       private Class m_Class = null;
  -
  -    /**
  -     * the name of the described class
  -     */
  -    private String classname = null;
  -
  -
       /**
        * the table name used to store the scalar attributes of this class
        */
       private String m_TableName = null;
  -
       /**
        * the FieldDescriptors for the primitive attributes
        */
       private FieldDescriptor[] m_FieldDescriptions = null;
  -
       /**
        * the descriptors for collection attributes
        */
       private Vector m_CollectionDescriptors = new Vector();
  -
       /**
        * the descriptor for 1-1 reference attributes
        */
       private Vector m_ObjectReferenceDescriptors = new Vector();
  -
       /**
        * the vector of indices used in DDL generation.
        */
       private Vector indexes = new Vector();
  -
  -    /**
  -     * the JDBCConnectionDescriptor describing the RDBMS connection to be used for this class
  -     */
  -    private JdbcConnectionDescriptor m_ConnDescription = null;
  -
       /**
        * the non-primary key FieldDescriptors
        */
       private FieldDescriptor[] nonPrimaryKeyFieldDescriptors = null;
  -
       /**
        * the primary key FieldDescriptors
        */
       private FieldDescriptor[] primaryKeyFieldDescriptors = null;
  -
       /**
        * the optimistic lockingFieldDescriptors BRJ
        */
       private FieldDescriptor[] lockingFieldDescriptors = null;
  -
       /**
        * the RowReader for this class
        */
       private RowReader rowReader = null;
  -
  -    /**
  -     * the RowReader class name for this class
  -     */
  -    private String rowReaderClassName = null;
  -
       /**
        * tells whether we tried to lookup multiargs Constructor already
        */
       private boolean alreadyLookedup = false;
  -
       /**
        * the types of the arguments for the attributes in m_FieldDescriptions
        */
       private Class[] argsForConstructor = null;
  -
       /**
        * the list of classes in the extent of this class. can be empty
        */
       private Vector extentClasses = new Vector();
  -
       /**
        * the list of class names in the extent of this class. can be empty
        */
       private Vector extentClassNames = new Vector();
  -
       /**
        * the class that this class extends
        */
  @@ -204,37 +172,31 @@
        * reference column for the superclass
        */
       private int superClassFieldRef;
  -
       /**
        * does the described class represent an interface?
        */
       private boolean isInterface = false;
  -
       /**
  -     * the constructor defined by m_Class to initialze all scalar attributes described in m_FieldDescriptions
  +     * the constructor defined by m_Class to initialze all scalar attributes
  +     * described in m_FieldDescriptions
        */
       private Constructor multiArgumentConstructor = null;
  -
       /**
        * the proxy class for the described class, may be null
        */
       private Class proxyClass = null;
  -
       /**
        * the proxy class name for the described class, may be null
        */
       private String proxyClassName = null;
  -
  -    private FieldDescriptor m_autoIncrementField = null;
  -
  -    private Map m_fieldDescriptorNameMap = new HashMap();
  -    private Map m_collectionDescriptorNameMap = new HashMap();
  -    private Map m_objectReferenceDescriptorsNameMap = new HashMap();
  -
       /**
        * if false do not accept implicit locks on this class
        */
       private boolean acceptLocks = true;
  +    private FieldDescriptor m_autoIncrementField = null;
  +    private Map m_fieldDescriptorNameMap = new HashMap();
  +    private Map m_collectionDescriptorNameMap = new HashMap();
  +    private Map m_objectReferenceDescriptorsNameMap = new HashMap();
   
       /**
        * Constructor declaration
  @@ -244,88 +206,46 @@
           this.m_repository = pRepository;
       }
   
  -    public ClassDescriptor()
  -    {
  -        this(DescriptorRepository.getDefaultInstance());
  -    }
  -
  -
       /**
  -     * sets the row reader class for thie class descriptor
  +     * sets the row reader class for this descriptor
        */
       public void setRowReader(RowReader newReader)
       {
           this.rowReader = newReader;
  -        setRowReaderClassName(newReader.getClass().getName());
       }
   
       /**
  -     * sets the row reader class name for thie class descriptor
  +     * Returns the {@link org.apache.ojb.broker.accesslayer.RowReader}
  +     * for this descriptor.
        */
  -    public void setRowReaderClassName(String newReaderClassName)
  -    {
  -        this.rowReaderClassName = newReaderClassName;
  -    }
  -
  -    public String getRowReaderClassName()
  -    {
  -        return this.rowReaderClassName;
  -    }
  -
  -
       public synchronized RowReader getRowReader()
       {
           if (rowReader == null)
           {
  -            // if no RowReader has been declared, use the default reader
  -            if (rowReaderClassName == null)
  -            {
  -                rowReader = new RowReaderDefaultImpl();
  -            }
  -            else
  -            {
  -                try
  -                {
  -                    Class rowReaderClass = Class.forName(rowReaderClassName, true,
  -                            Thread.currentThread().getContextClassLoader());
  -                    rowReader = (RowReader) rowReaderClass.newInstance();
  -                }
  -                catch (Exception e)
  -                {
  -                    throw new MetadataException(e);
  -                }
  -            }
  +            setRowReader(RowReaderDefaultImpl.class.getName());
           }
           return this.rowReader;
       }
   
       /**
  -     * Method declaration
  -     * @return
  -     */
  -    private String getTableName()
  -    {
  -        return m_TableName;
  -    }
  -
  -    /**
  -     * Answer Table name including schema	BRJ
  +     * sets the row reader class name for thie class descriptor
        */
  -    public String getFullTableName()
  +    public void setRowReader(String newReaderClassName)
       {
  -        if (getSchema() != null)
  -            return getSchema() + "." + getTableName();
  -        else
  -            return getTableName();
  +        try
  +        {
  +            this.rowReader = (RowReader) ClassHelper.
  +                    newInstance(newReaderClassName, ClassDescriptor.class, this);
  +        }
  +        catch (Exception e)
  +        {
  +            throw new MetadataException("Instantiating of current set RowReader failed", e);
  +        }
       }
   
  -    /**
  -     * Method declaration
  -     * @param str
  -     */
  -    public void setTableName(String str)
  +    public String getRowReaderClassName()
       {
  -        m_TableName = str;
  +        return this.rowReader != null ? this.rowReader.getClass().getName() : null;
       }
   
       /**
  @@ -334,7 +254,7 @@
        */
       public String getClassNameOfObject()
       {
  -        return this.classname;
  +        return this.m_Class != null ? this.m_Class.getName() : null;
       }
   
   
  @@ -344,26 +264,7 @@
        */
       public Class getClassOfObject()
       {
  -        if (m_Class != null)
  -        {
  -            return m_Class;
  -        }
  -        else if (classname != null)
  -        {
  -            try
  -            {
  -                m_Class = Class.forName(classname, true, Thread.currentThread().getContextClassLoader());
  -                return m_Class;
  -            }
  -            catch (ClassNotFoundException e)
  -            {
  -                throw new PersistenceBrokerException(e);
  -            }
  -        }
  -        else
  -        {
  -            return null;
  -        }
  +        return m_Class;
       }
   
       /**
  @@ -373,20 +274,10 @@
       public void setClassOfObject(Class c)
       {
           m_Class = c;
  -        this.classname = c.getName();
  -    }
  -
  -    /**
  -     * sets the name of the class described by this descriptor.
  -     * @param classname the class to describe
  -     */
  -    public void setClassNameOfObject(String classname)
  -    {
  -        this.classname = classname;
  +        // TODO
           // Shouldn't the HashMap in DescriptorRepository be updated as well?
       }
   
  -
       /**
        * adds a FIELDDESCRIPTOR to this ClassDescriptor.
        * @param fld
  @@ -427,8 +318,8 @@
        */
       public void addCollectionDescriptor(CollectionDescriptor cod)
       {
  -        cod.setClassDescriptor(this); // BRJ
           m_CollectionDescriptors.add(cod);
  +        cod.setClassDescriptor(this); // BRJ
       }
   
       /**
  @@ -446,85 +337,8 @@
        */
       public void addObjectReferenceDescriptor(ObjectReferenceDescriptor ord)
       {
  -        ord.setClassDescriptor(this); // BRJ
           m_ObjectReferenceDescriptors.add(ord);
  -    }
  -
  -    /**
  -     * Method declaration
  -     * @return
  -     */
  -    public JdbcConnectionDescriptor getConnectionDescriptor()
  -    {
  -        if (m_ConnDescription == null)
  -        {
  -            // if class has no special JDBC Connection use the DefaultConnection
  -            m_ConnDescription = this.getRepository().getDefaultJdbcConnection();
  -        }
  -        return m_ConnDescription;
  -    }
  -
  -    /**
  -     * Method declaration
  -     * @param jcd
  -     */
  -    public void setConnectionDescriptor(JdbcConnectionDescriptor jcd)
  -    {
  -        m_ConnDescription = jcd;
  -    }
  -
  -    /**
  -     * Method declaration
  -     * @param index
  -     * @return
  -     */
  -    public FieldDescriptor getFieldDescriptorByIndex(int index)
  -    {
  -        return m_FieldDescriptions[index - 1];
  -    }
  -
  -    /**
  -     * Method declaration
  -     * @return
  -     */
  -    public String toString()
  -    {
  -        return "table:      \t"
  -                + m_TableName
  -                + "\n"
  -                + "FieldDescriptions:\t"
  -                + (m_FieldDescriptions == null ? "" : m_FieldDescriptions.toString());
  -
  -    }
  -
  -    /**
  -     * Method declaration
  -     * @param name
  -     * @return
  -     */
  -    public FieldDescriptor getFieldDescriptorByName(String name)
  -    {
  -        if (name == null)
  -            return null;
  -        if (m_FieldDescriptions == null)
  -            return null;
  -        FieldDescriptor retval = (FieldDescriptor) m_fieldDescriptorNameMap.get(name);
  -        if (retval == null)
  -        {
  -            int size = m_FieldDescriptions.length;
  -            FieldDescriptor temp = null;
  -            for (int i = 0; ((i < size) && (retval == null)); i++)
  -            {
  -                temp = m_FieldDescriptions[i];
  -                if (name.equals(temp.getPersistentField().getName()))
  -                {
  -                    retval = temp;
  -                    m_fieldDescriptorNameMap.put(name, retval);
  -                    break;
  -                }
  -            }
  -        }
  -        return retval;
  +        ord.setClassDescriptor(this); // BRJ
       }
   
       /**
  @@ -584,24 +398,6 @@
       }
   
       /**
  -     * returns the transaction isolation level to be used for this class. Used only in the ODMG server
  -     */
  -    public int getIsolationLevel()
  -    {
  -        return m_IsolationLevel;
  -    }
  -
  -    /**
  -     * Method declaration
  -     * @param isoLevel
  -     */
  -    public void setIsolationLevel(int isoLevel)
  -    {
  -        m_IsolationLevel = isoLevel;
  -    }
  -
  -
  -    /**
        * add an Extent class to the current descriptor
        * @param newExtendClass
        */
  @@ -615,100 +411,29 @@
        * add an Extent class to the current descriptor
        * @param newExtendClassName name of the class to add
        */
  -    public void addExtentClassName(String newExtendClassName)
  -    {
  -        extentClassNames.add(newExtendClassName);
  -        m_repository.addExtent(newExtendClassName, this);
  -    }
  -
  -    public void setSuperClass(String classname)
  -    {
  -        this.superClass = classname;
  -
  -
  -    }
  -
  -    public void setSuperClassFieldRef(int fieldId)
  -    {
  -        this.superClassFieldRef = fieldId;
  -    }
  -
  -    public int getSuperClassFieldRef()
  -    {
  -        return superClassFieldRef;
  -    }
  -
  -    public String getSuperClass()
  +    public void addExtentClassName(String newExtentClassName)
       {
  -        return superClass;
  +        extentClassNames.add(newExtentClassName);
  +        m_repository.addExtent(newExtentClassName, this);
       }
   
       /**
  -     * returns a Constructor that takes all persistent attributes
  -     * of the class as arguments.
  -     * Returns null, if such a constructor does not exist.
  -     * PersistenceBroker clients are not urged to implement such constructors
  -     * for persistence capable classes. But it's strongly recommended as
  -     * it minimizes the overhead for reflective operations.
  +     * return all classes in this extent.
  +     * Creation date: (02.02.2001 17:49:11)
  +     * @return java.util.Vector
        */
  -    public Constructor getConstructor()
  +    public synchronized Vector getExtentClasses()
       {
  -        if (multiArgumentConstructor == null && !alreadyLookedup)
  +        if (extentClassNames.size() > extentClasses.size())
           {
  -            if (argsForConstructor == null)
  +            extentClasses.clear();
  +            for (Iterator iter = extentClassNames.iterator(); iter.hasNext();)
               {
  -                argsForConstructor = new Class[getFieldDescriptions().length];
  -                for (int i = 0; i < getFieldDescriptions().length; i++)
  +                String classname = (String) iter.next();
  +                Class extentClass;
  +                try
                   {
  -                    argsForConstructor[i] = getFieldDescriptions()[i].getPersistentField().getType();
  -                }
  -            }
  -            try
  -            {
  -                multiArgumentConstructor = getClassOfObject().getConstructor(argsForConstructor);
  -            }
  -            catch (Exception ignored)
  -            {
  -                // this exception is thrown, if no suitable Constructor was
  -                // found. In this case we tell the user that it is better to have
  -                // a multiargs constructor defined
  -                String args = "";
  -                for (int i = 0; i < argsForConstructor.length; i++)
  -                {
  -                    args += ((args.length() == 0) ? "(" : ", ");
  -                    args += argsForConstructor[i].getName();
  -                }
  -                args += ")";
  -                LoggerFactory.getDefaultLogger().warn(
  -                        "Please define a public constructor for "
  -                        + this.getClassOfObject()
  -                        + "\nwith the following signature: "
  -                        + args
  -                        + ".\nIt must initialize the classes persistent attributes. This is recommended to increase performance but it's not mandatory!");
  -            }
  -            alreadyLookedup = true;
  -        }
  -        return multiArgumentConstructor;
  -    }
  -
  -    /**
  -     * return all classes in this extent.
  -     * Creation date: (02.02.2001 17:49:11)
  -     * @return java.util.Vector
  -     */
  -    public synchronized Vector getExtentClasses()
  -    {
  -        if (extentClassNames.size() > extentClasses.size())
  -        {
  -            extentClasses.clear();
  -            for (Iterator iter = extentClassNames.iterator(); iter.hasNext();)
  -            {
  -                String classname = (String) iter.next();
  -                Class extentClass;
  -                try
  -                {
  -                    extentClass = Class.forName(classname, true,
  -                            Thread.currentThread().getContextClassLoader());
  +                    extentClass = ClassHelper.getClass(classname);
                   }
                   catch (ClassNotFoundException e)
                   {
  @@ -732,10 +457,20 @@
   
       /**
        * Insert the method's description here.
  +     * Creation date: (02.02.2001 17:49:11)
  +     * @return boolean
  +     */
  +    public boolean isExtent()
  +    {
  +        return (getExtentClassNames().size() > 0);
  +    }
  +
  +    /**
  +     * Insert the method's description here.
        * Creation date: (26.01.2001 09:20:09)
        * @return java.lang.Class
        */
  -    public synchronized java.lang.Class getProxyClass()
  +    public synchronized Class getProxyClass()
       {
   
           if ((proxyClass == null) && (proxyClassName != null))
  @@ -749,8 +484,7 @@
               {
                   try
                   {
  -                    proxyClass = Class.forName(proxyClassName, true,
  -                            Thread.currentThread().getContextClassLoader());
  +                    proxyClass = ClassHelper.getClass(proxyClassName);
                   }
                   catch (ClassNotFoundException e)
                   {
  @@ -762,48 +496,10 @@
       }
   
       /**
  -     * Insert the method's description here.
  -     * Creation date: (02.02.2001 17:49:11)
  -     * @return boolean
  -     */
  -    public boolean isExtent()
  -    {
  -        return (getExtentClassNames().size() > 0);
  -    }
  -
  -    /**
  -     * Insert the method's description here.
  -     * Creation date: (02.02.2001 17:49:11)
  -     * @return boolean
  -     */
  -    public boolean isInterface()
  -    {
  -        return isInterface;
  -    }
  -
  -    /**
  -     * Insert the method's description here.
  -     * Creation date: (02.02.2001 17:49:11)
  -     * @param newIsInterface boolean
  -     */
  -    public void setIsInterface(boolean newIsInterface)
  -    {
  -        isInterface = newIsInterface;
  -    }
  -
  -    /**
  -     * @return boolean true if the mapped class is abstract
  -     */
  -    public boolean isAbstract()
  -    {
  -        return Modifier.isAbstract(getClassOfObject().getModifiers());
  -    }
  -
  -    /**
        * Sets the proxy class to be used.
        * @param newProxyClass java.lang.Class
        */
  -    public void setProxyClass(java.lang.Class newProxyClass)
  +    public void setProxyClass(Class newProxyClass)
       {
           proxyClass = newProxyClass;
           if (proxyClass == null)
  @@ -833,34 +529,6 @@
       }
   
       /**
  -     * returns a vector containing values for all the Objects attribute
  -     * @throws MetadataException if tehre is an erros accessing obj field values
  -     */
  -    public Object[] getAllValues(Object obj) throws PersistenceBrokerException
  -    {
  -        FieldDescriptor[] allFields = getFieldDescriptions();
  -        Object[] result = new Object[allFields.length];
  -
  -        for (int i = 0; i < allFields.length; i++)
  -        {
  -            FieldDescriptor fmd = allFields[i];
  -            PersistentField f = fmd.getPersistentField();
  -            Object cv = f.get(obj);
  -
  -            // handle autoincrement attributes if not filled
  -            if (fmd.isAutoIncrement())
  -            {
  -                cv = getAutoIncrementValue(fmd, obj, cv);
  -            }
  -
  -            // apply type and value mapping
  -            cv = fmd.getFieldConversion().javaToSql(cv);
  -            result[i] = cv;
  -        }
  -        return result;
  -    }
  -
  -    /**
        * returns array of all FieldDescriptors.
        * @return FIELDDESCRIPTOR[]
        */
  @@ -870,108 +538,136 @@
       }
   
       /**
  -     * returns an Array with an Objects PK VALUES, with any java-to-sql
  -     * FieldConversion applied. If the Object is a Proxy or a VirtualProxy NO
  -     * conversion is necessary.
  -     *
  -     * @param objectOrProxy
  -     * @return Object[]
  -     * @throws PersistenceBrokerException
  +     * Method declaration
  +     * @param index
  +     * @return
        */
  -    public Object[] getKeyValues(Object objectOrProxy) throws PersistenceBrokerException
  +    public FieldDescriptor getFieldDescriptorByIndex(int index)
       {
  -        return getKeyValues(objectOrProxy, true);
  +        return m_FieldDescriptions[index - 1];
       }
   
       /**
  -     * returns an Array with an Objects PK VALUES if convertToSql is true, any
  -     * associated java-to-sql conversions are applied. If the Object is a Proxy
  -     * or a VirtualProxy NO conversion is necessary.
  -     *
  -     * @param objectOrProxy
  -     * @param convertToSql
  -     * @return Object[]
  -     * @throws PersistenceBrokerException
  +     * Method declaration
  +     * @param name
  +     * @return
        */
  -    public Object[] getKeyValues(Object objectOrProxy, boolean convertToSql) throws PersistenceBrokerException
  +    public FieldDescriptor getFieldDescriptorByName(String name)
       {
  -        if (Proxy.isProxyClass(objectOrProxy.getClass()))
  -        {
  -            return getKeyValuesForProxy((Proxy)objectOrProxy);
  -        }
  -        else if (objectOrProxy instanceof VirtualProxy)
  -        {
  -            return getKeyValuesForProxy((VirtualProxy)objectOrProxy);
  -        }
  -        else
  +        if (name == null)
  +            return null;
  +        if (m_FieldDescriptions == null)
  +            return null;
  +        FieldDescriptor retval = (FieldDescriptor) m_fieldDescriptorNameMap.get(name);
  +        if (retval == null)
           {
  -            return getKeyValuesForObject(objectOrProxy,convertToSql);
  +            int size = m_FieldDescriptions.length;
  +            FieldDescriptor temp = null;
  +            for (int i = 0; ((i < size) && (retval == null)); i++)
  +            {
  +                temp = m_FieldDescriptions[i];
  +                if (name.equals(temp.getPersistentField().getName()))
  +                {
  +                    retval = temp;
  +                    m_fieldDescriptorNameMap.put(name, retval);
  +                    break;
  +                }
  +            }
           }
  +        return retval;
       }
   
       /**
  -     * returns an Array with an Objects PK VALUES
  -     * if convertToSql is true, any associated java-to-sql conversions are applied
  -     * @throws MetadataException if there is an erros accessing o field values
  +     * return the FieldDescriptor for the Attribute referenced in the path<br>
  +     * the path may contain simple attribut names, functions and path expressions
  +     * using relationships <br>
  +     * ie: name, avg(price), adress.street
  +     * @param aPath the path to the attribute
  +     * @return the FieldDescriptor or null (ie: for m:n queries)
        */
  -    protected Object[] getKeyValuesForObject(Object o, boolean convertToSql) throws PersistenceBrokerException
  +    public FieldDescriptor getFieldDescriptorForPath(String aPath)
       {
  -        FieldDescriptor[] pkFields = getPkFields();
  -        Object[] result = new Object[pkFields.length];
  +        ArrayList desc = getAttributeDescriptorsForPath(aPath);
  +        FieldDescriptor fld = null;
  +        Object temp;
   
  -        for (int i = 0; i < result.length; i++)
  +        if (!desc.isEmpty())
           {
  -            FieldDescriptor fmd = pkFields[i];
  -            PersistentField f = fmd.getPersistentField();
  -            Object cv = f.get(o);
  -
  -            // handle autoincrement attributes if not filled
  -            if (fmd.isAutoIncrement())
  -            {
  -                cv = getAutoIncrementValue(fmd, o, cv);
  -            }
  -
  -            if (convertToSql)
  +            temp = desc.get(desc.size() - 1);
  +            if (temp instanceof FieldDescriptor)
               {
  -                // BRJ : apply type and value mapping
  -                cv = fmd.getFieldConversion().javaToSql(cv);
  +                fld = (FieldDescriptor) temp;
               }
  -            result[i] = cv;
           }
  -        return result;
  +        return fld;
       }
   
       /**
  -     * returns an Array with the Proxy's PK VALUES
  -     * @param aProxy
  -     * @return Object[]
  -     * @throws PersistenceBrokerException
  +     *
  +     * @return this classes FieldDescriptor's as well as it's parents and so on and so on
        */
  -    protected Object[] getKeyValuesForProxy(Proxy aProxy) throws PersistenceBrokerException
  +    public FieldDescriptor[] getFieldDescriptorsInHeirarchy()
       {
  -        IndirectionHandler handler;
  +        if (superClass == null)
  +        {
  +            return getFieldDescriptions();
  +        }
  +        ClassDescriptor cldSuper = getRepository().getDescriptorFor(superClass);
  +        return appendFieldDescriptorArrays(getFieldDescriptions(), cldSuper.getFieldDescriptorsInHeirarchy());
  +    }
   
  -        handler = (IndirectionHandler) Proxy.getInvocationHandler(aProxy);
  -        return handler.getIdentity().getPrimaryKeyValues();
  +    private FieldDescriptor[] appendFieldDescriptorArrays(FieldDescriptor[] fieldDescriptions, FieldDescriptor[] fieldDescriptorsInHeirarchy)
  +    {
  +        // take the 2 arrays and add them into one
  +        int size = fieldDescriptions.length + fieldDescriptorsInHeirarchy.length;
  +        FieldDescriptor[] newArray = new FieldDescriptor[size];
  +        int i;
  +        int j = 0;
  +        for (i = 0; i < fieldDescriptions.length; i++, j++)
  +        {
  +            FieldDescriptor fieldDescription = fieldDescriptions[i];
  +            newArray[j] = fieldDescription;
  +        }
  +        for (i = 0; i < fieldDescriptorsInHeirarchy.length; i++, j++)
  +        {
  +            FieldDescriptor fieldDescription = fieldDescriptorsInHeirarchy[i];
  +            newArray[j] = fieldDescription;
  +        }
  +        return newArray;
       }
   
       /**
  -     * returns an Array with the VirtualProxy's PK VALUES
  -     * @param aProxy
  -     * @return Object[]
  -     * @throws PersistenceBrokerException
  +     * Returns the first found autoincrement field
  +     * defined in this class descriptor. Use carefully
  +     * when multiple autoincrement field were defined.
        */
  -    protected Object[] getKeyValuesForProxy (VirtualProxy aProxy) throws PersistenceBrokerException
  +    public FieldDescriptor getAutoIncrementField()
       {
  -        IndirectionHandler handler;
  +        if (m_autoIncrementField == null)
  +        {
  +            FieldDescriptor[] fds = getPkFields();
   
  -        handler = (IndirectionHandler) VirtualProxy.getIndirectionHandler(aProxy);
  -        return handler.getIdentity().getPrimaryKeyValues();
  +            for (int i = 0; i < fds.length; i++)
  +            {
  +                FieldDescriptor fd = fds[i];
  +                if (fd.isAutoIncrement())
  +                {
  +                    m_autoIncrementField = fd;
  +                    break;
  +                }
  +            }
  +        }
  +        if (m_autoIncrementField == null)
  +        {
  +            LoggerFactory.getDefaultLogger().warn(this.getClass().getName() + ": " +
  +                    "Could not found autoincrement attribute for class: " + this.getClassNameOfObject());
  +        }
  +        return m_autoIncrementField;
       }
   
       /**
        * returns an Array with an Objects CURRENT locking VALUES , BRJ
  -     * @throws MetadataException if there is an erros accessing o field values
  +     * @throws PersistenceBrokerException if there is an erros accessing o field values
        */
       public Object[] getCurrentLockingValues(Object o) throws PersistenceBrokerException
       {
  @@ -991,7 +687,7 @@
       /**
        * updates the values for locking fields , BRJ
        * handles int, long, Timestamp
  -     * @throws MetadataException if there is an erros accessing obj field values
  +     * @throws PersistenceBrokerException if there is an erros accessing obj field values
        */
       public void updateLockingValues(Object obj) throws PersistenceBrokerException
       {
  @@ -1038,160 +734,6 @@
       }
   
       /**
  -     * @throws MetadataException if there is an erros accessing obj field values
  -     */
  -    private Object getAutoIncrementValue(FieldDescriptor fmd, Object obj, Object cv)
  -    {
  -        if ((cv == null) || ((cv instanceof Number) && (((Number) cv).intValue() == 0)))
  -        {
  -            PersistentField f = fmd.getPersistentField();
  -            Object result = cv;
  -            PersistenceBroker broker = null;
  -            try
  -            {
  -                if (m_repository != null)
  -                {
  -                    // arminw
  -                    // use the PBKey of the associated descriptor repository
  -                    // to match the 'correct' repository
  -                    /* @todo maybe this could be critical in some
  -                     * situations, e.g. if the associated PBKey was always the
  -                     * default PBKey. Check this out.
  -                     */
  -                    broker = PersistenceBrokerFactory.createPersistenceBroker(m_repository.getPBkey());
  -                }
  -                else
  -                {
  -                    // no repository, we use the default PB
  -                    broker = PersistenceBrokerFactory.defaultPersistenceBroker();
  -                }
  -                // int
  -                if ((f.getType() == int.class) || (f.getType() == Integer.class))
  -                {
  -                    if ((f.get(obj) == null) || (((Number) f.get(obj)).intValue() == 0))
  -                    {
  -                        /*
  -                        arminw
  -                        old version
  -                        Class extent = broker.getExtentClass(this.getClassOfObject());
  -                        result = new Integer(broker.getUniqueId(extent, f.getName()));
  -
  -                        we should not give the top-level extent to sequence manager,
  -                        sequence manager itself should take care of uniqueness over the extents
  -                        */
  -                        result = new Integer(broker.getUniqueId(fmd));
  -                        // reflect autoincrement value back into object
  -                        f.set(obj, result);
  -                    }
  -                }
  -                // long
  -                else if ((f.getType() == long.class) || (f.getType() == Long.class))
  -                {
  -                    if ((f.get(obj) == null) || (((Number) f.get(obj)).longValue() == 0))
  -                    {
  -                        /*
  -                        arminw
  -                        old version
  -                        Class extent = broker.getExtentClass(this.getClassOfObject());
  -                        result = new Long(broker.getUniqueLong(extent, f.getName()));
  -
  -                        we should not give the top-level extent to sequence manager,
  -                        sequence manager itself should take care of uniqueness over the extents
  -                        */
  -
  -                        result = new Long(broker.getUniqueLong(fmd));
  -                        // reflect autoincrement value back into object
  -                        f.set(obj, result);
  -                    }
  -                }
  -                // String
  -                else if (String.class.isAssignableFrom(f.getType()))
  -                {
  -                    if (f.get(obj) == null)
  -                    {
  -                        result = broker.getUniqueString(fmd);
  -                        // reflect autoincrement value back into object
  -                        f.set(obj, result);
  -                    }
  -                }
  -                // Object
  -                else if (!f.getType().isPrimitive())
  -                {
  -                    // only assign a value if attribute == null
  -                    if (f.get(obj) == null)
  -                    {
  -                        result = broker.getUniqueObject(fmd);
  -                        if (result != null)
  -                        {
  -                            // reflect autoincrement value back into object
  -                            f.set(obj, result);
  -                        }
  -                        else
  -                        {
  -                            throw new OJBRuntimeException(
  -                                    "OJB ERROR: Dont know how to autoincrement field " +
  -                                    f.getDeclaringClass() + "#" + f.getName());
  -                        }
  -                    }
  -                }
  -                else
  -                {
  -                    throw new OJBRuntimeException(
  -                            "OJB ERROR: Dont know how to autoincrement field " +
  -                            f.getDeclaringClass() + "#" + f.getName());
  -                }
  -                return result;
  -            }
  -            catch (MetadataException e)
  -            {
  -                throw new OJBRuntimeException(
  -                        "Error while trying to autoincrement field " +
  -                        f.getDeclaringClass() + "#" + f.getName(), e);
  -            }
  -            finally
  -            {
  -                if (broker != null)
  -                {
  -                    broker.close();
  -                }
  -            }
  -        }
  -        else
  -        {
  -            return cv;
  -        }
  -
  -    }
  -
  -    /**
  -     * returns an Array with an Objects NON-PK VALUES
  -     * @throws MetadataException if there is an erros accessing o field values
  -     */
  -    public Object[] getNonKeyValues(Object o) throws PersistenceBrokerException
  -    {
  -        FieldDescriptor[] nonPkFields = getNonPkFields();
  -        Object[] result = new Object[nonPkFields.length];
  -
  -        for (int i = 0; i < result.length; i++)
  -        {
  -            FieldDescriptor fmd = nonPkFields[i];
  -            PersistentField f = fmd.getPersistentField();
  -            Object cv = f.get(o);
  -
  -            // handle autoincrement attributes if not filled
  -            if (fmd.isAutoIncrement())
  -            {
  -                cv = getAutoIncrementValue(fmd, o, cv);
  -            }
  -
  -            // apply type and value conversion
  -            cv = fmd.getFieldConversion().javaToSql(cv);
  -            result[i] = cv;
  -        }
  -        return result;
  -    }
  -
  -    /**
        * return an array of PK FieldDescription sorted ascending
        * according to the field-descriptions getOrder() property
        */
  @@ -1263,6 +805,21 @@
       }
   
       /**
  +     * convenience function to get the first primary key
  +     * <p>
  +     * useful when there is only one
  +     */
  +    public FieldDescriptor getPrimaryKey()
  +    {
  +        FieldDescriptor[] fds = getPkFields();
  +        if (fds != null && fds.length > 0)
  +        {
  +            return fds[0];
  +        }
  +        return null;
  +    }
  +
  +    /**
        * return an array of FieldDescription for optimistic locking sorted ascending
        * according to the field-descriptions getOrder() property
        */
  @@ -1288,6 +845,14 @@
       }
   
       /**
  +     * return true if optimistic locking is used
  +     */
  +    public boolean isLocking()
  +    {
  +        return getLockingFields().length > 0;
  +    }
  +
  +    /**
        * returns a dynamic Proxy that implements all interfaces of the
        * class described by this ClassDescriptor.
        *
  @@ -1330,104 +895,13 @@
           for (int i = 0; i < interfaces.length; i++)
           {
               unique.put(interfaces[i].getName(), interfaces[i]);
  -        }
  -        interfaces = (Class[]) unique.values().toArray(new Class[unique.size()]);
  -        // return dynymic Proxy Class implementing all interfaces
  -        Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(), interfaces);
  -
  -        return proxyClass;
  -    }
  -
  -    /**
  -     * return true if optimistic locking is used
  -     */
  -    public boolean isLocking()
  -    {
  -        return getLockingFields().length > 0;
  -    }
  -
  -    /**
  -     * Gets the repository.
  -     * @return Returns a DescriptorRepository
  -     */
  -    public DescriptorRepository getRepository()
  -    {
  -    	if (null == m_repository)
  -    	{
  -    		// todo: I don't know if this is always the correct repository!
  -    		m_repository = DescriptorRepository.getDefaultInstance();
  -    	}
  -        return m_repository;
  -    }
  -
  -    /**
  -     * Sets the repository.
  -     * @param repository The repository to set
  -     */
  -    public void setRepository(DescriptorRepository repository)
  -    {
  -        m_repository = repository;
  -    }
  -
  -    /**
  -     * Gets the schema.
  -     * @return Returns a String
  -     */
  -    public String getSchema()
  -    {
  -        return schema;
  -    }
  -
  -    /**
  -     * Sets the schema.
  -     * @param schema The schema to set
  -     */
  -    public void setSchema(String schema)
  -    {
  -        this.schema = schema;
  -    }
  -
  -    /**
  -     * Gets the IndexDescriptors used for DDL generation.
  -     */
  -    public Vector getIndexes()
  -    {
  -        return indexes;
  -    }
  -
  -    /**
  -     * Sets the IndexDescriptors used for DDL generation.
  -     */
  -    public void setIndexes(Vector indexes)
  -    {
  -        this.indexes = indexes;
  -    }
  -
  -    /**
  -     * return the FieldDescriptor for the Attribute referenced in the path<br>
  -     * the path may contain simple attribut names, functions and path expressions
  -     * using relationships <br>
  -     * ie: name, avg(price), adress.street
  -     * @param aPath the path to the attribute
  -     * @return the FieldDescriptor or null (ie: for m:n queries)
  -     */
  -    public FieldDescriptor getFieldDescriptorForPath(String aPath)
  -    {
  -        ArrayList desc = getAttributeDescriptorsForPath(aPath);
  -        FieldDescriptor fld = null;
  -        Object temp;
  -
  -        if (!desc.isEmpty())
  -        {
  -            temp = desc.get(desc.size() - 1);
  -            if (temp instanceof FieldDescriptor)
  -            {
  -                fld = (FieldDescriptor) temp;
  -            }
  -        }
  -        return fld;
  -    }
  +        }
  +        interfaces = (Class[]) unique.values().toArray(new Class[unique.size()]);
  +        // return dynymic Proxy Class implementing all interfaces
  +        Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(), interfaces);
   
  +        return proxyClass;
  +    }
   
       /**
        * return all AttributeDescriptors for the path<br>
  @@ -1440,7 +914,7 @@
        */
       public ArrayList getAttributeDescriptorsForPath(String aPath)
       {
  -        return getAttributeDescriptorsForCleanPath(cleanPath(aPath));
  +        return getAttributeDescriptorsForCleanPath(SqlHelper.cleanPath(aPath));
       }
   
       /**
  @@ -1504,35 +978,53 @@
       }
   
       /**
  -     * remove functions and () from path
  -     * ie: avg(amount) -> amount <br>
  -     * ie: sum(accounts.amount) -> accounts.amount
  -     * @param aPath the path to the attribute
  +     * returns a Constructor that takes all persistent attributes
  +     * of the class as arguments.
  +     * Returns null, if such a constructor does not exist.
  +     * PersistenceBroker clients are not urged to implement such constructors
  +     * for persistence capable classes. But it's strongly recommended as
  +     * it minimizes the overhead for reflective operations.
        */
  -    public static String cleanPath(String aPath)
  +    public Constructor getConstructor()
       {
  -        int braceBegin;
  -        int braceEnd;
  -
  -        if (aPath == null)
  -        {
  -            return aPath;
  -        }
  -
  -        braceBegin = aPath.indexOf("(");
  -        braceEnd = aPath.lastIndexOf(")");
  -        if (braceBegin >= 0 && braceEnd >= 0)
  -        {
  -            return aPath.substring(braceBegin + 1, braceEnd).trim();
  -        }
  -        else
  +        if (multiArgumentConstructor == null && !alreadyLookedup)
           {
  -            return aPath;
  +            if (argsForConstructor == null)
  +            {
  +                argsForConstructor = new Class[getFieldDescriptions().length];
  +                for (int i = 0; i < getFieldDescriptions().length; i++)
  +                {
  +                    argsForConstructor[i] = getFieldDescriptions()[i].getPersistentField().getType();
  +                }
  +            }
  +            try
  +            {
  +                multiArgumentConstructor = getClassOfObject().getConstructor(argsForConstructor);
  +            }
  +            catch (Exception ignored)
  +            {
  +                // this exception is thrown, if no suitable Constructor was
  +                // found. In this case we tell the user that it is better to have
  +                // a multiargs constructor defined
  +                String args = "";
  +                for (int i = 0; i < argsForConstructor.length; i++)
  +                {
  +                    args += ((args.length() == 0) ? "(" : ", ");
  +                    args += argsForConstructor[i].getName();
  +                }
  +                args += ")";
  +                LoggerFactory.getDefaultLogger().warn(this.getClass().getName() + ": " +
  +                        "Please define a public constructor for "
  +                        + this.getClassOfObject()
  +                        + "\nwith the following signature: "
  +                        + args
  +                        + ".\nIt must initialize the classes persistent attributes. This is recommended to increase performance but it's not mandatory!");
  +            }
  +            alreadyLookedup = true;
           }
  -
  +        return multiArgumentConstructor;
       }
   
  -
       /*
        * @see XmlCapable#toXML()
        */
  @@ -1553,10 +1045,10 @@
           // isolation level is optional
           if (null != getRepository())
           {
  -        	if (getIsolationLevel() != this.getRepository().getDefaultIsolationLevel())
  -        	{
  -            	result += "    " + tags.getAttribute(ISOLATION_LEVEL, this.isolationLevelXml()) + eol;
  -        	}
  +            if (getIsolationLevel() != this.getRepository().getDefaultIsolationLevel())
  +            {
  +                result += "    " + tags.getAttribute(ISOLATION_LEVEL, this.isolationLevelXml()) + eol;
  +            }
           }
   
           Class theProxyClass = null;
  @@ -1602,7 +1094,7 @@
           //accept-locks is optional, enabled by default
           if (!this.acceptLocks)
           {
  -            result += "        " + tags.getAttribute(ACCEPT_LOCKS,"false") + eol;
  +            result += "        " + tags.getAttribute(ACCEPT_LOCKS, "false") + eol;
           }
           // sequence manager attribute not yet implemented
   
  @@ -1654,9 +1146,7 @@
               {
                   result += ((CollectionDescriptor) cols.get(i)).toXML();
               }
  -
           }
  -
           result += "  " + tags.getClosingTagById(CLASS_DESCRIPTOR);
           return result;
       }
  @@ -1689,89 +1179,55 @@
                   {
                       return LITERAL_IL_READ_UNCOMMITTED;
                   }
  -
           }
  +    }
  +
  +    public void setSuperClass(String classname)
  +    {
  +        this.superClass = classname;
  +    }
   
  +    public void setSuperClassFieldRef(int fieldId)
  +    {
  +        this.superClassFieldRef = fieldId;
       }
   
  -    /**
  -     * Returns the first found autoincrement field
  -     * defined in this class descriptor. Use carefully
  -     * when multiple autoincrement field were defined.
  -     */
  -    public FieldDescriptor getAutoIncrementField()
  +    public int getSuperClassFieldRef()
       {
  -        if (m_autoIncrementField == null)
  -        {
  -            FieldDescriptor[] fds = getPkFields();
  +        return superClassFieldRef;
  +    }
   
  -            for (int i = 0; i < fds.length; i++)
  -            {
  -                FieldDescriptor fd = fds[i];
  -                if (fd.isAutoIncrement())
  -                {
  -                    m_autoIncrementField = fd;
  -                    break;
  -                }
  -            }
  -        }
  -        if(m_autoIncrementField == null)
  -        {
  -            LoggerFactory.getDefaultLogger().warn(
  -                    "Could not found autoincrement attribute for class: " + this.getClassNameOfObject());
  -        }
  -        return m_autoIncrementField;
  +    public String getSuperClass()
  +    {
  +        return superClass;
       }
   
       /**
  -     *
  -     * @return this classes FieldDescriptor's as well as it's parents and so on and so on
  +     * Insert the method's description here.
  +     * Creation date: (02.02.2001 17:49:11)
  +     * @return boolean
        */
  -    public FieldDescriptor[] getFieldDescriptorsInHeirarchy()
  +    public boolean isInterface()
       {
  -        if (superClass == null)
  -        {
  -            return getFieldDescriptions();
  -        }
  -        ClassDescriptor cldSuper = getRepository().getDescriptorFor(superClass);
  -        return appendFieldDescriptorArrays(getFieldDescriptions(), cldSuper.getFieldDescriptorsInHeirarchy());
  +        return isInterface;
       }
   
  -    private FieldDescriptor[] appendFieldDescriptorArrays(FieldDescriptor[] fieldDescriptions, FieldDescriptor[] fieldDescriptorsInHeirarchy)
  +    /**
  +     * Insert the method's description here.
  +     * Creation date: (02.02.2001 17:49:11)
  +     * @param newIsInterface boolean
  +     */
  +    public void setIsInterface(boolean newIsInterface)
       {
  -        // take the 2 arrays and add them into one
  -        int size = fieldDescriptions.length + fieldDescriptorsInHeirarchy.length;
  -        FieldDescriptor[] newArray = new FieldDescriptor[size];
  -        int i;
  -        int j = 0;
  -        for (i = 0; i < fieldDescriptions.length; i++, j++)
  -        {
  -            FieldDescriptor fieldDescription = fieldDescriptions[i];
  -            newArray[j] = fieldDescription;
  -        }
  -        for (i = 0; i < fieldDescriptorsInHeirarchy.length; i++, j++)
  -        {
  -            FieldDescriptor fieldDescription = fieldDescriptorsInHeirarchy[i];
  -            newArray[j] = fieldDescription;
  -        }
  -
  -        return newArray;
  +        isInterface = newIsInterface;
       }
   
       /**
  -     * convenience function to get the first primary key
  -     * <p>
  -     * useful when there is only one
  -     * @return
  +     * @return boolean true if the mapped class is abstract
        */
  -    public FieldDescriptor getPrimaryKey()
  +    public boolean isAbstract()
       {
  -        FieldDescriptor[] fds = getPkFields();
  -        if (fds != null && fds.length > 0)
  -        {
  -            return fds[0];
  -        }
  -        return null;
  +        return Modifier.isAbstract(getClassOfObject().getModifiers());
       }
   
       /**
  @@ -1790,5 +1246,119 @@
       public void setAcceptLocks(boolean acceptLocks)
       {
           this.acceptLocks = acceptLocks;
  +    }
  +
  +    /**
  +     * Gets the IndexDescriptors used for DDL generation.
  +     */
  +    public Vector getIndexes()
  +    {
  +        return indexes;
  +    }
  +
  +    /**
  +     * Sets the IndexDescriptors used for DDL generation.
  +     */
  +    public void setIndexes(Vector indexes)
  +    {
  +        this.indexes = indexes;
  +    }
  +
  +    /**
  +     * Gets the repository.
  +     * @return Returns a DescriptorRepository
  +     */
  +    public DescriptorRepository getRepository()
  +    {
  +        return m_repository;
  +    }
  +
  +    /**
  +     * Sets the repository.
  +     * @param repository The repository to set
  +     */
  +    public void setRepository(DescriptorRepository repository)
  +    {
  +        m_repository = repository;
  +    }
  +
  +    /**
  +     * returns the transaction isolation level to be used for this class. Used only in the ODMG server
  +     */
  +    public int getIsolationLevel()
  +    {
  +        return m_IsolationLevel;
  +    }
  +
  +    /**
  +     * Method declaration
  +     * @param isoLevel
  +     */
  +    public void setIsolationLevel(int isoLevel)
  +    {
  +        m_IsolationLevel = isoLevel;
  +    }
  +
  +    /**
  +     * Method declaration
  +     * @return
  +     */
  +    private String getTableName()
  +    {
  +        return m_TableName;
  +    }
  +
  +    /**
  +     * Method declaration
  +     * @param str
  +     */
  +    public void setTableName(String str)
  +    {
  +        m_TableName = str;
  +    }
  +
  +    /**
  +     * Answer Table name including schema	BRJ
  +     */
  +    public String getFullTableName()
  +    {
  +        if (getSchema() != null)
  +            return getSchema() + "." + getTableName();
  +        else
  +            return getTableName();
  +    }
  +
  +    /**
  +     * Gets the schema.
  +     * @return Returns a String
  +     */
  +    public String getSchema()
  +    {
  +        return schema;
  +    }
  +
  +    /**
  +     * Sets the schema.
  +     * @param schema The schema to set
  +     */
  +    public void setSchema(String schema)
  +    {
  +        this.schema = schema;
  +    }
  +
  +    /**
  +     * Return a string representation of this class.
  +     */
  +    public String toString()
  +    {
  +        ToStringBuilder buf = new ToStringBuilder(this);
  +        return buf.
  +                append("classNameOfObject", getClassNameOfObject()).
  +                append("tableName", getTableName()).
  +                append("schema", getSchema()).
  +                append("isInterface", isInterface()).
  +                append("extendClassNames", getExtentClassNames().toString()).
  +                append("fieldDescriptions", getFieldDescriptions()).
  +                toString();
       }
   }
  
  
  
  1.9       +17 -57    jakarta-ojb/src/java/org/apache/ojb/broker/metadata/AttributeDescriptorBase.java
  
  Index: AttributeDescriptorBase.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/AttributeDescriptorBase.java,v
  retrieving revision 1.8
  retrieving revision 1.9
  diff -u -r1.8 -r1.9
  --- AttributeDescriptorBase.java	20 Oct 2002 15:49:52 -0000	1.8
  +++ AttributeDescriptorBase.java	24 Dec 2002 13:14:34 -0000	1.9
  @@ -54,94 +54,55 @@
    * <http://www.apache.org/>.
    */
   
  -import java.io.Serializable;
  +import org.apache.ojb.broker.metadata.fieldaccess.PersistentField;
  +import org.apache.ojb.broker.metadata.fieldaccess.PersistentFieldFactory;
   
  -import org.apache.ojb.broker.metadata.fieldaccess.*;
  +import java.io.Serializable;
   
   /**
  - *
  - * is the base class for all other attribute descriptors. It holds basic the mapping information for a specific
  - *
  - * attribute.
  - *
  - *
  + * Is the base class for all other attribute descriptors.
  + * It holds basic the mapping information for a specific attribute.
    *
    * @author <a href="mailto:thma@apache.org">Thomas Mahler<a>
  - *
  + * @version $Id$
    */
   public class AttributeDescriptorBase extends DescriptorBase implements Serializable
   {
       private PersistentField m_PersistentField = null;
       private ClassDescriptor m_ClassDescriptor = null;
  -    
  -    private String classname = null;
  -    private String fieldname = null;
  -    
   
       /**
  -     * @throws MetadataException if an error occours when setting the PersistenteField
  +     * Constructor declaration
        */
  -    public void setPersistentField(Class c, String fieldname)
  +    public AttributeDescriptorBase(ClassDescriptor descriptor)
       {
  -        this.classname = c.getName();
  -        this.fieldname = fieldname;
  -        m_PersistentField = PersistentFieldFactory.createPersistentField(c,fieldname);
  +        this.m_ClassDescriptor = descriptor;
       }
  -    
  -    /**
  -     * @throws MetadataException if an error occours when setting the PersistenteField
  -     */
  -    public void setPersistentField(String classname, String fieldname)
  -    {
  -    	this.classname = classname;
  -    	this.fieldname = fieldname;
  -    }    
  -
  -
  -
   
       /**
  -     * Constructor declaration
  +     * @throws MetadataException if an error occours when setting the PersistenteField
        */
  -    public AttributeDescriptorBase()
  +    public void setPersistentField(Class c, String fieldname)
       {
  +        m_PersistentField = PersistentFieldFactory.createPersistentField(c, fieldname);
       }
   
       /**
  -     * Method declaration
  -     *
  -     *
  -     * @return
  -     *
        *
        */
  -    public synchronized PersistentField getPersistentField()
  +    public PersistentField getPersistentField()
       {
  -    	if (m_PersistentField == null)
  -    	{
  -            try
  -            {
  -                Class clazz = Class.forName(this.classname, true,
  -                                		Thread.currentThread().getContextClassLoader());
  -                m_PersistentField = PersistentFieldFactory.createPersistentField(clazz,fieldname);	
  -            }
  -            catch (ClassNotFoundException e)
  -            {
  -            	throw new MetadataException(e);
  -            }
  -    	}
           return m_PersistentField;
       }
   
       /**
  -     * @return the name of the Attribute 
  -     */ 
  +     * @return the name of the Attribute
  +     */
       public String getAttributeName()
       {
  -        //return getPersistentField().getName();
  -        return this.fieldname;
  +        return getPersistentField().getName();
       }
  -        
  +
       /**
        * Gets the classDescriptor.
        * @return Returns a ClassDescriptor
  @@ -159,5 +120,4 @@
       {
           m_ClassDescriptor = classDescriptor;
       }
  -
   }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/MetadataManager.java
  
  Index: MetadataManager.java
  ===================================================================
  package org.apache.ojb.broker.metadata;
  
  import org.apache.ojb.broker.util.logging.LoggerFactory;
  import org.apache.ojb.broker.util.logging.Logger;
  import org.apache.ojb.broker.util.configuration.impl.OjbConfigurator;
  import org.apache.ojb.broker.PBKey;
  import org.apache.ojb.broker.singlevm.PersistenceBrokerConfiguration;
  import org.apache.commons.lang.SerializationUtils;
  import org.xml.sax.SAXException;
  
  import javax.xml.parsers.ParserConfigurationException;
  import java.io.IOException;
  
  /**
   * Central class for metadata operations, manages OJB's
   * {@link org.apache.ojb.broker.metadata.DescriptorRepository} and
   * {@link org.apache.ojb.broker.metadata.ConnectionRepository} instances.
   * <br>
   * Allow a bunch of different repository handling possibilities - allows a transparent flexible
   * metadata manipulation at runtime.
   * <p>
   * Per default the manager handle one global {@link org.apache.ojb.broker.metadata.DescriptorRepository}
   * for all calling threads, but you could {@link #setEnablePerThreadChanges enable a per thread}
   * handling. Then it is possible to set a different
   * {@link org.apache.ojb.broker.metadata.DescriptorRepository} for each calling thread.
   * This allows a per thread manipulation of the metadata at runtime.
   * </p>
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: MetadataManager.java,v 1.1 2002/12/24 13:14:33 arminw Exp $
   */
  public class MetadataManager
  {
      private static Logger log = LoggerFactory.getLogger(MetadataManager.class);
  
      private static ThreadLocal threadedRepository = new ThreadLocal();
      private static MetadataManager singleton;
      static
      {
          singleton = new MetadataManager();
      }
  
      private DescriptorRepository globalRepository;
      private ConnectionRepository connectionRepository;
      private boolean enablePerThreadChanges;
  
      // singleton
      private MetadataManager()
      {
          String repository = ((PersistenceBrokerConfiguration) OjbConfigurator.getInstance()
                      .getConfigurationFor(null)).getRepositoryFilename();
          try
          {
              globalRepository = new RepositoryPersistor().readDescriptorRepository(repository);
              connectionRepository = new RepositoryPersistor().readConnectionRepository(repository);
          }
          catch (Exception e)
          {
              throw new MetadataException("Could not read DescriptorRepository data",e);
          }
      }
  
      /**
       * Returns an instance of this class.
       */
      public static MetadataManager getInstance()
      {
          return singleton;
      }
  
      /**
       * Returns the current valid {@link DescriptorRepository} for
       * the caller.
       * <br>
       * When {@link #isEnablePerThreadChanges per thread descriptor handling}  is enabled
       * we first search for a {@link DescriptorRepository} for the calling thread, if not found
       * the global descriptor was returned.
       */
      public DescriptorRepository getRepository()
      {
          DescriptorRepository repository;
          if (enablePerThreadChanges)
          {
              repository = (DescriptorRepository) threadedRepository.get();
              if(repository == null)
              {
                  repository = getGlobalRepository();
  //                repository = copyOfGlobalRepository();
  //                threadedRepository.set(repository);
              }
              return repository;
          }
          else
          {
              return globalRepository;
          }
      }
  
      /**
       * Returns explicit the global {@link DescriptorRepository} - use with
       * care, because it ignores the {@link #setEnablePerThreadChanges per thread mode}.
       */
      public DescriptorRepository getGlobalRepository()
      {
          return globalRepository;
      }
  
      /**
       * Returns the {@link ConnectionRepository}.
       */
      public ConnectionRepository connectionRepository()
      {
          return connectionRepository;
      }
  
      /**
       * Set the {@link DescriptorRepository} - if <i>global</i> was true, the
       * given descriptor aquire global availability (<i>use with care!</i>),
       * else the given descriptor was associated with the calling thread.
       *
       * @see #isEnablePerThreadChanges
       * @see #setEnablePerThreadChanges
       */
      public void setDescriptor(DescriptorRepository repository, boolean global)
      {
          if(global)
          {
              if(log.isDebugEnabled()) log.debug("Set new global repository: "+repository);
              globalRepository = repository;
          }
          else
          {
              if(log.isDebugEnabled()) log.debug("Set new threaded repository: "+repository);
              threadedRepository.set(repository);
          }
      }
  
      /**
       * Convenience method for
       * {@link #setDescriptorRepository setDescriptor(repository, false)}.
       */
      public void setPerThreadDescriptor(DescriptorRepository repository)
      {
          setDescriptor(repository, false);
      }
  
      /**
       * Returns a copy of the current global
       * {@link org.apache.ojb.broker.metadata.DescriptorRepository}
       */
      public DescriptorRepository copyOfGlobalRepository()
      {
          return (DescriptorRepository) SerializationUtils.clone(globalRepository);
      }
  
      /**
       * If returns <i>true</i> runtime (per thread) changes
       * of the {@link org.apache.ojb.broker.metadata.DescriptorRepository}
       * will take effect.
       * <br>
       * If returns <i>false</i> all made and further runtime (per thread)
       * changes will be ignored.
       *
       * @see #setEnablePerThreadChanges
       */
      public boolean isEnablePerThreadChanges()
      {
          return enablePerThreadChanges;
      }
  
      /**
       * Enable the possibility of making per thread runtime changes
       * of the {@link org.apache.ojb.broker.metadata.DescriptorRepository}.
       *
       * @see #isEnablePerThreadChanges
       */
      public void setEnablePerThreadChanges(boolean enablePerThreadChanges)
      {
          this.enablePerThreadChanges = enablePerThreadChanges;
      }
  }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/MetadataConfiguration.java
  
  Index: MetadataConfiguration.java
  ===================================================================
  package org.apache.ojb.broker.metadata;
  
  /**
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: MetadataConfiguration.java,v 1.1 2002/12/24 13:14:33 arminw Exp $
   */
  public interface MetadataConfiguration
  {
      /**
       * If true OJB use a serialized version of the repository
       * configuration file for repetition read.
       */
      public boolean useSerializedRepository();
  }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/ConnectionRepository.java
  
  Index: ConnectionRepository.java
  ===================================================================
  package org.apache.ojb.broker.metadata;
  
  import org.apache.commons.lang.SerializationUtils;
  import org.apache.commons.lang.SystemUtils;
  import org.apache.ojb.broker.util.logging.Logger;
  import org.apache.ojb.broker.util.logging.LoggerFactory;
  
  import java.io.Serializable;
  import java.util.Collection;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.ArrayList;
  import java.util.List;
  
  /**
   * Manages all {@link JdbcConnectionDescriptor} instances.
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: ConnectionRepository.java,v 1.1 2002/12/24 13:14:33 arminw Exp $
   */
  public class ConnectionRepository implements Serializable, XmlCapable
  {
      private static Logger log = LoggerFactory.getLogger(ConnectionRepository.class);
  
      public static final String DATABASE_METADATA_FILENAME = "repository_database.xml";
      private HashMap jcdMap = new HashMap();
  
      public ConnectionRepository()
      {
      }
  
      /**
       * Returns a copy of the matching {@link JdbcConnectionDescriptor}.
       */
      public JdbcConnectionDescriptor getDescriptor(String jcdAlias)
      {
          JdbcConnectionDescriptor result = (JdbcConnectionDescriptor) jcdMap.get(jcdAlias);
          if (result != null)
          {
              result = (JdbcConnectionDescriptor) SerializationUtils.clone(result);
          }
          else
          {
              log.info("Could not found " + JdbcConnectionDescriptor.class.getName() + " for alias '" + jcdAlias + "'");
          }
          return result;
      }
  
      /**
       * Add a new {@link JdbcConnectionDescriptor}.
       */
      public void addDescriptor(JdbcConnectionDescriptor jcd)
      {
          synchronized (jcdMap)
          {
              if (jcdMap.containsKey(jcd.getJcdAlias()))
              {
                  throw new MetadataException("Found duplicate jcd-alias '" + jcd.getJcdAlias() +
                          "', remove the old descriptor first, before add anew one with same jcd-alias. "+jcd);
              }
              jcdMap.put(jcd.getJcdAlias(), jcd);
              if(log.isDebugEnabled()) log.debug("New descriptor was added: " + jcd);
          }
      }
  
      /**
       * Remove a descriptor.
       * @param validKey  This could be the {@link JdbcConnectionDescriptor}
       * itself, or the {@link JdbcConnectionDescriptor#getJcdAlias jcd-alias name}
       * as String.
       */
      public void removeDescriptor(Object validKey)
      {
          String jcdMapKey;
          if (validKey instanceof String)
          {
              jcdMapKey = (String) validKey;
          }
          else if (validKey instanceof JdbcConnectionDescriptor)
          {
              jcdMapKey = ((JdbcConnectionDescriptor) validKey).getJcdAlias();
          }
          else
          {
              throw new MetadataException("Could not remove descriptor, given object was no vaild key: " +
                      validKey);
          }
          Object removed = null;
          synchronized (jcdMap)
          {
              removed = jcdMap.remove(jcdMapKey);
          }
          log.info("Remove descriptor: " + removed);
      }
  
      /**
       * Return a deep copy of all managed {@link JdbcConnectionDescriptor}.
       */
      public List getAllDescriptor()
      {
          return (List) SerializationUtils.clone(new ArrayList(jcdMap.values()));
      }
  
      public String toXML()
      {
          String eol = SystemUtils.LINE_SEPARATOR;
          // use copy to avoid sync problems
          HashMap map = (HashMap) jcdMap.clone();
          StringBuffer buf = new StringBuffer();
          buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
          buf.append(eol);
          buf.append("<database-repository>");
          buf.append(eol);
          buf.append(eol);
          Iterator it = map.values().iterator();
          while (it.hasNext())
          {
              JdbcConnectionDescriptor jcd = (JdbcConnectionDescriptor) it.next();
              buf.append(jcd.toXML());
              buf.append(eol);
          }
          buf.append(eol);
          buf.append("</database-repository>");
          return buf.toString();
      }
  }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/metadata/ConnectionDescriptorXmlHandler.java
  
  Index: ConnectionDescriptorXmlHandler.java
  ===================================================================
  package org.apache.ojb.broker.metadata;
  
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache ObjectRelationalBridge" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache ObjectRelationalBridge", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  import org.apache.ojb.broker.PersistenceBrokerException;
  import org.apache.ojb.broker.util.logging.Logger;
  import org.apache.ojb.broker.util.logging.LoggerFactory;
  import org.apache.ojb.broker.util.ClassHelper;
  import org.xml.sax.Attributes;
  import org.xml.sax.SAXException;
  import org.xml.sax.SAXParseException;
  import org.xml.sax.helpers.DefaultHandler;
  
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.util.List;
  
  /**
   * The handler catches Parsing events raised by the xml-parser
   * and builds up the {@link ConnectionRepository} that is used
   * within the OJB PersistenceBroker System.
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: ConnectionDescriptorXmlHandler.java,v 1.1 2002/12/24 13:14:33 arminw Exp $
   */
  public class ConnectionDescriptorXmlHandler
          extends DefaultHandler
          implements RepositoryElements, IsolationLevels
  {
      private Logger logger = LoggerFactory.getLogger(ConnectionDescriptorXmlHandler.class);
  
      private ConnectionRepository con_repository;
      private JdbcConnectionDescriptor m_CurrentJCD;
  //    private String m_CurrentString;
      private List conDesList;
  
      /**
       * All known xml tags are kept in this table.
       * The tags table allows lookup from literal to id
       * and from id to literal.
       */
      private RepositoryTags tags = RepositoryTags.getInstance();
  
      /**
       * build a handler that fills the given repository
       * from an XML file.
       */
      public ConnectionDescriptorXmlHandler(ConnectionRepository cr)
      {
          if (cr != null)
          {
              con_repository = cr;
              conDesList = new ArrayList();
          }
          else
          {
              throw new MetadataException("Given ConnectionRepository argument was null");
          }
      }
  
      /**
       * startDocument callback, nothing to do here.
       */
      public void startDocument()
      {
          logger.debug("****   startDoc   ****");
      }
  
      /**
       * Here we overgive the found descriptors to {@link ConnectionRepository}.
       */
      public void endDocument()
      {
          logger.debug("****   endDoc   ****");
          for (Iterator iterator = conDesList.iterator(); iterator.hasNext();)
          {
              JdbcConnectionDescriptor jcd = (JdbcConnectionDescriptor) iterator.next();
              con_repository.addDescriptor(jcd);
          }
      }
  
      /**
       * startElement callback.
       * Only some Elements need special start operations.
       * @throws MetadataException indicating mapping errors
       */
      public void startElement(String uri, String name, String qName, Attributes atts)
      {
          boolean isDebug = logger.isDebugEnabled();
          try
          {
              switch (getLiteralId(qName))
              {
                  case JDBC_CONNECTION_DESCRIPTOR:
                      {
                          if (isDebug) logger.debug("   > " + tags.getTagById(JDBC_CONNECTION_DESCRIPTOR));
                          JdbcConnectionDescriptor newJcd = new JdbcConnectionDescriptor();
                          conDesList.add(newJcd);
                          m_CurrentJCD = newJcd;
  
                          // set the jcdAlias attribute
                          String jcdAlias = atts.getValue(tags.getTagById(JCD_ALIAS));
                          if (isDebug) logger.debug("     " + tags.getTagById(JCD_ALIAS) + ": " + jcdAlias);
                          m_CurrentJCD.setJcdAlias(jcdAlias);
  
                          // set the jcdAlias attribute
                          String defaultConnection = atts.getValue(tags.getTagById(DEFAULT_CONNECTION));
                          if (isDebug) logger.debug("     " + tags.getTagById(DEFAULT_CONNECTION) + ": " + defaultConnection);
                          m_CurrentJCD.setDefaultConnection(Boolean.valueOf(defaultConnection).booleanValue());
  
                          // set platform attribute
                          String platform = atts.getValue(tags.getTagById(DBMS_NAME));
                          if (isDebug) logger.debug("     " + tags.getTagById(DBMS_NAME) + ": " + platform);
                          m_CurrentJCD.setDbms(platform);
  
                          // set jdbc-level attribute
                          String level = atts.getValue(tags.getTagById(JDBC_LEVEL));
                          if (isDebug) logger.debug("     " + tags.getTagById(JDBC_LEVEL) + ": " + level);
                          m_CurrentJCD.setJdbcLevel(level);
  
                          // set driver attribute
                          String driver = atts.getValue(tags.getTagById(DRIVER_NAME));
                          if (isDebug) logger.debug("     " + tags.getTagById(DRIVER_NAME) + ": " + driver);
                          m_CurrentJCD.setDriver(driver);
  
                          // set protocol attribute
                          String protocol = atts.getValue(tags.getTagById(URL_PROTOCOL));
                          if (isDebug) logger.debug("     " + tags.getTagById(URL_PROTOCOL) + ": " + protocol);
                          m_CurrentJCD.setProtocol(protocol);
  
                          // set subprotocol attribute
                          String subprotocol = atts.getValue(tags.getTagById(URL_SUBPROTOCOL));
                          if (isDebug) logger.debug("     " + tags.getTagById(URL_SUBPROTOCOL) + ": " + subprotocol);
                          m_CurrentJCD.setSubProtocol(subprotocol);
  
                          // set the dbalias attribute
                          String dbalias = atts.getValue(tags.getTagById(URL_DBALIAS));
                          if (isDebug) logger.debug("     " + tags.getTagById(URL_DBALIAS) + ": " + dbalias);
                          m_CurrentJCD.setDbAlias(dbalias);
  
                          // set the datasource attribute
                          String datasource = atts.getValue(tags.getTagById(DATASOURCE_NAME));
                          if (isDebug) logger.debug("     " + tags.getTagById(DATASOURCE_NAME) + ": " + datasource);
                          m_CurrentJCD.setDatasourceName(datasource);
  
                          // set the user attribute
                          String user = atts.getValue(tags.getTagById(USER_NAME));
                          if (isDebug) logger.debug("     " + tags.getTagById(USER_NAME) + ": " + user);
                          m_CurrentJCD.setUserName(user);
  
                          // set the password attribute
                          String password = atts.getValue(tags.getTagById(USER_PASSWD));
                          if (isDebug) logger.debug("     " + tags.getTagById(USER_PASSWD) + ": " + password);
                          m_CurrentJCD.setPassWord(password);
  
                          // set eager-release attribute
                          String eagerRelease = atts.getValue(tags.getTagById(EAGER_RELEASE));
                          if (isDebug) logger.debug("     " + tags.getTagById(EAGER_RELEASE) + ": " + eagerRelease);
                          m_CurrentJCD.setEagerRelease(Boolean.valueOf(eagerRelease).booleanValue());
  
                          // set batch-mode attribute
                          String batchMode = atts.getValue(tags.getTagById(BATCH_MODE));
                          if (isDebug) logger.debug("     " + tags.getTagById(BATCH_MODE) + ": " + batchMode);
                          m_CurrentJCD.setBatchMode(Boolean.valueOf(batchMode).booleanValue());
  
  
                          break;
                      }
                  case CONNECTION_POOL:
                      {
                          if (isDebug) logger.debug("    > " + tags.getTagById(CONNECTION_POOL));
                          ConnectionPoolDescriptor m_CurrentCPD = m_CurrentJCD.getConnectionPoolDescriptor();
  
                          String maxActive = atts.getValue(tags.getTagById(CON_MAX_ACTIVE));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_MAX_ACTIVE) + ": " + maxActive);
                          if (checkString(maxActive)) m_CurrentCPD.setMaxActive(new Integer(maxActive).intValue());
  
                          String maxIdle = atts.getValue(tags.getTagById(CON_MAX_IDLE));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_MAX_IDLE) + ": " + maxIdle);
                          if (checkString(maxIdle)) m_CurrentCPD.setMaxIdle(new Integer(maxIdle).intValue());
  
                          String maxWait = atts.getValue(tags.getTagById(CON_MAX_WAIT));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_MAX_WAIT) + ": " + maxWait);
                          if (checkString(maxWait)) m_CurrentCPD.setMaxWait(new Integer(maxWait).intValue());
  
                          String minEvictableIdleTimeMillis = atts.getValue(tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_MIN_EVICTABLE_IDLE_TIME_MILLIS) + ": " + minEvictableIdleTimeMillis);
                          if (checkString(minEvictableIdleTimeMillis)) m_CurrentCPD.setMinEvictableIdleTimeMillis(new Long(minEvictableIdleTimeMillis).longValue());
  
                          String numTestsPerEvictionRun = atts.getValue(tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_NUM_TESTS_PER_EVICTION_RUN) + ": " + numTestsPerEvictionRun);
                          if (checkString(numTestsPerEvictionRun)) m_CurrentCPD.setNumTestsPerEvictionRun(new Integer(numTestsPerEvictionRun).intValue());
  
                          String testOnBorrow = atts.getValue(tags.getTagById(CON_TEST_ON_BORROW));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_TEST_ON_BORROW) + ": " + testOnBorrow);
                          if (checkString(testOnBorrow)) m_CurrentCPD.setTestOnBorrow(new Boolean(testOnBorrow).booleanValue());
  
                          String testOnReturn = atts.getValue(tags.getTagById(CON_TEST_ON_RETURN));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_TEST_ON_RETURN) + ": " + testOnReturn);
                          if (checkString(testOnReturn)) m_CurrentCPD.setTestOnReturn(new Boolean(testOnReturn).booleanValue());
  
                          String testWhileIdle = atts.getValue(tags.getTagById(CON_TEST_WHILE_IDLE));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_TEST_WHILE_IDLE) + ": " + testWhileIdle);
                          if (checkString(testWhileIdle)) m_CurrentCPD.setTestWhileIdle(new Boolean(testWhileIdle).booleanValue());
  
                          String timeBetweenEvictionRunsMillis = atts.getValue(tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_TIME_BETWEEN_EVICTION_RUNS_MILLIS) + ": " + timeBetweenEvictionRunsMillis);
                          if (checkString(timeBetweenEvictionRunsMillis)) m_CurrentCPD.setTimeBetweenEvictionRunsMillis(new Long(timeBetweenEvictionRunsMillis).longValue());
  
                          String whenExhaustedAction = atts.getValue(tags.getTagById(CON_WHEN_EXHAUSTED_ACTION));
                          if (isDebug) logger.debug("     " + tags.getTagById(CON_WHEN_EXHAUSTED_ACTION) + ": " + whenExhaustedAction);
                          if (checkString(whenExhaustedAction)) m_CurrentCPD.setWhenExhaustedAction(new Byte(whenExhaustedAction).byteValue());
  
                          String connectionFactoryStr = atts.getValue(tags.getTagById(CONNECTION_FACTORY));
                          if (isDebug) logger.debug("     " + tags.getTagById(CONNECTION_FACTORY) + ": " + connectionFactoryStr);
                          if (checkString(connectionFactoryStr)) m_CurrentCPD.setConnectionFactory(ClassHelper.getClass(connectionFactoryStr));
  
                          String validationQuery = atts.getValue(tags.getTagById(VALIDATION_QUERY));
                          if (isDebug) logger.debug("     " + tags.getTagById(VALIDATION_QUERY) + ": " + validationQuery);
                          if (checkString(connectionFactoryStr)) m_CurrentCPD.setValidationQuery(validationQuery);
  
                          break;
                      }
                  default :
                      {
                          // nop
                      }
              }
          }
          catch (Exception ex)
          {
              logger.error(ex);
              throw new PersistenceBrokerException(ex);
          }
      }
  
      private boolean checkString(String str)
      {
          return (str != null && !str.equals(""));
      }
  
      /**
       * returns the XmlCapable id associated with the literal.
       * OJB maintains a RepositoryTags table that provides
       * a mapping from xml-tags to XmlCapable ids.
       * @param literal the literal to lookup
       * @return the int value representing the XmlCapable
       *
       * @throws MetadataException if no literal was found in tags mapping
       */
      private int getLiteralId(String literal) throws PersistenceBrokerException
      {
          try
          {
              return tags.getIdByTag(literal);
          }
          catch (Exception e)
          {
              throw new MetadataException("unknown literal: '" + literal + "'", e);
          }
      }
  
      /**
       * endElement callback. most elements are build up from here.
       */
      public void endElement(String uri, String name, String qName)
      {
          try
          {
              switch (getLiteralId(qName))
              {
                  case JDBC_CONNECTION_DESCRIPTOR:
                      {
                          logger.debug("   < " + tags.getTagById(JDBC_CONNECTION_DESCRIPTOR));
                          break;
                      }
                  case CONNECTION_POOL:
                      {
                          logger.debug("   < " + tags.getTagById(CONNECTION_POOL));
                          break;
                      }
                  default :
                      {
                          // noop
                      }
              }
          }
          catch (Exception ex)
          {
              logger.error(ex);
              throw new PersistenceBrokerException(ex);
          }
      }
  
  //    /**
  //     * characters callback.
  //     */
  //    public void characters(char ch[], int start, int length)
  //    {
  //        if (m_CurrentString == null)
  //            m_CurrentString = new String(ch, start, length);
  //        else
  //            m_CurrentString += new String(ch, start, length);
  //    }
  
      /**
       * Error callback.
       */
      public void error(SAXParseException e) throws SAXException
      {
          logger.error(e);
          throw e;
      }
  
      /**
       * fatal error callback.
       */
      public void fatalError(SAXParseException e) throws SAXException
      {
          logger.fatal(e);
          throw e;
      }
  
      /**
       * warning callback.
       */
      public void warning(SAXParseException e) throws SAXException
      {
          logger.warn(e);
          throw e;
      }
  }
  
  
  
  1.3       +20 -10    jakarta-ojb/src/java/org/apache/ojb/broker/metadata/torque/TorqueRepositoryGenerator.java
  
  Index: TorqueRepositoryGenerator.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/metadata/torque/TorqueRepositoryGenerator.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- TorqueRepositoryGenerator.java	17 Jun 2002 19:34:11 -0000	1.2
  +++ TorqueRepositoryGenerator.java	24 Dec 2002 13:14:35 -0000	1.3
  @@ -61,26 +61,30 @@
   import java.io.IOException;
   import java.util.Iterator;
   
  -public class TorqueRepositoryGenerator {
  +public class TorqueRepositoryGenerator
  +{
   
       private TorqueTablePreprocessor tablePreprocessor;
       private TorqueTableGenerator tableGenerator;
   
  -    public TorqueRepositoryGenerator(String xmlInputFile, boolean ignoreAutoIncrement) throws Exception {
  +    public TorqueRepositoryGenerator(String xmlInputFile, boolean ignoreAutoIncrement) throws Exception
  +    {
           RepositoryPersistor persistor = new RepositoryPersistor();
  -        DescriptorRepository repository = persistor.readFromFile(xmlInputFile);
  +        DescriptorRepository repository = persistor.readDescriptorRepository(xmlInputFile);
           this.tablePreprocessor = new TorqueTablePreprocessor(repository);
           this.tablePreprocessor.buildStandardTables();
           this.tableGenerator = new TorqueTableGenerator(repository, ignoreAutoIncrement);
       }
   
  -    public void generateTorqueRepository(String xmlOutputFile, String databaseName, String indexTablespaceName) throws Exception {
  +    public void generateTorqueRepository(String xmlOutputFile, String databaseName, String indexTablespaceName) throws Exception
  +    {
           Iterator tableDescriptorIterators = this.tablePreprocessor.getStandardTables().values().iterator();
           StringBuffer buffer = new StringBuffer(4096);
   
           generateDatabaseHeader(databaseName, indexTablespaceName, buffer);
   
  -        while (tableDescriptorIterators.hasNext()) {
  +        while (tableDescriptorIterators.hasNext())
  +        {
               this.tableGenerator.generateStandardTable((TableDescriptor) tableDescriptorIterators.next(), buffer, indexTablespaceName);
           }
   
  @@ -89,7 +93,8 @@
           generateOutputFile(xmlOutputFile, buffer);
       }
   
  -    private void generateDatabaseHeader(String databaseName, String indexTablespaceName, StringBuffer buffer) {
  +    private void generateDatabaseHeader(String databaseName, String indexTablespaceName, StringBuffer buffer)
  +    {
           buffer.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"yes\" ?>\n");
           buffer.append("<!DOCTYPE database>\n\n");
           buffer.append("<database name=\"");
  @@ -99,19 +104,24 @@
           buffer.append("\">\n");
       }
   
  -    private void generateOutputFile(String xmlOutputFile, StringBuffer buffer) throws IOException {
  +    private void generateOutputFile(String xmlOutputFile, StringBuffer buffer) throws IOException
  +    {
           FileWriter writer = new FileWriter(xmlOutputFile);
           writer.write(buffer.toString());
           writer.flush();
           writer.close();
       }
   
  -    public static void main(String args[]) throws Exception {
  -        if (args.length >= 4 && args.length <= 5) {
  +    public static void main(String args[]) throws Exception
  +    {
  +        if (args.length >= 4 && args.length <= 5)
  +        {
               boolean ignoreAutoIncrement = (args.length == 5 && args[4].equalsIgnoreCase("true"));
               TorqueRepositoryGenerator generator = new TorqueRepositoryGenerator(args[0], ignoreAutoIncrement);
               generator.generateTorqueRepository(args[1], args[2], args[3]);
  -        } else {
  +        }
  +        else
  +        {
               System.out.println("[TorqueRepositoryGenerator] Usage: inputFile outputFile databaseName indexTablespaceName (ignoreAutoIncrement)");
           }
       }
  
  
  

Mime
View raw message