Adds to the EDBObject special entries which mark that a model is referring to other models through
OpenEngSBForeignKey annotations
427144
private void fillEDBObjectWithEngineeringObjectInformation(EDBObject object, OpenEngSBModel model)
        throws IllegalAccessException {
        if (!new AdvancedModelWrapper(model).isEngineeringObject()) {
            return;
        }
        for (Field field : model.getClass().getDeclaredFields()) {
            OpenEngSBForeignKey annotation = field.getAnnotation(OpenEngSBForeignKey.class);
            if (annotation == null) {
                continue;
            }
            String value = (String) FieldUtils.readField(field, model, true);
            if (value == null) {
                continue;
            }
            value = String.format("%s/%s", ContextHolder.get().getCurrentContextId(), value);
            String key = getEOReferenceStringFromAnnotation(annotation);
            object.put(key, new EDBObjectEntry(key, value, String.class));
        }
    }
720368
def add_to_dict(self, an_object, extras=None):
        
        if an_object.id is None:
            raise ModelError("id must be set on object before adding to output.")
        if hasattr(an_object, "base_type"):
            mtype = an_object.base_type
        elif hasattr(an_object, "type"):
            if an_object.type in standard_types:
                mtype = an_object.type
            else:
                mtype = "custom_type"
        else:
            raise ModelError("Object does not have attribute 'base_type' or 'type', cannot add to output.")
        if mtype not in self.unordered_models:  # Catch any custom objects
            self.unordered_models[mtype] = OrderedDict()

        if hasattr(an_object, "add_to_dict"):
            an_object.add_to_dict(self.unordered_models)

        elif hasattr(an_object, "to_dict"):
            self.unordered_models[mtype][an_object.unique_hash] = an_object.to_dict(compression=self.compression)
        else:
            raise ModelError("Object does not have method 'to_dict', cannot add to output.")
1218077
private void ensureReferencedFKs(ModelDef modelDef, CollectionDescriptorDef collDef) throws ConstraintException
    {
        String             elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);
        ClassDescriptorDef elementClassDef  = modelDef.getClass(elementClassName);
        String             fkFieldNames     = collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY);
        ArrayList          missingFields    = new ArrayList();
        SequencedHashMap   fkFields         = new SequencedHashMap();

        // first we gather all field names
        for (CommaListIterator it = new CommaListIterator(fkFieldNames); it.hasNext();)
        {
            String             fieldName = (String)it.next();
            FieldDescriptorDef fieldDef  = elementClassDef.getField(fieldName);

            if (fieldDef == null)
            {
                missingFields.add(fieldName);
            }
            fkFields.put(fieldName, fieldDef);
        }

        // next we traverse all sub types and gather fields as we go
        for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext() && !missingFields.isEmpty();)
        {
            ClassDescriptorDef subTypeDef = (ClassDescriptorDef)it.next();

            for (int idx = 0; idx < missingFields.size();)
            {
                FieldDescriptorDef fieldDef = subTypeDef.getField((String)missingFields.get(idx));

                if (fieldDef != null)
                {
                    fkFields.put(fieldDef.getName(), fieldDef);
                    missingFields.remove(idx);
                }
                else
                {
                    idx++;
                }
            }
        }
        if (!missingFields.isEmpty())
        {
            throw new ConstraintException("Cannot find field "+missingFields.get(0).toString()+" in the hierarchy with root type "+
                                          elementClassDef.getName()+" which is used as foreignkey in collection "+
                                          collDef.getName()+" in "+collDef.getOwner().getName());
        }

        // copy the found fields into the element class
        ensureFields(elementClassDef, fkFields.values());
    }
1206012
def add_extra_model_fields(sender, **kwargs):
    
    model_key = sender._meta.app_label, sender._meta.model_name
    for field_name, field in fields.get(model_key, {}):
        field.contribute_to_class(sender, field_name)
1030873
private ModelDescription getDescriptionFromObject(EDBObject obj) {
        String modelName = obj.getString(EDBConstants.MODEL_TYPE);
        String modelVersion = obj.getString(EDBConstants.MODEL_TYPE_VERSION);
        if (modelName == null || modelVersion == null) {
            throw new IllegalArgumentException("The object " + obj.getOID() + " contains no model information");
        }
        return new ModelDescription(modelName, modelVersion);
    }
894066
public static void populateCompoundKey(DBObject dbObj, EntityMetadata m, MetamodelImpl metaModel, Object id)
    {
        EmbeddableType compoundKey = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());
        // Iterator<Attribute> iter = compoundKey.getAttributes().iterator();
        BasicDBObject compoundKeyObj = new BasicDBObject();

        compoundKeyObj = getCompoundKeyColumns(m, id, compoundKey, metaModel);

        dbObj.put("_id", compoundKeyObj);
    }
955167
def __AddAdditionalProperties(self, message, schema, properties):
        """"""
        additional_properties_info = schema['additionalProperties']
        entries_type_name = self.__AddAdditionalPropertyType(
            message.name, additional_properties_info)
        description = util.CleanDescription(
            additional_properties_info.get('description'))
        if description is None:
            description = 'Additional properties of type %s' % message.name
        attrs = {
            'items': {
                '$ref': entries_type_name,
            },
            'description': description,
            'type': 'array',
        }
        field_name = 'additionalProperties'
        message.fields.append(self.__FieldDescriptorFromProperties(
            field_name, len(properties) + 1, attrs))
        self.__AddImport('from %s import encoding' % self.__base_files_package)
        message.decorators.append(
            'encoding.MapUnrecognizedFields(%r)' % field_name)
944414
def obj_ref(obj):
    """"""
    from indico_livesync.models.queue import EntryType
    if isinstance(obj, Category):
        ref = {'type': EntryType.category, 'category_id': obj.id}
    elif isinstance(obj, Event):
        ref = {'type': EntryType.event, 'event_id': obj.id}
    elif isinstance(obj, Session):
        ref = {'type': EntryType.session, 'session_id': obj.id}
    elif isinstance(obj, Contribution):
        ref = {'type': EntryType.contribution, 'contrib_id': obj.id}
    elif isinstance(obj, SubContribution):
        ref = {'type': EntryType.subcontribution, 'subcontrib_id': obj.id}
    else:
        raise ValueError('Unexpected object: {}'.format(obj.__class__.__name__))
    return ImmutableDict(ref)
1067479
public List<EDBObject> convertModelToEDBObject(Object model, ConnectorInformation info) {
        if (!OpenEngSBModel.class.isAssignableFrom(model.getClass())) {
            throw new IllegalArgumentException("This function need to get a model passed");
        }
        List<EDBObject> objects = new ArrayList<>();
        if (model != null) {
            convertSubModel((OpenEngSBModel) model, objects, info);
        }
        return objects;
    }
836902
private Object convertEDBObjectToUncheckedModel(Class<?> model, EDBObject object) {
        if (!checkEDBObjectModelType(object, model)) {
            return null;
        }
        filterEngineeringObjectInformation(object, model);
        List<OpenEngSBModelEntry> entries = new ArrayList<>();
        for (PropertyDescriptor propertyDescriptor : getPropertyDescriptorsForClass(model)) {
            if (propertyDescriptor.getWriteMethod() == null
                    || propertyDescriptor.getName().equals(ModelUtils.MODEL_TAIL_FIELD_NAME)) {
                continue;
            }
            Object value = getValueForProperty(propertyDescriptor, object);
            Class<?> propertyClass = propertyDescriptor.getPropertyType();
            if (propertyClass.isPrimitive()) {
                entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, ClassUtils
                    .primitiveToWrapper(propertyClass)));
            } else {
                entries.add(new OpenEngSBModelEntry(propertyDescriptor.getName(), value, propertyClass));
            }
        }

        for (Map.Entry<String, EDBObjectEntry> objectEntry : object.entrySet()) {
            EDBObjectEntry entry = objectEntry.getValue();
            Class<?> entryType;
            try {
                entryType = model.getClassLoader().loadClass(entry.getType());
                entries.add(new OpenEngSBModelEntry(entry.getKey(), entry.getValue(), entryType));
            } catch (ClassNotFoundException e) {
                LOGGER.error("Unable to load class {} of the model tail", entry.getType());
            }
        }
        return ModelUtils.createModel(model, entries);
    }
1221981
public List<EDBObject> getModelsReferringToThisModel(EngineeringDatabaseService edbService) {
        return edbService.query(QueryRequest.query(
            EDBConverter.REFERENCE_PREFIX + "%", getCompleteModelOID()));
    }
797610
private Object createModelOfEDBObject(EDBObject object, Map<ModelDescription, Class<?>> cache) {
        try {
            ModelDescription description = getDescriptionFromObject(object);
            Class<?> modelClass;
            if (cache.containsKey(description)) {
                modelClass = cache.get(description);
            } else {
                modelClass = modelRegistry.loadModel(description);
                cache.put(description, modelClass);
            }
            return edbConverter.convertEDBObjectToModel(modelClass, object);
        } catch (IllegalArgumentException | ClassNotFoundException e) {
            LOGGER.warn("Unable to create model of the object {}", object.getOID(), e);
            return null;
        }
    }
105545
def attach_foreignkey(objects, field, related=[], database=None):
    

    if not objects:
        return

    if database is None:
        database = list(objects)[0]._state.db

    is_foreignkey = isinstance(field, SingleRelatedObjectDescriptor)

    if not is_foreignkey:
        field = field.field
        accessor = '_%s_cache' % field.name
        model = field.rel.to
        lookup = 'pk'
        column = field.column
        key = lookup
    else:
        accessor = field.cache_name
        field = field.related.field
        model = field.model
        lookup = field.name
        column = 'pk'
        key = field.column

    objects = [o for o in objects if (related or getattr(o, accessor, False) is False)]

    if not objects:
        return

    # Ensure values are unique, do not contain already present values, and are not missing
    # values specified in select_related
    values = distinct(filter(None, (getattr(o, column) for o in objects)))
    if values:
        qs = model.objects.filter(**{'%s__in' % lookup: values})
        if database:
            qs = qs.using(database)
        if related:
            qs = qs.select_related(*related)

        queryset = queryset_to_dict(qs, key=key)
    else:
        queryset = {}

    for o in objects:
        setattr(o, accessor, queryset.get(getattr(o, column)))
1085797
def add_annotation(self, entity, annotation, value):
        '''  '''
        url = self.base_path + 'term/add-annotation'
        data = {'tid': entity['id'],
                'annotation_tid': annotation['id'],
                'value': value,
                'term_version': entity['version'],
                'annotation_term_version': annotation['version']}
        return self.post(url, data)
57370
def register_model(cls, model):
        

        rest_name = model.rest_name
        resource_name = model.resource_name

        if rest_name not in cls._model_rest_name_registry:
            cls._model_rest_name_registry[rest_name] = [model]
            cls._model_resource_name_registry[resource_name] = [model]

        elif model not in cls._model_rest_name_registry[rest_name]:
            cls._model_rest_name_registry[rest_name].append(model)
            cls._model_resource_name_registry[resource_name].append(model)
911292
public void addCache(ModelKey modelKey, Object model) {
		if ((modelKey == null) || (modelKey.getDataKey() == null))
			return;
		String modelClassName = null;
		try {
			if (modelKey.getModelClass() == null) {
				ModelMapping modelMapping = this.modelFactory.getModelMapping(modelKey.getFormName());
				modelClassName = modelMapping.getClassName();
			} else
				modelClassName = modelKey.getModelClass().getName();
			if (ModelUtil.isModel(model.getClass()))
				modelCacheManager.saveCache(modelKey.getDataKey(), modelClassName, model);
			else
				Debug.logError("addCache error:" + model.getClass() + " not ModelIF or @Model", module);
		} catch (Exception e) {
			Debug.logError("addCache error:" + e, module);
		}

	}
1197114
private void getCompositeIdEmbeddables(EmbeddableType embeddable, List compositeEmbeddables, MetamodelImpl metaModel)
    {
        compositeEmbeddables.add(embeddable.getJavaType().getSimpleName());

        for (Object column : embeddable.getAttributes())
        {

            Attribute columnAttribute = (Attribute) column;
            Field f = (Field) columnAttribute.getJavaMember();

            if (columnAttribute.getJavaType().isAnnotationPresent(Embeddable.class))
            {
                getCompositeIdEmbeddables(metaModel.embeddable(columnAttribute.getJavaType()), compositeEmbeddables,
                        metaModel);
            }
        }
    }