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/util SqlHelper.java ClassHelper.java BrokerHelper.java
Date Tue, 24 Dec 2002 13:25:26 GMT
arminw      2002/12/24 05:25:26

  Modified:    src/java/org/apache/ojb/broker/util BrokerHelper.java
  Added:       src/java/org/apache/ojb/broker/util SqlHelper.java
                        ClassHelper.java
  Log:
  more helper classes
  
  Revision  Changes    Path
  1.4       +327 -1    jakarta-ojb/src/java/org/apache/ojb/broker/util/BrokerHelper.java
  
  Index: BrokerHelper.java
  ===================================================================
  RCS file: /home/cvs/jakarta-ojb/src/java/org/apache/ojb/broker/util/BrokerHelper.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- BrokerHelper.java	29 Nov 2002 13:55:17 -0000	1.3
  +++ BrokerHelper.java	24 Dec 2002 13:25:26 -0000	1.4
  @@ -54,10 +54,21 @@
    * <http://www.apache.org/>.
    */
   
  +import org.apache.ojb.broker.OJBRuntimeException;
   import org.apache.ojb.broker.PBKey;
  +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.metadata.ClassDescriptor;
  +import org.apache.ojb.broker.metadata.FieldDescriptor;
  +import org.apache.ojb.broker.metadata.MetadataException;
  +import org.apache.ojb.broker.metadata.fieldaccess.PersistentField;
   import org.apache.ojb.broker.singlevm.PersistenceBrokerConfiguration;
  +import org.apache.ojb.broker.util.sequence.SequenceManagerException;
   
  +import java.lang.reflect.Proxy;
   import java.util.StringTokenizer;
   
   
  @@ -70,6 +81,13 @@
   {
       public static final String REPOSITORY_NAME_SEPARATOR = "#";
   
  +    private PersistenceBroker broker;
  +
  +    public BrokerHelper(PersistenceBroker broker)
  +    {
  +        this.broker = broker;
  +    }
  +
       /**
        * splits up the name string and extract db url,
        * user name and password and build a new PBKey
  @@ -99,4 +117,312 @@
           return ((PersistenceBrokerConfiguration) PersistenceBrokerFactory.
                   getConfigurator().getConfigurationFor(null)).isRunningInServerMode();
       }
  +
  +
  +
  +    // ***************************************************************************
  +    // methods from ClassDescriptor
  +    // ***************************************************************************
  +
  +
  +    /**
  +     * 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
  +     */
  +    public Object[] getKeyValues(ClassDescriptor cld, Object objectOrProxy, boolean convertToSql)
  +            throws PersistenceBrokerException
  +    {
  +        /*
  +        arminw
  +        TODO: Check it out. Because the isProxyClass method is costly and most objects
  +        aren't proxies, I add a instanceof check before. Is every Proxy a instance of Proxy?
  +        */
  +        if ((objectOrProxy instanceof Proxy) && Proxy.isProxyClass(objectOrProxy.getClass()))
  +        {
  +            // return getKeyValuesForProxy((Proxy) objectOrProxy);
  +            IndirectionHandler handler;
  +            handler = (IndirectionHandler) Proxy.getInvocationHandler((Proxy) objectOrProxy);
  +            return handler.getIdentity().getPrimaryKeyValues();
  +        }
  +        else if (objectOrProxy instanceof VirtualProxy)
  +        {
  +            // return getKeyValuesForProxy((VirtualProxy) objectOrProxy);
  +            IndirectionHandler handler;
  +            handler = (IndirectionHandler) VirtualProxy.getIndirectionHandler((VirtualProxy)
objectOrProxy);
  +            return handler.getIdentity().getPrimaryKeyValues();
  +        }
  +        else
  +        {
  +            // return getKeyValuesForObject(broker, cld, objectOrProxy, convertToSql);
  +
  +            FieldDescriptor[] pkFields = cld.getPkFields();
  +            Object[] result = new Object[pkFields.length];
  +            for (int i = 0; i < result.length; i++)
  +            {
  +                FieldDescriptor fmd = pkFields[i];
  +                PersistentField f = fmd.getPersistentField();
  +                Object cv = f.get(objectOrProxy);
  +
  +                // handle autoincrement attributes if not filled
  +                if (fmd.isAutoIncrement())
  +                {
  +                    cv = getAutoIncrementValue(fmd, objectOrProxy, cv);
  +                }
  +
  +                if (convertToSql)
  +                {
  +                    // BRJ : apply type and value mapping
  +                    cv = fmd.getFieldConversion().javaToSql(cv);
  +                }
  +                result[i] = cv;
  +            }
  +            return result;
  +        }
  +    }
  +
  +    /**
  +     * 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
  +     */
  +    public Object[] getKeyValues(ClassDescriptor cld, Object objectOrProxy)
  +            throws PersistenceBrokerException
  +    {
  +        return getKeyValues(cld, objectOrProxy, true);
  +    }
  +
  +    /**
  +     * @throws MetadataException if there is an erros accessing obj field values
  +     */
  +    public 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;
  +            try
  +            {
  +                // 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.serviceSequenceManager().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.serviceSequenceManager().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.serviceSequenceManager().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.serviceSequenceManager().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 PersistenceBrokerException(
  +                        "Error while trying to autoincrement field " +
  +                        f.getDeclaringClass() + "#" + f.getName(), e);
  +            }
  +            catch (SequenceManagerException e)
  +            {
  +                throw new PersistenceBrokerException("Could not get key value", e);
  +            }
  +        }
  +        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(ClassDescriptor cld, Object o)
  +            throws PersistenceBrokerException
  +    {
  +        FieldDescriptor[] nonPkFields = cld.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;
  +    }
  +
  +
  +// Only used by StatementManager
  +//    /**
  +//     * returns an array containing values for all the Objects attribute
  +//     * @throws MetadataException if tehre is an erros accessing obj field values
  +//     */
  +//    public Object[] getAllValues(PersistenceBroker broker, ClassDescriptor cld,Object
obj) throws PersistenceBrokerException
  +//    {
  +//        FieldDescriptor[] allFields = cld.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(broker, fmd, obj, cv);
  +//            }
  +//
  +//            // apply type and value mapping
  +//            cv = fmd.getFieldConversion().javaToSql(cv);
  +//            result[i] = cv;
  +//        }
  +//        return result;
  +//    }
  +
  +
  +//    /**
  +//     * 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
  +//     */
  +//    protected static Object[] getKeyValuesForObject(PersistenceBroker broker, ClassDescriptor
cld, Object o, boolean convertToSql) throws PersistenceBrokerException
  +//    {
  +//        FieldDescriptor[] pkFields = cld.getPkFields();
  +//        Object[] result = new Object[pkFields.length];
  +//
  +//        for (int i = 0; i < result.length; i++)
  +//        {
  +//            FieldDescriptor fmd = pkFields[i];
  +//            PersistentField f = fmd.getPersistentField();
  +//            Object cv = f.get(o);
  +//
  +//            // handle autoincrement attributes if not filled
  +//            if (fmd.isAutoIncrement())
  +//            {
  +//                cv = getAutoIncrementValue(broker, fmd, o, cv);
  +//            }
  +//
  +//            if (convertToSql)
  +//            {
  +//                // BRJ : apply type and value mapping
  +//                cv = fmd.getFieldConversion().javaToSql(cv);
  +//            }
  +//            result[i] = cv;
  +//        }
  +//        return result;
  +//    }
  +//
  +//    /**
  +//     * returns an Array with the Proxy's PK VALUES
  +//     * @param aProxy
  +//     * @return Object[]
  +//     * @throws PersistenceBrokerException
  +//     */
  +//    protected static Object[] getKeyValuesForProxy(Proxy aProxy) throws PersistenceBrokerException
  +//    {
  +//        IndirectionHandler handler;
  +//
  +//        handler = (IndirectionHandler) Proxy.getInvocationHandler(aProxy);
  +//        return handler.getIdentity().getPrimaryKeyValues();
  +//    }
  +//
  +//    /**
  +//     * returns an Array with the VirtualProxy's PK VALUES
  +//     * @param aProxy
  +//     * @return Object[]
  +//     * @throws PersistenceBrokerException
  +//     */
  +//    protected static Object[] getKeyValuesForProxy(VirtualProxy aProxy) throws PersistenceBrokerException
  +//    {
  +//        IndirectionHandler handler;
  +//
  +//        handler = (IndirectionHandler) VirtualProxy.getIndirectionHandler(aProxy);
  +//        return handler.getIdentity().getPrimaryKeyValues();
  +//    }
   }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/util/SqlHelper.java
  
  Index: SqlHelper.java
  ===================================================================
  package org.apache.ojb.broker.util;
  
  /**
   * Helper class for all SQL related stuff.
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: SqlHelper.java,v 1.1 2002/12/24 13:25:26 arminw Exp $
   */
  public class SqlHelper
  {
      /**
       * remove functions and () from path
       * ie: avg(amount) -> amount <br>
       * ie: sum(accounts.amount) -> accounts.amount
       * @param aPath the path to the attribute
       */
      public static String cleanPath(String aPath)
      {
          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
          {
              return aPath;
          }
      }
  }
  
  
  
  1.1                  jakarta-ojb/src/java/org/apache/ojb/broker/util/ClassHelper.java
  
  Index: ClassHelper.java
  ===================================================================
  package org.apache.ojb.broker.util;
  
  import org.apache.ojb.broker.util.logging.Logger;
  import org.apache.ojb.broker.util.logging.LoggerFactory;
  
  import java.lang.reflect.InvocationTargetException;
  
  /**
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: ClassHelper.java,v 1.1 2002/12/24 13:25:26 arminw Exp $
   */
  public class ClassHelper
  {
      //private static Logger log = LoggerFactory.getLogger(ClassHelper.class);
  
      /**
       * Returns a class object for the given name or <i>null</i>
       */
      public static Class getClass(String className, boolean initialize) throws ClassNotFoundException
      {
          return Class.forName(className, initialize, Thread.currentThread().getContextClassLoader());
      }
  
      /**
       * Returns new instance of the given class, using the default constructor.
       */
      public static Object newInstance(Class target) throws InstantiationException,
              IllegalAccessException, ClassNotFoundException
      {
          return target.newInstance();
      }
  
      /**
       * Returns new instance of the given class name, using the default constructor.
       */
      public static Object newInstance(Class target, Class[] types, Object[] args) throws
              InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
              NoSuchMethodException, SecurityException, ClassNotFoundException
      {
          return target.getConstructor(types).newInstance(args);
      }
  
  
  
      // *******************************************************************
      // Convenience methods
      // *******************************************************************
  
      /**
       * Convenience for
       * {@link #getClass(String, boolean) getClass(name, true)}
       */
      public static Class getClass(String name) throws ClassNotFoundException
      {
          return getClass(name, true);
      }
  
  
      /**
       * Returns new instance of the given class name, using the default constructor.
       */
      public static Object newInstance(String className) throws InstantiationException,
              IllegalAccessException, ClassNotFoundException
      {
          return newInstance(getClass(className));
      }
  
      /**
       * Returns new instance of the given class name, using the default constructor.
       */
      public static Object newInstance(String className, Class[] types, Object[] args) throws
              InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
              NoSuchMethodException, SecurityException, ClassNotFoundException
      {
          return newInstance(getClass(className),types, args);
      }
  
      public static Object newInstance(Class target, Class type, Object arg) throws
              InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
              NoSuchMethodException, SecurityException, ClassNotFoundException
      {
          return newInstance(target, new Class[]{type}, new Object[]{arg});
      }
  
      public static Object newInstance(String className, Class type, Object arg) throws
              InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
              NoSuchMethodException, SecurityException, ClassNotFoundException
      {
          return newInstance(className, new Class[]{type}, new Object[]{arg});
      }
  }
  
  
  

Mime
View raw message