/*! initialize inner state by parsing configuration parameters

@param id
name of id field
@param fields
name of data field(s)
@param extra
name of extra field(s)
@param relation
name of relation field
519674
public function init($id,$fields,$extra,$relation){
		$this->id	= $this->parse($id,false);
		$this->text = $this->parse($fields,true);
		$this->data	= array_merge($this->text,$this->parse($extra,true));
		$this->relation_id = $this->parse($relation,false);
	}
995274
private void onRelationalAttributes(List<RelationHolder> rlHolders, Row row, Table schemaTable)
    {
        // Iterate over relations
        if (rlHolders != null && !rlHolders.isEmpty())
        {
            for (RelationHolder rh : rlHolders)
            {
                String relationName = rh.getRelationName();
                Object valueObj = rh.getRelationValue();

                if (!StringUtils.isEmpty(relationName) && valueObj != null)
                {
                    if (valueObj != null)
                    {
                        NoSqlDBUtils.add(schemaTable.getField(relationName), row, valueObj, relationName);
                        KunderaCoreUtils.printQuery(
                                "Add relation: relation name:" + relationName + "relation value:" + valueObj,
                                showQuery);
                    }
                }
            }
        }
    }
685815
public void addState(final String id, final Collection<Attribute> attributes) {
    this.stateMap.put(id, attributes);
  }
1083292
protected void initAdditionalInfo(CmsListInfoBean infoBean) {

        // create the state info
        CmsResourceState state = infoBean.getResourceState();
        if (state != null) {
            String stateKey = Messages.get().key(Messages.GUI_RESOURCE_STATE_0);
            String stateValue = CmsResourceStateUtil.getStateName(state);
            String stateStyle = CmsResourceStateUtil.getStateStyle(state);
            m_additionalInfo.add(new AdditionalInfoItem(new CmsAdditionalInfoBean(stateKey, stateValue, stateStyle)));
            ensureOpenCloseAdditionalInfo();
        }

        // set the additional info
        if (infoBean.hasAdditionalInfo()) {
            ensureOpenCloseAdditionalInfo();
            for (CmsAdditionalInfoBean additionalInfo : infoBean.getAdditionalInfo()) {
                m_additionalInfo.add(new AdditionalInfoItem(additionalInfo));
            }
        }
    }
150298
public void init(BaseField field, boolean bChangeDataOnRefresh)
    {
        super.init(field);
        m_objOriginalData = null;
        m_bAlwaysEnabled = false;
        m_bChangeDataOnRefresh = bChangeDataOnRefresh;
        this.setRespondsToMode(DBConstants.SCREEN_MOVE, false);
    }
580804
public void setRelationalDatabases(java.util.Collection<RelationalDatabase> relationalDatabases) {
        if (relationalDatabases == null) {
            this.relationalDatabases = null;
            return;
        }

        this.relationalDatabases = new java.util.ArrayList<RelationalDatabase>(relationalDatabases);
    }
634737
public function assignChild ($relationIdentifier, $id, $childId)
		{
			$relation = $this->getRelation($relationIdentifier);

			if (!$relation) {
				throw new RelationException('Invalid relation `' . $relationIdentifier);
			}

			if ($relation instanceof OneToMany) {
				$this->database->createQuery()
					->update()
					->table($relation->getRelatedTable())
					->set(
						array(
							$relation->getRelatedKey() => $id,
						)
					)
					->whereEqual($relation->getKey(), $childId)
					->execute();
			} else if ($relation instanceof ManyToMany) {
				if (! $this->getChild($relationIdentifier, $id, $childId)) {
					$this->database->createQuery()
						->insert()
						->into($relation->getRelationalTable())
						->set(
							array(
								$relation->getKey()         => $id,
								$relation->getRelatedKey()  => $childId,
							)
						)
						->execute();
				}
			} else {
				throw new RelationException('Invalid relation type `' . gettype($relation) . '`');
			}
		}
439668
def init(req, model):
    

    fields = model.all_fields
    rels = model.relationships
    params = []

    for key, val in req.params.items():
        try:
            field, oper = _parse_param(key)
        except (TypeError, ValueError):
            continue

        try:
            local_field, foreign_filter = field.split('/')
            field_type = getattr(model, local_field)

            foreign_field = field_type.field
            foreign_rtype = field_type.rtype

            if hasattr(field_type, 'local_field'):
                local_field = field_type.local_field

            param = FilterRel(foreign_field, foreign_filter, foreign_rtype,
                              local_field, field, oper, val)
        except AttributeError:
            raise InvalidQueryParams(**{
                'detail': 'The filter query param "%s" specified a filter '
                          'containing a "." indicating a relationship filter '
                          'but a relationship by that name does not exist '
                          'on the requested resource.' % key,
                'links': LINK,
                'parameter': PARAM,
            })
        except ValueError:
            param = Filter(field, oper, val)

        _validate_param(param)
        _validate_rel(param, rels)
        _validate_field(param, fields)
        params.append(param)

    return params
1201209
@Override
    public void init(Driver d, Properties properties) {
        // Cookies to store to session
        this.storeCookiesInSession = Parameters.STORE_COOKIES_IN_SESSION.getValue(properties);
        // Cookies to discard
        this.discardCookies = Parameters.DISCARD_COOKIES.getValue(properties);

        // Verify configuration
        if (this.storeCookiesInSession.contains("*") && this.storeCookiesInSession.size() > 1) {
            throw new ConfigurationException("storeCookiesInSession must be a list of cookie names OR *");
        }
        if (this.discardCookies.contains("*") && this.discardCookies.size() > 1) {
            throw new ConfigurationException("discardCookies must be a list of cookie names OR *");
        }
        if (this.storeCookiesInSession.contains("*") && this.discardCookies.contains("*")) {
            throw new ConfigurationException(
                    "cannot use * for storeCookiesInSession AND discardCookies at the same time");
        }
    }
724298
public function setRelation($contentType, $id)
    {
        if (empty($this->relation[$contentType]) || !in_array($id, $this->relation[$contentType], false)) {
            $this->relation[$contentType][] = $id;
        }
    }
798382
private void addRelationIntoMetadata(Class<?> entityClass, Field relationField, EntityMetadata metadata)
    {
        RelationMetadataProcessor relProcessor = null;
        try
        {
            relProcessor = RelationMetadataProcessorFactory
                    .getRelationMetadataProcessor(relationField, kunderaMetadata);

            this.factory.validate(relationField, new RelationAttributeRule());

            relProcessor = RelationMetadataProcessorFactory
                    .getRelationMetadataProcessor(relationField, kunderaMetadata);

            if (relProcessor != null)
            {
                relProcessor.addRelationIntoMetadata(relationField, metadata);
            }

        }
        catch (PersistenceException pe)
        {
            throw new MetamodelLoaderException("Error with relationship in @Entity(" + entityClass + "."
                    + relationField.getName() + "), reason: " + pe);
        }

    }
1319328
@Override
	public void addExtraState(EntityEntryExtraState extraState) {
		if ( next == null ) {
			next = extraState;
		}
		else {
			next.addExtraState( extraState );
		}
	}
886571
public void initialize() throws SQLException {
		if (initialized) {
			// just skip it if already initialized
			return;
		}

		if (connectionSource == null) {
			throw new IllegalStateException("connectionSource was never set on " + getClass().getSimpleName());
		}

		databaseType = connectionSource.getDatabaseType();
		if (databaseType == null) {
			throw new IllegalStateException(
					"connectionSource is getting a null DatabaseType in " + getClass().getSimpleName());
		}
		if (tableConfig == null) {
			tableInfo = new TableInfo<T, ID>(databaseType, dataClass);
		} else {
			tableConfig.extractFieldTypes(databaseType);
			tableInfo = new TableInfo<T, ID>(databaseType, tableConfig);
		}
		statementExecutor = new StatementExecutor<T, ID>(databaseType, tableInfo, this);

		/*
		 * This is a bit complex. Initially, when we were configuring the field types, external DAO information would be
		 * configured for auto-refresh, foreign BaseDaoEnabled classes, and foreign-collections. This would cause the
		 * system to go recursive and for class loops, a stack overflow.
		 * 
		 * Then we fixed this by putting a level counter in the FieldType constructor that would stop the configurations
		 * when we reach some recursion level. But this created some bad problems because we were using the DaoManager
		 * to cache the created DAOs that had been constructed already limited by the level.
		 * 
		 * What we do now is have a 2 phase initialization. The constructor initializes most of the fields but then we
		 * go back and call FieldType.configDaoInformation() after we are done. So for every DAO that is initialized
		 * here, we have to see if it is the top DAO. If not we save it for dao configuration later.
		 */
		List<BaseDaoImpl<?, ?>> daoConfigList = daoConfigLevelLocal.get();
		daoConfigList.add(this);
		if (daoConfigList.size() > 1) {
			// if we have recursed then just save the dao for later configuration
			return;
		}

		try {
			/*
			 * WARNING: We do _not_ use an iterator here because we may be adding to the list as we process it and we'll
			 * get exceptions otherwise. This is an ArrayList so the get(i) should be efficient.
			 * 
			 * Also, do _not_ get a copy of daoConfigLevel.doArray because that array may be replaced by another, larger
			 * one during the recursion.
			 */
			for (int i = 0; i < daoConfigList.size(); i++) {
				BaseDaoImpl<?, ?> dao = daoConfigList.get(i);

				/*
				 * Here's another complex bit. The first DAO that is being constructed as part of a DAO chain is not yet
				 * in the DaoManager cache. If we continue onward we might come back around and try to configure this
				 * DAO again. Forcing it into the cache here makes sure it won't be configured twice. This will cause it
				 * to be stuck in twice when it returns out to the DaoManager but that's a small price to pay. This also
				 * applies to self-referencing classes.
				 */
				DaoManager.registerDao(connectionSource, dao);

				try {
					// config our fields which may go recursive
					for (FieldType fieldType : dao.getTableInfo().getFieldTypes()) {
						fieldType.configDaoInformation(connectionSource, dao.getDataClass());
					}
				} catch (SQLException e) {
					// unregister the DAO we just pre-registered
					DaoManager.unregisterDao(connectionSource, dao);
					throw e;
				}

				// it's now been fully initialized
				dao.initialized = true;
			}
		} finally {
			// if we throw we want to clear our class hierarchy here
			daoConfigList.clear();
			daoConfigLevelLocal.remove();
		}
	}
1159899
private JSONArray mapRelations(String oid) {
		// We want our parsed data for reading
		JsonSimple formData = parsedFormData(oid);
		if (formData == null) {
			log.error("Error parsing form data");
			return null;
		}

		// And raw data to see existing relations and write new ones
		JsonSimple rawData = getDataFromStorage(oid);
		if (rawData == null) {
			log.error("Error reading data from storage");
			return null;
		}
		// Existing relationship data
		JSONArray relations = rawData.writeArray("relationships");
		boolean changed = false;

		// For all configured relationships
		for (String baseField : relationFields.keySet()) {
			JsonSimple relationConfig = relationFields.get(baseField);

			// Find the path we need to look under for our related object
			List<String> basePath = relationConfig.getStringList("path");
			if (basePath == null || basePath.isEmpty()) {
				log.error("Ignoring invalid relationship '{}'. No 'path'"
						+ " provided in configuration", baseField);
				continue;
			}

			// Get our base object
			Object object = formData.getPath(basePath.toArray());
			if (object instanceof JsonObject) {
				// And process it
				JsonObject newRelation = lookForRelation(oid, baseField,
						relationConfig, new JsonSimple((JsonObject) object));
				if (newRelation != null
						&& !isKnownRelation(relations, newRelation)) {
					log.info("Adding relation: '{}' => '{}'", baseField,
							newRelation.get("identifier"));
					relations.add(newRelation);
					changed = true;
				}
			}
			// If base path points at an array
			if (object instanceof JSONArray) {
				// Try every entry
				for (Object loopObject : (JSONArray) object) {
					if (loopObject instanceof JsonObject) {
						JsonObject newRelation = lookForRelation(oid,
								baseField, relationConfig, new JsonSimple(
										(JsonObject) loopObject));
						if (newRelation != null
								&& !isKnownRelation(relations, newRelation)) {
							log.info("Adding relation: '{}' => '{}'",
									baseField, newRelation.get("identifier"));
							relations.add(newRelation);
							changed = true;
						}
					}
				}
			}
		}

		// Do we need to store our object again?
		if (changed) {
			try {
				saveObjectData(rawData, oid);
			} catch (TransactionException ex) {
				log.error("Error updating object '{}' in storage: ", oid, ex);
				return null;
			}
		}

		return relations;
	}
137193
protected function setInitialState() {
        $this->initialState['attributes'] = $this->attributes;
        $this->initialState['relationships'] = [];
        foreach($this->relationships as $name => $rel) {
            $data = $rel->getData();
            if ($data) {
                if ($data instanceof ResourceCollectionInterface) {
                    $val = $data->summarize();
                } else {
                    $val = $data->getId() ?: "initial-".rand(1,10000);
                }
            } else {
                $val = null;
            }
            $this->initialState['relationships'][$name] = $val;
        }
    }
1017400
function(parent, key) {
      this.parent = this.parent || parent;
      this.key = this.key || key;
      if (this.parent !== parent) {
        throw "Internal Error. Relation retrieved from two different Objects.";
      }
      if (this.key !== key) {
        throw "Internal Error. Relation retrieved from two different keys.";
      }
    }
3585
public void init(MDatabase pDatabase, FieldList record, Object key)
    {
        super.init(pDatabase, record, key);
    }