Package org.datanucleus.state

Examples of org.datanucleus.state.ObjectProvider


      }
    };
    assertFalse(bm.batchOperationInProgress());
    bm.start();
    assertTrue(bm.batchOperationInProgress());
    final ObjectProvider sm1 = newStateManagerMock();
    final ObjectProvider sm2 = newStateManagerMock();
    bm.add(sm1);
    bm.add(sm2);
    JDOPersistenceManager jpm = (JDOPersistenceManager) pm;
    DatastoreManager dm = new DatastoreManager(
            jpm.getExecutionContext().getClassLoaderResolver(), jpm.getExecutionContext().getNucleusContext(),
View Full Code Here


      }
    };
    assertFalse(bm.batchOperationInProgress());
    bm.start();
    assertTrue(bm.batchOperationInProgress());
    final ObjectProvider sm1 = newStateManagerMock();
    final ObjectProvider sm2 = newStateManagerMock();
    bm.add(sm1);
    bm.add(sm2);
    JDOPersistenceManager jpm = (JDOPersistenceManager) pm;
    DatastoreManager dm = new DatastoreManager(
            jpm.getExecutionContext().getClassLoaderResolver(), jpm.getExecutionContext().getNucleusContext(),
View Full Code Here

                while (elementsIter.hasNext())
                {
                    Object elem = elementsIter.next();
                    if (api.isPersistable(elem))
                    {
                        ObjectProvider sm = ec.findObjectProvider(elem);
                        if (sm != null)
                        {
                            if (smsColl == null)
                            {
                                smsColl = new HashSet();
                            }
                            smsColl.add(sm);
                        }
                    }
                }
            }
            else if (value instanceof java.util.Map)
            {
                Iterator entriesIter = ((java.util.Map)value).entrySet().iterator();
                while (entriesIter.hasNext())
                {
                    Map.Entry entry = (Map.Entry)entriesIter.next();
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    if (api.isPersistable(key))
                    {
                        ObjectProvider sm = ec.findObjectProvider(key);
                        if (sm != null)
                        {
                            if (smsColl == null)
                            {
                                smsColl = new HashSet();
                            }
                            smsColl.add(sm);
                        }
                    }
                    if (api.isPersistable(val))
                    {
                        ObjectProvider sm = ec.findObjectProvider(val);
                        if (sm != null)
                        {
                            if (smsColl == null)
                            {
                                smsColl = new HashSet();
View Full Code Here

                        // Update any detached reference to refer to the attached variant
                        ownerSM.replaceFieldMakeDirty(ownerFieldNumber, pcNew);
                        RelationType relationType = mmd.getRelationType(clr);
                        if (relationType == RelationType.ONE_TO_ONE_BI)
                        {
                            ObjectProvider relatedSM = ec.findObjectProvider(pcNew);
                            AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                            // TODO Allow for multiple related fields
                            relatedSM.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), ownerSM.getObject());
                        }
                        else if (relationType == RelationType.MANY_TO_ONE_BI)
                        {
                            // TODO Update the container element with the attached variant
                            if (NucleusLogger.PERSISTENCE.isDebugEnabled())
                            {
                                NucleusLogger.PERSISTENCE.debug("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 (getNumberOfDatastoreMappings() <= 0)
                {
                    // If the field doesn't map to any datastore fields, omit the set process
                    return;
                }
            }
        }

        if (pos == null)
        {
            return;
        }

        ObjectProvider op = (value != null ? ec.findObjectProvider(value) : null);
        try
        {
            if (op != null)
            {
                op.setStoringPC();
            }

            int n = 0;
            NotYetFlushedException notYetFlushed = null;
            for (int i=0; i<javaTypeMappings.length; i++)
            {
                // Set the PreparedStatement positions for this implementation mapping
                int[] posMapping;
                if (setValueFKOnly)
                {
                    // Only using first "pos" value(s)
                    n = 0;
                }
                else if (n >= pos.length)
                {
                    n = 0; // store all implementations to the same columns, so we reset the index
                }
                if (javaTypeMappings[i].getReferenceMapping() != null)
                {
                    posMapping = new int[javaTypeMappings[i].getReferenceMapping().getNumberOfDatastoreMappings()];
                }
                else
                {
                    posMapping = new int[javaTypeMappings[i].getNumberOfDatastoreMappings()];
                }
                for (int j=0; j<posMapping.length; j++)
                {
                    posMapping[j] = pos[n++];
                }

                try
                {
                    if (javaTypeMappingNumber == -2 || (value != null && javaTypeMappingNumber == i))
                    {
                        // This mapping is where the value is to be stored, or using persistent interfaces
                        javaTypeMappings[i].setObject(ec, ps, posMapping, value);
                    }
                    else if (!setValueFKOnly)
                    {
                        // Set null for this mapping, since the value is null or is for something else
                        javaTypeMappings[i].setObject(ec, ps, posMapping, null);
                    }
                }
                catch (NotYetFlushedException e)
                {
                    notYetFlushed = e;
                }
            }
            if (notYetFlushed != null)
            {
                throw notYetFlushed;
            }
        }
        finally
        {
            if (op != null)
            {
                op.unsetStoringPC();
            }
        }
    }
View Full Code Here

    });

    if (!inserted) {
      // Element was already persistent so make sure the FK is in place
      // TODO This is really "ManagedRelationships" so needs to go in RelationshipManager
      ObjectProvider elementOP = ec.findObjectProvider(element);
      if (relationType == RelationType.ONE_TO_MANY_BI) {
        // Managed Relations : 1-N bidir, so update the owner of the element
        elementOP.isLoaded(getFieldNumberInElementForBidirectional(elementOP)); // Ensure is loaded
        Object oldOwner = elementOP.provideField(getFieldNumberInElementForBidirectional(elementOP));
        if (oldOwner != newOwner) {
          if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
            NucleusLogger.PERSISTENCE.debug(LOCALISER.msg("055009", StringUtils.toJVMIDString(op.getObject()),
                ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(element)));
          }

          int relatedFieldNumber = getFieldNumberInElementForBidirectional(elementOP);
          elementOP.replaceFieldMakeDirty(relatedFieldNumber, newOwner);
          if (ec.getManageRelations()) {
            // Managed Relationships - add the change we've made here to be analysed at flush
            ec.getRelationshipManager(elementOP).relationChange(relatedFieldNumber, oldOwner, newOwner);
          }

          if (ec.isFlushing()) {
            elementOP.flush();
          }
        }
        return oldOwner != newOwner;
      }
      else {
View Full Code Here

    if (elementsIter != null) {
      while (elementsIter.hasNext()) {
        Object element = elementsIter.next();
        if (ec.getApiAdapter().isPersistable(element) && ec.getApiAdapter().isDeleted(element)) {
          // Element is waiting to be deleted so flush it (it has the FK)
          ObjectProvider elementSM = ec.findObjectProvider(element);
          elementSM.flush();
        } else {
          if (deleteElements) {
            ec.deleteObjectInternal(element);
          } else {
            // TODO Null this out (in parent)
View Full Code Here

        if (cmd.getIdentityType() == IdentityType.APPLICATION)
        {
            AbstractMemberMetaData mmd =
                cmd.getMetaDataForManagedMemberAtAbsolutePosition(cmd.getPKMemberPositions()[index]);
            ObjectProvider sm = null;
            if (ec != null)
            {
                sm = ec.findObjectProvider(value);
            }

            if (sm == null)
            {
                // Transient or detached maybe, so use reflection to get PK field values
                if (mmd instanceof FieldMetaData)
                {
                    return ClassUtils.getValueOfFieldByReflection(value, mmd.getName());
                }
                else
                {
                    return ClassUtils.getValueOfMethodByReflection(value,
                        ClassUtils.getJavaBeanGetterName(mmd.getName(), false), (Object[])null);
                }
            }

            if (!mmd.isPrimaryKey())
            {
                // Make sure the field is loaded
                sm.isLoaded(mmd.getAbsoluteFieldNumber());
            }
            FieldManager fm = new SingleValueFieldManager();
            sm.provideFields(new int[] {mmd.getAbsoluteFieldNumber()}, fm);
            return fm.fetchObjectField(mmd.getAbsoluteFieldNumber());
        }
        else if (cmd.getIdentityType() == IdentityType.DATASTORE)
        {
            OID oid = (OID)nucleusCtx.getApiAdapter().getIdForObject(value);
View Full Code Here

    ExecutionContext ec = op.getExecutionContext();
    if (ec.getApiAdapter().isDetached(element)) {// User passed in detached object to collection.remove()! {
      // Find an attached equivalent of this detached object (DON'T attach the object itself)
      elementToRemove = ec.findObject(ec.getApiAdapter().getIdForObject(element), true, false, element.getClass().getName());
    }
    ObjectProvider elementOP = ec.findObjectProvider(elementToRemove);

    // Check for change of owner of the element (removed from this but added to another one maybe?)
    if (MetaDataUtils.isOwnedRelation(ownerMemberMetaData, storeMgr)) {
      // Check for ownership change when owned relation, and prevent changes
      Object oldOwner = null;
      if (relationType == RelationType.ONE_TO_MANY_BI) {
        if (!ec.getApiAdapter().isDeleted(elementToRemove)) {
          // Find the existing owner if the record hasn't already been deleted
          int elemOwnerFieldNumber = getFieldNumberInElementForBidirectional(elementOP);
          elementOP.isLoaded(elemOwnerFieldNumber);
          oldOwner = elementOP.provideField(elemOwnerFieldNumber);
        }
      }
      if (RelationType.isBidirectional(relationType) && oldOwner != op.getObject() && oldOwner != null) {
        // Owner of the element has been changed, so reject it
        return false;
      }
    }

    boolean deleteElements = deleteElementsOnRemoveOrClear();
    if (ec.getApiAdapter().isPersistable(elementToRemove) && ec.getApiAdapter().isDeleted(elementToRemove)) {
      // Element is waiting to be deleted so flush it (it has the FK)
      elementOP.flush();
    } else {
      if (deleteElements) {
        ec.deleteObjectInternal(elementToRemove);
      } else {
        // TODO Null it out
View Full Code Here

        if (!api.isPersistable(value))
        {
            throw new NucleusException(LOCALISER.msg("041016", value.getClass(), value)).setFatal();
        }

        ObjectProvider valueSM = ec.findObjectProvider(value);

        try
        {
            ClassLoaderResolver clr = ec.getClassLoaderResolver();

            // Check if the field is attributed in the datastore
            boolean hasDatastoreAttributedPrimaryKeyValues = hasDatastoreAttributedPrimaryKeyValues(
                ec.getMetaDataManager(), storeMgr, clr);

            boolean inserted = false;
            if (ownerFieldNumber >= 0)
            {
                // Field mapping : is this field of the related object present in the datastore?
                inserted = storeMgr.isObjectInserted(valueSM, ownerFieldNumber);
            }
            else if (mmd == null)
            {
                // Identity mapping : is the object inserted far enough to be considered of this mapping type?
                inserted = storeMgr.isObjectInserted(valueSM, type);
            }

            if (valueSM != null)
            {
                if (ec.getApiAdapter().isDetached(value) && valueSM.getReferencedPC() != null && ownerSM != null && mmd != null)
                {
                    // Still detached but started attaching so replace the field with what will be the attached
                    // Note that we have "fmd != null" here hence omitting any M-N relations where this is a join table
                    // mapping
                    ownerSM.replaceFieldMakeDirty(ownerFieldNumber, valueSM.getReferencedPC());
                }

                if (valueSM.isWaitingToBeFlushedToDatastore())
                {
                    // Related object is not yet flushed to the datastore so flush it so we can set the FK
                    valueSM.flush();
                }
            }
            else
            {
                if (ec.getApiAdapter().isDetached(value))
                {
                    // Field value is detached and not yet started attaching, so attach
                    Object attachedValue = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
                    if (attachedValue != value && ownerSM != null)
                    {
                        // Replace the field value if using copy-on-attach
                        ownerSM.replaceFieldMakeDirty(ownerFieldNumber, attachedValue);
                    }
                }
            }

            // we can execute this block when
            // 1) the pc has been inserted; OR
            // 2) is not in process of being inserted; OR
            // 3) is being inserted yet is inserted enough to use this mapping; OR
            // 4) the PC PK values are not attributed by the database and this mapping is for a PK field (compound identity)
            // 5) the value is the same object as we are inserting anyway and has its identity set
            if (inserted || !ec.isInserting(value) ||
                (!hasDatastoreAttributedPrimaryKeyValues && (this.mmd != null && this.mmd.isPrimaryKey())) ||
                (!hasDatastoreAttributedPrimaryKeyValues && ownerSM == valueSM && api.getIdForObject(value) != null))
            {
                // The PC is either already inserted, or inserted down to the level we need, or not inserted at all,
                // or the field is a PK and identity not attributed by the datastore

                // Object either already exists, or is not yet being inserted.
                id = api.getIdForObject(value);

                // Check if the PersistenceCapable exists in this datastore
                boolean requiresPersisting = false;
                if (ec.getApiAdapter().isDetached(value) && ownerSM != null)
                {
                    // Detached object so needs attaching
                    if (ownerSM.isInserting())
                    {
                        // Inserting other object, and this object is detached but if detached from this datastore
                        // we can just return the value now and attach later (in InsertRequest)
                        if (!ec.getNucleusContext().getPersistenceConfiguration().getBooleanProperty("datanucleus.attachSameDatastore"))
                        {
                            if (ec.getObjectFromCache(api.getIdForObject(value)) != null)
                            {
                                // Object is in cache so exists for this datastore, so no point checking
                            }
                            else
                            {
                                try
                                {
                                    Object obj = ec.findObject(api.getIdForObject(value), true, false,
                                        value.getClass().getName());
                                    if (obj != null)
                                    {
                                        // Make sure this object is not retained in cache etc
                                        ObjectProvider objSM = ec.findObjectProvider(obj);
                                        if (objSM != null)
                                        {
                                            ec.evictFromTransaction(objSM);
                                        }
                                        ec.removeObjectFromLevel1Cache(api.getIdForObject(value));
                                    }
                                }
                                catch (NucleusObjectNotFoundException onfe)
                                {
                                    // Object doesnt yet exist
                                    requiresPersisting = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        requiresPersisting = true;
                    }
                }
                else if (id == null)
                {
                    // Transient object, so we need to persist it
                    requiresPersisting = true;
                }
                else
                {
                    ExecutionContext pcEC = ec.getApiAdapter().getExecutionContext(value);
                    if (pcEC != null && ec != pcEC)
                    {
                        throw new NucleusUserException(LOCALISER.msg("041015"), id);
                    }
                }

                if (requiresPersisting)
                {
                    // PERSISTENCE-BY-REACHABILITY
                    // This PC object needs persisting (new or detached) to do the "set"
                    if (mmd != null && !mmd.isCascadePersist() && !ec.getApiAdapter().isDetached(value))
                    {
                        // Related PC object not persistent, but cant do cascade-persist so throw exception
                        if (NucleusLogger.PERSISTENCE.isDebugEnabled())
                        {
                            NucleusLogger.PERSISTENCE.debug(LOCALISER.msg("007006",
                                mmd.getFullFieldName()));
                        }
                        throw new ReachableObjectNotCascadedException(mmd.getFullFieldName(), value);
                    }

                    if (NucleusLogger.PERSISTENCE.isDebugEnabled())
                    {
                        NucleusLogger.PERSISTENCE.debug(LOCALISER.msg("007007",
                            mmd != null ? mmd.getFullFieldName() : null));
                    }

                    try
                    {
                        Object pcNew = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
                        if (hasDatastoreAttributedPrimaryKeyValues)
                        {
                            ec.flushInternal(false);
                        }
                        id = api.getIdForObject(pcNew);
                        if (ec.getApiAdapter().isDetached(value) && ownerSM != null)
                        {
                            // Update any detached reference to refer to the attached variant
                            ownerSM.replaceFieldMakeDirty(ownerFieldNumber, pcNew);
                            RelationType relationType = mmd.getRelationType(clr);
                            if (relationType == RelationType.MANY_TO_ONE_BI)
                            {
                                // TODO Update the container to refer to the attached object
                                if (NucleusLogger.PERSISTENCE.isInfoEnabled())
                                {
                                    NucleusLogger.PERSISTENCE.info("PCMapping.setObject : object " + ownerSM.getInternalObjectId() +
                                        " has field " + ownerFieldNumber + " that is 1-N bidirectional." +
                                        " Have just attached the N side so should really update the reference in the 1 side collection" +
                                        " to refer to this attached object. Not yet implemented");
                                }
                            }
                            else if (relationType == RelationType.ONE_TO_ONE_BI)
                            {
                                AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                                // TODO Cater for more than 1 related field
                                ObjectProvider relatedSM = ec.findObjectProvider(pcNew);
                                relatedSM.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), ownerSM.getObject());
                            }
                        }
                    }
                    catch (NotYetFlushedException e)
                    {
                        setObjectAsNull(ec, ps, param);
                        throw new NotYetFlushedException(value);
                    }
                }

                if (valueSM != null)
                {
                    valueSM.setStoringPC();
                }

                // If the field doesn't map to any datastore fields (e.g remote FK), omit the set process
                if (getNumberOfDatastoreMappings() > 0)
                {
                    if (id instanceof OID)
                    {
                        OID oid = (OID)id;
                        try
                        {
                            // Try as a Long
                            getDatastoreMapping(0).setObject(ps, param[0], oid.getKeyValue());
                        }
                        catch (Exception e)
                        {
                            // Must be a String
                            getDatastoreMapping(0).setObject(ps, param[0], oid.getKeyValue().toString());
                        }
                    }
                    else
                    {
                        boolean fieldsSet = false;
                        if (api.isSingleFieldIdentity(id) && javaTypeMappings.length > 1)
                        {
                            Object key = api.getTargetKeyForSingleFieldIdentity(id);
                            AbstractClassMetaData keyCmd = ec.getMetaDataManager().getMetaDataForClass(key.getClass(), clr);
                            if (keyCmd != null && keyCmd.getIdentityType() == IdentityType.NONDURABLE)
                            {
                                // Embedded ID - Make sure these are called starting at lowest first, in order
                                // We cannot just call OP.provideFields with all fields since that does last first
                                ObjectProvider keyOP = ec.findObjectProvider(key);
                                int[] fieldNums = keyCmd.getAllMemberPositions();
                                FieldManager fm = new AppIDObjectIdFieldManager(param, ec, ps, javaTypeMappings);
                                for (int i=0;i<fieldNums.length;i++)
                                {
                                    keyOP.provideFields(new int[] {fieldNums[i]}, fm);
                                }
                                fieldsSet = true;
                            }
                        }
View Full Code Here

        RelationType relationType = mmd.getRelationType(clr);
        if (pc != null)
        {
            if (relationType == RelationType.ONE_TO_ONE_BI)
            {
                ObjectProvider otherSM = sm.getExecutionContext().findObjectProvider(pc);
                AbstractMemberMetaData relatedMmd = mmd.getRelatedMemberMetaDataForObject(clr, sm.getObject(), pc);
                if (relatedMmd == null)
                {
                    // Fsck knows why
                    throw new NucleusUserException("You have a field " + mmd.getFullFieldName() + " that is 1-1 bidir yet cannot find the equivalent field at the other side. Why is that?");
                }
                Object relatedValue = otherSM.provideField(relatedMmd.getAbsoluteFieldNumber());
                if (relatedValue == null)
                {
                    // Managed Relations : Other side not set so update it in memory
                    if (NucleusLogger.PERSISTENCE.isDebugEnabled())
                    {
                        NucleusLogger.PERSISTENCE.debug(LOCALISER.msg("041018",
                            sm.getObjectAsPrintable(), mmd.getFullFieldName(),
                            StringUtils.toJVMIDString(pc), relatedMmd.getFullFieldName()));
                    }
                    otherSM.replaceField(relatedMmd.getAbsoluteFieldNumber(), sm.getObject());
                }
                else if (relatedValue != sm.getObject())
                {
                    // Managed Relations : Other side is inconsistent so throw exception
                    throw new NucleusUserException(
                        LOCALISER.msg("041020",
                            sm.getObjectAsPrintable(), mmd.getFullFieldName(),
                            StringUtils.toJVMIDString(pc),
                            StringUtils.toJVMIDString(relatedValue)));
                }
            }
            else if (relationType == RelationType.MANY_TO_ONE_BI && relatedMmds[0].hasCollection())
            {
                // TODO Make sure we have this PC in the collection at the other side
                ObjectProvider otherSM = sm.getExecutionContext().findObjectProvider(pc);
                if (otherSM != null)
                {
                    // Managed Relations : add to the collection on the other side
                    Collection relatedColl = (Collection)otherSM.provideField(relatedMmds[0].getAbsoluteFieldNumber());
                    if (relatedColl != null && !(relatedColl instanceof SCOCollection))
                    {
                        // TODO Make sure the collection is a wrapper
                        boolean contained = relatedColl.contains(sm.getObject());
                        if (!contained)
                        {
                            NucleusLogger.PERSISTENCE.info(
                                LOCALISER.msg("041022",
                                sm.getObjectAsPrintable(), mmd.getFullFieldName(),
                                StringUtils.toJVMIDString(pc), relatedMmds[0].getFullFieldName()));
                            // TODO Enable this. CUrrently causes issues with
                            // PMImplTest, InheritanceStrategyTest, TCK "inheritance1.conf"
                            /*relatedColl.add(sm.getObject());*/
                        }
                    }
                }
            }
            else if (relationType == RelationType.MANY_TO_ONE_UNI)
            {
                ObjectProvider otherSM = sm.getExecutionContext().findObjectProvider(pc);
                if (otherSM == null)
                {
                    // Related object is not yet persisted so persist it
                    Object other = sm.getExecutionContext().persistObjectInternal(pc, null, -1, ObjectProvider.PC);
                    otherSM = sm.getExecutionContext().findObjectProvider(other);
View Full Code Here

TOP

Related Classes of org.datanucleus.state.ObjectProvider

Copyright © 2018 www.massapicom. 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.