Package org.datanucleus.api

Examples of org.datanucleus.api.ApiAdapter


        {
            if (pcClass == null)
            {
                pcClass = ec.getClassLoaderResolver().classForName(cmd.getFullClassName());
            }
            ApiAdapter api = ec.getApiAdapter();
            int[] pkFieldNums = cmd.getPKMemberPositions();
            Object[] pkFieldValues = new Object[pkFieldNums.length];
            for (int i=0;i<pkFieldNums.length;i++)
            {
                AbstractMemberMetaData pkMmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNums[i]);
                if (pkMmd.getType() == int.class)
                {
                    pkFieldValues[i] = resultsFM.fetchIntField(pkFieldNums[i]);
                }
                else if (pkMmd.getType() == short.class)
                {
                    pkFieldValues[i] = resultsFM.fetchShortField(pkFieldNums[i]);
                }
                else if (pkMmd.getType() == long.class)
                {
                    pkFieldValues[i] = resultsFM.fetchLongField(pkFieldNums[i]);
                }
                else if (pkMmd.getType() == char.class)
                {
                    pkFieldValues[i] = resultsFM.fetchCharField(pkFieldNums[i]);
                }
                else if (pkMmd.getType() == boolean.class)
                {
                    pkFieldValues[i] = resultsFM.fetchBooleanField(pkFieldNums[i]);
                }
                else if (pkMmd.getType() == byte.class)
                {
                    pkFieldValues[i] = resultsFM.fetchByteField(pkFieldNums[i]);
                }
                else if (pkMmd.getType() == double.class)
                {
                    pkFieldValues[i] = resultsFM.fetchDoubleField(pkFieldNums[i]);
                }
                else if (pkMmd.getType() == float.class)
                {
                    pkFieldValues[i] = resultsFM.fetchFloatField(pkFieldNums[i]);
                }
                else if (pkMmd.getType() == String.class)
                {
                    pkFieldValues[i] = resultsFM.fetchStringField(pkFieldNums[i]);
                }
                else
                {
                    pkFieldValues[i] = resultsFM.fetchObjectField(pkFieldNums[i]);
                }
            }

            Class idClass = ec.getClassLoaderResolver().classForName(cmd.getObjectidClass());
            if (cmd.usesSingleFieldIdentityClass())
            {
                // Create SingleField identity with query key value
                Object id = api.getNewSingleFieldIdentity(idClass, pcClass, pkFieldValues[0]);
                if (inheritanceCheck)
                {
                    // Check if this identity exists in the cache(s)
                    if (ec.hasIdentityInCache(id))
                    {
                        return id;
                    }

                    // Check if this id for any known subclasses is in the cache to save searching
                    String[] subclasses = ec.getMetaDataManager().getSubclassesForClass(pcClass.getName(), true);
                    if (subclasses != null)
                    {
                        for (int i=0;i<subclasses.length;i++)
                        {
                            Object subid = api.getNewSingleFieldIdentity(idClass,
                                ec.getClassLoaderResolver().classForName(subclasses[i]),
                                api.getTargetKeyForSingleFieldIdentity(id));
                            if (ec.hasIdentityInCache(subid))
                            {
                                return subid;
                            }
                        }
                    }

                    // Check the inheritance with the store manager (may involve a trip to the datastore)
                    String className = ec.getStoreManager().getClassNameForObjectID(id, ec.getClassLoaderResolver(), ec);
                    return api.getNewSingleFieldIdentity(idClass,
                        ec.getClassLoaderResolver().classForName(className), pkFieldValues[0]);
                }
                return id;
            }
            else
            {
                // Create user-defined PK class with PK field values
                try
                {
                    // All user-defined PK classes have a default constructor
                    Object id = idClass.newInstance();

                    for (int i=0;i<pkFieldNums.length;i++)
                    {
                        AbstractMemberMetaData pkMmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNums[i]);
                        Object value = pkFieldValues[i];
                        if (api.isPersistable(value))
                        {
                            // CompoundIdentity, so use id
                            value = api.getIdForObject(value);
                        }
                        if (pkMmd instanceof FieldMetaData)
                        {
                            // Set the field directly (assumed to be public)
                            Field pkField = ClassUtils.getFieldForClass(idClass, pkMmd.getName());
View Full Code Here


        if (!StringUtils.isWhitespace(value.type) && value.type.indexOf(',') > 0)
        {
            throw new InvalidMetaDataException(LOCALISER, "044144", mmd.getName(), mmd.getClassName());
        }

        ApiAdapter api = mmgr.getApiAdapter();

        // Make sure the type in "key", "value" is set
        key.populate(((AbstractMemberMetaData)parent).getAbstractClassMetaData().getPackageName(),
            clr, primary, mmgr);
        value.populate(((AbstractMemberMetaData)parent).getAbstractClassMetaData().getPackageName(),
            clr, primary, mmgr);

        // Check the field type and see if it is castable to a Map
        Class field_type = getMemberMetaData().getType();
        if (!java.util.Map.class.isAssignableFrom(field_type))
        {
            throw new InvalidMetaDataException(LOCALISER, "044145", getFieldName(),
                getMemberMetaData().getClassName(false));
        }

        if (java.util.Properties.class.isAssignableFrom(field_type))
        {
            // Properties defaults to <String, String>
            if (key.type == null)
            {
                key.type = String.class.getName();
            }
            if (value.type == null)
            {
                value.type = String.class.getName();
            }
        }

        // "key-type"
        if (key.type == null)
        {
            throw new InvalidMetaDataException(LOCALISER, "044146", getFieldName(),
                getMemberMetaData().getClassName(false));
        }

        // Check that the key type exists
        Class keyTypeClass = null;
        try
        {
            keyTypeClass = clr.classForName(key.type, primary);
        }
        catch (ClassNotResolvedException cnre)
        {
            try
            {
                // Maybe the user specified a java.lang class without fully-qualifying it
                // This is beyond the scope of the JDO spec which expects java.lang cases to be fully-qualified
                keyTypeClass = clr.classForName(ClassUtils.getJavaLangClassForType(key.type), primary);
            }
            catch (ClassNotResolvedException cnre2)
            {
                throw new InvalidMetaDataException(LOCALISER, "044147", getFieldName(),
                    getMemberMetaData().getClassName(false), key.type);
            }
        }

        if (!keyTypeClass.getName().equals(key.type))
        {
            // The value-type has been resolved from what was specified in the MetaData - update to the fully-qualified name
            NucleusLogger.METADATA.info(LOCALISER.msg("044148", getFieldName(),
                getMemberMetaData().getClassName(false), key.type, keyTypeClass.getName()));
            key.type = keyTypeClass.getName();
        }

        // "embedded-key"
        if (key.embedded == null)
        {
            // Assign default for "embedded-key" based on 18.13.2 of JDO 2 spec
            if (mmgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(keyTypeClass))
            {
                key.embedded = Boolean.TRUE;
            }
            else if (api.isPersistable(keyTypeClass) ||
                Object.class.isAssignableFrom(keyTypeClass) ||
                keyTypeClass.isInterface())
            {
                key.embedded = Boolean.FALSE;
            }
            else
            {
                key.embedded = Boolean.TRUE;
            }
        }
        if (Boolean.FALSE.equals(key.embedded))
        {
            // If the user has set a non-PC/non-Interface as not embedded, correct it since not supported.
            // Note : this fails when using in the enhancer since not yet PC
            if (!api.isPersistable(keyTypeClass) && !keyTypeClass.isInterface() &&
                keyTypeClass != java.lang.Object.class)
            {
                key.embedded = Boolean.TRUE;
            }
        }
        KeyMetaData keymd = ((AbstractMemberMetaData)parent).getKeyMetaData();
        if (keymd != null && keymd.getEmbeddedMetaData() != null)
        {
            // If the user has specified <embedded>, set to true
            key.embedded = Boolean.TRUE;
        }

        // "value-type"
        if (value.type == null)
        {
            throw new InvalidMetaDataException(LOCALISER, "044149",  getFieldName(),
                getMemberMetaData().getClassName(false));
        }

        // Check that the value-type exists
        Class valueTypeClass = null;
        try
        {
            valueTypeClass = clr.classForName(value.type);
        }
        catch (ClassNotResolvedException cnre)
        {
            try
            {
                // Maybe the user specified a java.lang class without fully-qualifying it
                // This is beyond the scope of the JDO spec which expects java.lang cases to be fully-qualified
                valueTypeClass = clr.classForName(ClassUtils.getJavaLangClassForType(value.type));
            }
            catch (ClassNotResolvedException cnre2)
            {
                throw new InvalidMetaDataException(LOCALISER, "044150", getFieldName(),
                    getMemberMetaData().getClassName(false), value.type);
            }
        }

        if (!valueTypeClass.getName().equals(value.type))
        {
            // The value-type has been resolved from what was specified in the MetaData - update to the fully-qualified name
            NucleusLogger.METADATA.info(LOCALISER.msg("044151", getFieldName(),
                getMemberMetaData().getClassName(false), value.type, valueTypeClass.getName()));
            value.type = valueTypeClass.getName();
        }

        // "embedded-value"
        if (value.embedded == null)
        {
            // Assign default for "embedded-value" based on 18.13.2 of JDO 2 spec
            if (mmgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(valueTypeClass))
            {
                value.embedded = Boolean.TRUE;
            }
            else if (api.isPersistable(valueTypeClass) ||
                Object.class.isAssignableFrom(valueTypeClass) ||
                valueTypeClass.isInterface())
            {
                value.embedded = Boolean.FALSE;
            }
            else
            {
                value.embedded = Boolean.TRUE;
            }
        }
        if (value.embedded == Boolean.FALSE)
        {
            // If the user has set a non-PC/non-Interface as not embedded, correct it since not supported.
            // Note : this fails when using in the enhancer since not yet PC
            if (!api.isPersistable(valueTypeClass) && !valueTypeClass.isInterface() &&
                valueTypeClass != java.lang.Object.class)
            {
                value.embedded = Boolean.TRUE;
            }
        }
View Full Code Here

        }

        if (mmgr != null)
        {
            // Set defaults for cascading when not yet set
            ApiAdapter apiAdapter = mmgr.getNucleusContext().getApiAdapter();
            if (cascadePersist == null)
            {
                cascadePersist = apiAdapter.getDefaultCascadePersistForField();
            }
            if (cascadeUpdate == null)
            {
                cascadeUpdate = apiAdapter.getDefaultCascadeUpdateForField();
            }
            if (cascadeDelete == null)
            {
                cascadeDelete = apiAdapter.getDefaultCascadeDeleteForField();
            }
            if (cascadeRefresh == null)
            {
                cascadeRefresh = apiAdapter.getDefaultCascadeRefreshForField();
            }
        }

        if (field == null && method == null)
        {
View Full Code Here

        if (pc == null)
        {
            return null;
        }

        ApiAdapter api = sm.getExecutionContext().getApiAdapter();
        if (!api.isPersistable(pc))
        {
            return pc;
        }

        if (!api.isDetached(pc))
        {
            if (api.isPersistent(pc))
            {
                // Persistent object that is not yet detached so detach it
                if (copy)
                {
                    // Detach a copy and return the copy
View Full Code Here

        {
            return null;
        }

        ClassLoaderResolver clr = sm.getExecutionContext().getClassLoaderResolver();
        ApiAdapter api = sm.getExecutionContext().getApiAdapter();
        AbstractMemberMetaData mmd =
            sm.getClassMetaData().getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber);
        int relationType = mmd.getRelationType(clr);

        switch (relationType)
        {
            case Relation.ONE_TO_ONE_BI:
            case Relation.ONE_TO_ONE_UNI:
            case Relation.MANY_TO_ONE_BI:
                if (api.isPersistable(value))
                {
                    // Process PC fields
                    return processPersistable(value);
                }
                break;

            case Relation.ONE_TO_MANY_BI:
            case Relation.ONE_TO_MANY_UNI:
            case Relation.MANY_TO_MANY_BI:
                if (mmd.hasCollection() || mmd.hasMap())
                {
                    // Process all elements of Collections/Maps that are PC
                    if (copy)
                    {
                        if (!(value instanceof SCO))
                        {
                            // Replace with SCO so we can work with it
                            value = sm.wrapSCOField(fieldNumber, value, false, false, true);
                        }
                        if (!(value instanceof SCO) && mmd.isSerialized())
                        {
                            // Collection/Map type not supported, but being serialised
                            if (mmd.hasCollection())
                            {
                                if (mmd.getCollection().elementIsPersistent())
                                {
                                    throw new NucleusUserException("Unable to detach " + mmd.getFullFieldName() +
                                        " since is of an unsupported Collection type with persistent elements");
                                }
                                return value;
                            }
                            else if (mmd.hasMap())
                            {
                                if (mmd.getMap().keyIsPersistent() || mmd.getMap().valueIsPersistent())
                                {
                                    throw new NucleusUserException("Unable to detach " + mmd.getFullFieldName() +
                                        " since is of an unsupported Map type with persistent keys/values");
                                }
                                return value;
                            }
                        }
                        return ((SCO)value).detachCopy(state);
                    }
                    else
                    {
                        if (!(value instanceof SCO))
                        {
                            // Replace with SCO so we can work with it
                            value = sm.wrapSCOField(fieldNumber, value, false, false, true);
                        }
                        SCO sco = (SCO)value;

                        if (sco instanceof Collection)
                        {
                            // Detach all PC elements of the collection
                            SCOUtils.detachForCollection(sm, ((Collection)sco).toArray(), state);
                            sco.unsetOwner();
                        }
                        else if (sco instanceof Map)
                        {
                            // Detach all PC keys/values of the map
                            SCOUtils.detachForMap(sm, ((Map)sco).entrySet(), state);
                            sco.unsetOwner();
                        }

                        if (SCOUtils.detachAsWrapped(sm))
                        {
                            return sco;
                        }
                        else
                        {
                            return sm.unwrapSCOField(fieldNumber, value, true);
                        }
                    }
                }
                else if (mmd.hasArray())
                {
                    // Process object array
                    if (!api.isPersistable(mmd.getType().getComponentType()))
                    {
                        // Array element type is not persistable so just return
                        return value;
                    }
View Full Code Here

    {
        // check if the object here is PC and is in the detached cache anyway
        SingleValueFieldManager sfv = new SingleValueFieldManager();
        sm.provideFields(new int[]{fieldNumber}, sfv);
        Object value = sfv.fetchObjectField(fieldNumber);
        ApiAdapter api = sm.getExecutionContext().getApiAdapter();

        if (api.isPersistable(value))
        {
            if (copy)
            {
                DetachState.Entry entry = ((DetachState)state).getDetachedCopyEntry(value);
                if (entry != null)
View Full Code Here

    private void setObjectAsValue(ExecutionContext ec, Object ps, int[] param, Object value, ObjectProvider ownerSM,
            int ownerFieldNumber)
    {
        Object id;

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

        ObjectProvider valueSM = ec.findObjectProvider(value);

        try
        {
            ClassLoaderResolver clr = ec.getClassLoaderResolver();
            MappedStoreManager storeMgr = (MappedStoreManager)ec.getStoreManager();

            // 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.removeObjectFromCache(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);
                            int relationType = mmd.getRelationType(clr);
View Full Code Here

        // Datastore Identity - retrieve the OID for the class.
        // Note that this is a temporary OID that is simply formed from the type of base class in the relationship
        // and the id stored in the FK. The real OID for the object may be of a different class.
        // For that reason we get the object by checking the inheritance (final param in getObjectById())
        Object oid = super.getObject(ec, rs, param);
        ApiAdapter api = ec.getApiAdapter();
        if (api.isPersistable(oid)) //why check this?
        {
          return oid;
        }
        return oid == null ? null : ec.findObject(oid, false, true, null);
    }
View Full Code Here

        {
            removeInternal(sm, key);
        }

        MapMetaData mapmd = ownerMemberMetaData.getMap();
        ApiAdapter api = ec.getApiAdapter();
        if (mapmd.isDependentKey() && !mapmd.isEmbeddedKey() && api.isPersistable(key))
        {
            // Delete the key if it is dependent
            ec.deleteObjectInternal(key);
        }

        if (mapmd.isDependentValue() && !mapmd.isEmbeddedValue() && api.isPersistable(oldValue))
        {
            if (!containsValue(sm, oldValue))
            {
                // Delete the value if it is dependent and is not keyed by another key
                ec.deleteObjectInternal(oldValue);
View Full Code Here

        Collection dependentElements = null;
        if (ownerMemberMetaData.getMap().isDependentKey() || ownerMemberMetaData.getMap().isDependentValue())
        {
            // Retain the PC dependent keys/values that need deleting after clearing
            dependentElements = new HashSet();
            ApiAdapter api = ownerSM.getExecutionContext().getApiAdapter();
            Iterator iter = entrySetStore().iterator(ownerSM);
            while (iter.hasNext())
            {
                Map.Entry entry = (Map.Entry)iter.next();
                MapMetaData mapmd = ownerMemberMetaData.getMap();
                if (api.isPersistable(entry.getKey()) && mapmd.isDependentKey() && !mapmd.isEmbeddedKey())
                {
                    dependentElements.add(entry.getKey());
                }
                if (api.isPersistable(entry.getValue()) && mapmd.isDependentValue() && !mapmd.isEmbeddedValue())
                {
                    dependentElements.add(entry.getValue());
                }
            }
        }
View Full Code Here

TOP

Related Classes of org.datanucleus.api.ApiAdapter

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.