Package org.jpox.store.mapped.mapping

Source Code of org.jpox.store.mapped.mapping.MultiMapping

/**********************************************************************
Copyright (c) 2005 Andy Jefferson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


Contributors:
    ...
**********************************************************************/
package org.jpox.store.mapped.mapping;

import org.jpox.ClassLoaderResolver;
import org.jpox.ObjectManager;
import org.jpox.ObjectManagerHelper;
import org.jpox.StateManager;
import org.jpox.api.ApiAdapter;
import org.jpox.exceptions.JPOXException;
import org.jpox.exceptions.JPOXObjectNotFoundException;
import org.jpox.exceptions.JPOXUserException;
import org.jpox.identity.OID;
import org.jpox.identity.OIDFactory;
import org.jpox.metadata.AbstractMemberMetaData;
import org.jpox.metadata.MetaDataManager;
import org.jpox.metadata.Relation;
import org.jpox.store.exceptions.NotYetFlushedException;
import org.jpox.store.exceptions.NullValueException;
import org.jpox.util.JPOXLogger;

/**
* Mapping to represent multiple mappings.
* This mapping can be used to represent, for example,
* <UL>
* <LI>a reference field (where there are multiple implementations)</LI>
* <LI>an element in a collection and the element has no table of its own, but multiple subclasses</LI>
* <LI>a FK of a PC field (where there may be multiple fields in the PK of the PC object)</LI>
* </UL>
* @version $Revision: 1.37 $
**/
public abstract class MultiMapping extends JavaTypeMapping
{
    /** The Java mappings represented by this mapping. */
    protected JavaTypeMapping[] javaTypeMappings = new JavaTypeMapping[0];

    /** Number of DatastoreField - convenience field to improve performance **/
    private int numberOfDatastoreFields = 0;

    /**
     * Method to add a Java type mapping for a field
     * @param mapping The mapping to add
     */
    public void addJavaTypeMapping(JavaTypeMapping mapping)
    {
        JavaTypeMapping[] jtm = javaTypeMappings;
        javaTypeMappings = new JavaTypeMapping[jtm.length+1];
        System.arraycopy(jtm, 0, javaTypeMappings, 0, jtm.length);
        javaTypeMappings[jtm.length] = mapping;
    }

    /**
     * Accessor for the Java type mappings
     * @return The Java type mappings
     */
    public JavaTypeMapping[] getJavaTypeMapping()
    {
        return javaTypeMappings;
    }

    /**
     * Accessor for the number of datastore fields.
     * @return The number of datastore fields.
     */
    public int getNumberOfDatastoreFields()
    {
        if (numberOfDatastoreFields == 0)
        {
            for (int i=0; i<javaTypeMappings.length; i++)
            {
                numberOfDatastoreFields += javaTypeMappings[i].getNumberOfDatastoreFields();
            }
        }
        return numberOfDatastoreFields;
    }

    /**
     * Accessor for a datastore mapping.
     * @param index The position of the mapping to return
     * @return The datastore mapping
     */
    public DatastoreMapping getDataStoreMapping(int index)
    {
        int currentIndex = 0;
        int numberJavaMappings = javaTypeMappings.length;
        for (int i=0; i<numberJavaMappings; i++)
        {
            int numberDatastoreMappings = javaTypeMappings[i].getNumberOfDatastoreFields();
            for (int j=0; j<numberDatastoreMappings; j++)
            {
                if (currentIndex == index)
                {
                    return javaTypeMappings[i].getDataStoreMapping(j);
                }
                currentIndex++;
            }
        }

        // TODO Localise this message
        throw new JPOXException("Invalid index " + index + " for DataStoreMapping.").setFatal();
    }

    /**
     * Method to set the parameters in the PreparedStatement with the fields of
     * this object.
     * @param om Object Manager
     * @param ps The PreparedStatement
     * @param pos The parameter positions
     * @param value The object to populate the statement with
     * @throws NotYetFlushedException Thrown if the object is not yet flushed to the datastore
     */
    public void setObject(ObjectManager om, Object ps, int[] pos, Object value)
    {
      setObject(om, ps, pos, value, null, -1);
    }
   
    /**
     * Sets a <code>value</code> into <code>preparedStatement</code>
     * at position specified by <code>exprIndex</code>.
     * @param om the ObjectManager
     * @param ps a datastore object that executes statements in the database
     * @param pos the position of the value in the statement
     * @param value the value
     * @param ownerSM the owner StateManager
     * @param ownerFieldNumber the owner absolute field number
     */   
    public void setObject(ObjectManager om, Object ps, int[] pos, Object value, StateManager ownerSM, int ownerFieldNumber)
    {
        ClassLoaderResolver clr = om.getClassLoaderResolver();
        ApiAdapter api = om.getApiAdapter();

        int n = 0;
        boolean foundClassAssignableFromValue = false;
        NotYetFlushedException notYetFlushed = null;

        if (value != null)
        {
          if (!om.isInserting(value))
          {
              // Object either already exists, or is not yet being inserted.
              Object id = api.getIdForObject(value);

              // Check if the PersistenceCapable exists in this datastore
              boolean requiresPersisting = false;
              if (om.getApiAdapter().isDetached(value) && ownerSM != null)
              {
                  // Detached object that needs attaching (or persisting if detached from a different datastore)
                  requiresPersisting = true;
              }
              else if (id == null)
              {
                  // Transient object, so we need to persist it
                  requiresPersisting = true;
              }
              else
              {
                    ObjectManager valueOM = ObjectManagerHelper.getObjectManager(value);
                  if (valueOM != null && om != valueOM)
                  {
                      throw new JPOXUserException(LOCALISER.msg("041015"), id);
                  }
              }
             
              if (requiresPersisting)
              {
                  // The object is either not yet persistent or is detached and so needs attaching
                  Object pcNew = om.persistObjectInternal(value, null, null, -1, StateManager.PC);
                  om.flushInternal(false);
                  id = api.getIdForObject(pcNew);
                  if (om.getApiAdapter().isDetached(value) && ownerSM != null)
                  {
                      // Update any detached reference to refer to the attached variant
                      ownerSM.replaceField(ownerFieldNumber, pcNew, true);
                        int relationType = fmd.getRelationType(clr);
                        if (relationType == Relation.ONE_TO_ONE_BI)
                        {
                            StateManager relatedSM = om.findStateManager(pcNew);
                            AbstractMemberMetaData[] relatedMmds = fmd.getRelatedMemberMetaData(clr);
                            // TODO Allow for multiple related fields
                            relatedSM.replaceField(relatedMmds[0].getAbsoluteFieldNumber(), ownerSM.getObject(), true);
                        }
                        else if (relationType == Relation.MANY_TO_ONE_BI)
                        {
                            // TODO Update the container element with the attached variant
                            if (JPOXLogger.PERSISTENCE.isInfoEnabled())
                            {
                                JPOXLogger.PERSISTENCE.info("PCMapping.setObject : object " + ownerSM.getInternalObjectId() +
                                    " has field " + ownerFieldNumber +
                                    " that is 1-N bidirectional - should really update the reference in the relation. Not yet supported");
                            }
                        }
                  }
              }       
            if (getNumberOfDatastoreFields() <= 0)
            {
                // If the field doesnt map to any datastore fields, omit the set process
              return;
            }         
          }
        }

        Class type = null;
        StateManager sm = null;
        if (value != null)
        {
            sm = om.findStateManager(value);
        }
        try
        {
          if (pos == null)
          {
            return;
          }
          if (sm != null)
          {
              sm.setStoringPC();
          }

            MetaDataManager mmgr = om.getStoreManager().getOMFContext().getMetaDataManager();
          boolean isPersistentInterface = mmgr.getMetaDataForInterface(clr.classForName(getType()), clr) != null;
          if (isPersistentInterface)
          {
              // Field is declared as a "persistent-interface" type so all impls of that type should match
              type = clr.classForName(getType());
          }
          else if (fmd != null && fmd.getFieldTypes() != null && fmd.getFieldTypes().length == 1)
          {
              isPersistentInterface = mmgr.getMetaDataForInterface(clr.classForName(fmd.getFieldTypes()[0]), clr) != null;
              if (isPersistentInterface)
              {
                  // Field is declared as interface and accepts "persistent-interface" value, so all impls should match
                  type = clr.classForName(fmd.getFieldTypes()[0]);
              }
          }

          for (int i=0; i<javaTypeMappings.length; i++)
          {
              if (n >=pos.length)
              {
                //this means we store all implementations to the same columns, so we reset the index
                n = 0;
                }
              int[] posMapping;
              if (javaTypeMappings[i].getReferenceMapping() != null)
              {          
                  posMapping = new int[javaTypeMappings[i].getReferenceMapping().getNumberOfDatastoreFields()];             
              }
              else
              {
                posMapping = new int[javaTypeMappings[i].getNumberOfDatastoreFields()];
              }
              for (int j=0; j<posMapping.length; j++)
              {
                  posMapping[j] = pos[n++];
              }
              try
              {
                    if (!isPersistentInterface)
                    {
                        // Normal interface
                        type = clr.classForName(javaTypeMappings[i].getType());
                    }
                    if (value != null && type.isAssignableFrom(value.getClass()))
                    {
                        foundClassAssignableFromValue = true;
                        javaTypeMappings[i].setObject(om, ps, posMapping, value);
                    }
                    else
                    {
                        javaTypeMappings[i].setObject(om, ps, posMapping, null);
                    }
                }
              catch (NotYetFlushedException e)
              {
                  notYetFlushed = e;
              }
          }
          if (notYetFlushed != null)
          {
              throw notYetFlushed;
          }
        }
        finally
        {
            if (sm != null)
            {
                sm.unsetStoringPC();
            }         
        }
        if (value != null && !foundClassAssignableFromValue)
        {
            // as required by the JDO spec, a ClassCastException is thrown
            // TODO Change this to a multiple field mapping localised message
            throw new ClassCastException(LOCALISER.msg("041044",
                fmd != null ? fmd.getFullFieldName() : "", type.getName(), value.getClass().getName()));
        }
    }

    /**
     * Method to retrieve an object of this type from the ResultSet.
     * @param om Object Manager
     * @param rs The ResultSet
     * @param pos The parameter positions
     * @return The object
     */
    public Object getObject(ObjectManager om, final Object rs, int[] pos)
    {
        // Go through the possible types for this field and find a non-null value (if there is one)
        int n = 0;
        for (int i=0; i<javaTypeMappings.length; i++)
        {
            int[] posMapping;
            if( n >=pos.length)
            {
              //this means we store all implementations to the same columns, so we reset the index
              n = 0;
            }

            if (javaTypeMappings[i].getReferenceMapping() != null)
            {
                posMapping = new int[javaTypeMappings[i].getReferenceMapping().getNumberOfDatastoreFields()];
            }
            else
            {
                posMapping = new int[javaTypeMappings[i].getNumberOfDatastoreFields()];
            }
            for (int j=0; j<posMapping.length; j++)
            {
                posMapping[j] = pos[n++];
            }

            Object value = null;
            try
            {
                // Retrieve the value (PC object) for this mappings' object
                value = javaTypeMappings[i].getObject(om, rs, posMapping);
            }
            catch (NullValueException e)
            {
                // expected if implementation object is null and has primitive
                // fields in the primary key
            }
            catch (JPOXObjectNotFoundException onfe)
            {
                // expected, will try next implementation
            }
            if (value != null)
            {
                if (value instanceof OID)
                {
                    // What situation is this catering for exactly ?
                    String className;
                    if (javaTypeMappings[i].getReferenceMapping() != null)
                    {
                        className = javaTypeMappings[i].getReferenceMapping().getDataStoreMapping(0).getDatastoreField().getStoredJavaType();
                    }
                    else
                    {
                        className = javaTypeMappings[i].getDataStoreMapping(0).getDatastoreField().getStoredJavaType();
                    }
                    value = OIDFactory.getInstance(om, className, ((OID)value).getKeyValue());
                    return om.findObject(value, false, true, null);
                }
                else if (om.getClassLoaderResolver().classForName(getType()).isAssignableFrom(value.getClass()))                
                {
                  return value;
                }
            }
        }
        return null;
    }
}
TOP

Related Classes of org.jpox.store.mapped.mapping.MultiMapping

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.