/*
|--------------------------------------------------------------------------
| Entity
|--------------------------------------------------------------------------
196809
function CjahInfo(obj) {
    this.id = obj.id
    this.state = obj.state
    this.states = obj.states
    this.trackerWebsite = cjah.getLink(obj.id)
}
974933
function(entity, options) {
      this._byId[entity.cid] = entity;
      var id = this.entityId(entity.attributes);
      if (id != null) this._byId[id] = entity;
      entity.on('all', this._onEntityEvent, this);
    }
561882
function normalizeEntity(entity) {
    if (entity !== null &&
            typeof entity !== 'undefined' &&
            typeof entity.getId === 'function') {
        return entity.getId();
    }
    return entity;
}
322302
private void buildEntityFromCursor(Object entity, HashMap obj, EntityType entityType)
    {
        Iterator<Attribute> iter = entityType.getAttributes().iterator();
        while (iter.hasNext())
        {
            Attribute attribute = iter.next();
            Field field = (Field) attribute.getJavaMember();
            if (field.isAnnotationPresent(Id.class))
            {
                PropertyAccessorHelper.set(entity, field, obj.get(ID));
            }
            else
            {
                PropertyAccessorHelper.set(entity, field, obj.get(((AbstractAttribute) attribute).getJPAColumnName()));
            }

        }
    }
664078
public function delete()
    {
        /*
         * TODO: https://github.com/sulu-io/sulu/pull/1171
         * This method needs to be refactored since in the first
         * iteration the logic was just moved from the Controller
         * to this class due to better reusability.
         */
        $delete = function($id) {
            /** @var Contact $contact */
            $contact = $this->contactRepository->findByIdAndDelete($id);

            if (!$contact) {
                throw new EntityNotFoundException($this->contactRepository->getClassName(), $id);
            }

            $addresses = $contact->getAddresses();
            /** @var Address $address */
            foreach ($addresses as $address) {
                if (!$address->hasRelations()) {
                    $this->em->remove($address);
                }
            }

            $phones = $contact->getPhones()->toArray();
            /** @var Phone $phone */
            foreach ($phones as $phone) {
                if (0 == $phone->getAccounts()->count() && 1 == $phone->getContacts()->count()) {
                    $this->em->remove($phone);
                }
            }
            $emails = $contact->getEmails()->toArray();
            /** @var Email $email */
            foreach ($emails as $email) {
                if (0 == $email->getAccounts()->count() && 1 == $email->getContacts()->count()) {
                    $this->em->remove($email);
                }
            }

            $urls = $contact->getUrls()->toArray();
            /** @var Url $url */
            foreach ($urls as $url) {
                if (0 == $url->getAccounts()->count() && 1 == $url->getContacts()->count()) {
                    $this->em->remove($url);
                }
            }

            $faxes = $contact->getFaxes()->toArray();
            /** @var Fax $fax */
            foreach ($faxes as $fax) {
                if (0 == $fax->getAccounts()->count() && 1 == $fax->getContacts()->count()) {
                    $this->em->remove($fax);
                }
            }

            $socialMediaProfiles = $contact->getSocialMediaProfiles()->toArray();
            /** @var SocialMediaProfile $socialMediaProfile */
            foreach ($socialMediaProfiles as $socialMediaProfile) {
                if (0 == $socialMediaProfile->getAccounts()->count()
                    && 1 == $socialMediaProfile->getContacts()->count()
                ) {
                    $this->em->remove($socialMediaProfile);
                }
            }

            $notes = $contact->getNotes()->toArray();
            /** @var Note $note */
            foreach ($notes as $note) {
                if (0 == $note->getAccounts()->count() && 1 == $note->getContacts()->count()) {
                    $this->em->remove($note);
                }
            }

            $this->em->remove($contact);
            $this->em->flush();
        };

        return $delete;
    }
85546
public function validate() {
		parent::validate();

		if ($this->getEntity() === null) {
			throw new ValidationException("'entity' can't be null", 'entity', $this);
		}
		if ($this->getEntityStates() === null) {
			throw new ValidationException("'entityStates' can't be null", 'entityStates', $this);
		}
		if ($this->getUrl() === null) {
			throw new ValidationException("'url' can't be null", 'url', $this);
		}
	}
1053440
function _processNode(node, level) {
        var nodeData = null;
        
        // entity tag
        if (w.isReadOnly === false && node.attr('_entity') && (node.attr('_tag') || node.attr('_note'))) {
            var id = node.attr('name');
            var entity = w.entitiesManager.getEntity(id);
            var type = node.attr('_type');
            var tag = node.attr('_tag');
            if (tag == null) {
                tag = w.schemaManager.mapper.getParentTag(type);
            }
            
            nodeData = {
                text: tag,
                li_attr: {name: id}, // 'class': type}
                state: {opened: level < 3}
            };
            
            if (w.schemaManager.mapper.isEntityTypeNote(type)) {
                var content = w.schemaManager.mapper.getNoteContentForEntity(entity);
                switch($.type(content)) {
                    case 'array':
                        nodeData.children = [];
                        for (var i = 0; i < content.length; i++) {
                            nodeData.children.push({
                                text: content[i],
                                li_attr: {name: id}
                            });
                        }
                        break;
                    case 'string':
                        nodeData.children = [];
                        nodeData.children.push({
                            text: content,
                            li_attr: {name: id}
                        });
                        break;
                    case 'object':
                        if (content.nodeType !== undefined) {
                            var root = $(tag, content).first();
                            
                            var processChildren = function(children, parent, id) {
                                children.each(function(index, el) {
                                    if (parent.children == null) parent.children = [];
                                    var childData = {
                                        text: el.nodeName,
                                        li_attr: {name: id}
                                    };
                                    parent.children.push(childData);
                                    
                                    processChildren($(el).children(), childData, id);
                                });
                            }
                            
                            processChildren(root.children(), nodeData, id);
                        }
                }
            }
            
        // structure tag
        } else if (node.attr('_tag')) {
            var tag = node.attr('_tag');
            if (w.isReadOnly === false || (w.isReadOnly && (tag === w.root || tree.tagFilter.indexOf(tag.toLowerCase()) !== -1))) {
                var id = node.attr('id');
                var info = w.structs[id];
                
                if (info == undefined) {
                    // redo/undo re-added a struct check
                    info = w.deletedStructs[id];
                    if (info != undefined) {
                        w.structs[id] = info;
                        delete w.deletedStructs[id];
                    }
                }
                
                if (info) {
                    var text = info._tag;
                    if (w.isReadOnly) {
                        if (tag === w.root) {
                            text = w.root;// || w.currentDocId;
                        } else {
                            text = w.utilities.getTitleFromContent(node.text());
                        }
                    }
                    nodeData = {
                        text: text,
                        li_attr: {name: id},
                        state: {opened: level < 3}
                    };
                }
            }
        }
        if (nodeData !== null) {
            nodeData.level = level;
            // FIXME we really shouldn't have this hardcoded here
            // manually set the level for CWRC schema to have proper sorting in readOnly mode
            if (w.schemaManager.schemaId === 'cwrcEntry') {
                var subtype = node.attr('subtype');
                if (subtype !== undefined) {
                    nodeData.level = parseInt(subtype);
                }
            }
        }
        
        return nodeData;
    }
885622
@Override
	public void put(Object entity) {
		if (entity == null) {
			throw new IllegalArgumentException("'entity' must not be [" + entity + "]");
		}
		
		if (operation != null) {
			throw new IllegalStateException("Log [" + operation + "] -> ["
					+ Log.Operation.PUT
					+ "] is not allowed: This operation must be first");
		}
		
		Key id = Keys.create(Translation.toKind(entity.getClass()), Entities.keyValue(entity));
		Entity e = datastore.get(local, id);
		
		if (e != null) {
			throw new EntityExistsException(id);
		}
		
		this.entity = entity;
		operation = Log.Operation.PUT;
	}
717560
protected void store(Object id, Object entity)
    {
        store(id, entity, Boolean.TRUE);
    }
5814
function(entity) {
  // Bind to start event right away.
  var boundStart = entity.start.bind(entity);
  this.on('start', boundStart);
  // Bind to preloadComplete, but only once.
  var boundPreloadComplete = entity.preloadComplete.bind(entity);
  this.once('preloadComplete', boundPreloadComplete);
  // Only bind to update after preloadComplete event.
  var boundUpdate = entity.update.bind(entity);
  this.once('preloadComplete', function() {
    this.on('update', boundUpdate);
  }.bind(this));
  entity.on('destroy', function() {
    this.removeListener('start', boundStart);
    this.removeListener('preloadComplete', boundPreloadComplete);
    this.removeListener('update', boundUpdate);
  }.bind(this));
  this.emit('entityAdded', entity);
}
1158769
function createEntityObject(e) {
		var obj = {id: e.id, className: e.constructor.name, children: []};
		if (e.children && e.children.length > 0) {
			e.children.forEach(function(c) {
				obj.children.push(createEntityObject(c));
			});
		}
		return obj;
	}
1062023
function Entity(route, opts) {
  if (!(this instanceof Entity)) return new Entity(route, opts);
  this._route = route;
  this._options = opts || {};
  this._methods = {};
  this.on('error', function() { /* stifle auto exit on error */ });
}
938816
public function deregisterEntity($entity)
    {
        $entityState = $this->getEntityState($entity);
        unset($this->aggregateRootChildren[$this->getObjectHashId($entity)]);

        if ($entityState == EntityStates::QUEUED || $entityState == EntityStates::REGISTERED) {
            $className                         = $this->getClassName($entity);
            $objectHashId                      = $this->getObjectHashId($entity);
            $entityId                          = $this->getEntityId($entity);
            $this->entityStates[$objectHashId] = EntityStates::UNREGISTERED;
            unset($this->entities[$className][$entityId]);
            $this->changeTracker->stopTracking($entity);
        }
    }
1344456
private void initEntityMetadata(Entity entity) {
    String kind = entity.kind();
    if (kind.trim().length() == 0) {
      kind = entityClass.getSimpleName();
    }
    entityMetadata = new EntityMetadata(entityClass, kind);
  }
202873
public function updateAction(Request $request)
        {

            try {
                $id = $this->getUser()->getId();

                /** @var User $oUser */
                $oUser = UserQuery::create()->findOneById($id);

                if ($oUser === null) {
                    throw $this->createNotFoundException('Unable to find User entity.');
                }

                $aPost = $request->request->get("form");


                $nbUpdatedRows = UserQuery::create()
                    ->filterById($id)
                    ->update(array('NotificationError' => isset($aPost['notification_error']), 'NotificationChange' => isset($aPost['notification_change'])));


                $aResult = array(
                    "success" => true,
                    "message" => $this->get("translator")->trans("notificationcenter.save.successful")
                );

            } catch (\Exception $e) {
                $aResult = array(
                    "success" => false,
                    "message" => $this->get("translator")->trans("notificationcenter.save.failed") . ":<br>" . $e->getMessage()
                );
            }

            $sResult  = json_encode($aResult);
            $response = new Response($sResult);
            $response->headers->set('Content-Type', 'application/json');

            return $response;

        }
632465
public function registerEntity(Entity $entity)
    {
        Logger::get()->debug('Registering entity ' . get_class($entity) . ":{$entity->id}...");
        self::$entities[get_called_class()][$entity->id] = $entity;
        Logger::get()->debug('Registered.');
    }
540829
public function data($entity = '') {
        $entities = [];

        foreach ($this->_data as $line) {
            if ($entity != '') {
                /** @var  $entityObject \Gcs\Framework\Core\Orm\Entity\Entity */
                $entityObject = self::Entity()->$entity();

                foreach ($line as $key => $field) {
                    $value = null;
                    $parent = '';

                    $key = str_replace('count_one_' . $entityObject->name() . '_', '', $key);
                    $key = str_replace('count_many_' . $entityObject->name() . '_', '', $key);
                    $key = str_replace($entityObject->name() . '_', '', $key);

                    if ($entityObject->getField($key) != null) {
                        if (in_array($entityObject->getField($key)->type, [Field::INCREMENT, Field::INT, Field::TEXT, Field::FLOAT, Field::STRING, Field::CHAR, Field::BOOL, Field::DATE, Field::DATETIME, Field::TIMESTAMP, Field::ENUM])) {
                            if ($entityObject->getField($key)->foreign == null) {
                                //If the field is a Datetime or Date or Timestamp we must convert it to \DateTime
                                switch ($entityObject->getField($key)->type) {
                                    case Field::DATETIME:
                                        $value = new \DateTime($field);
                                        break;

                                    case Field::DATE:
                                        $value = new \DateTime($field);
                                        break;

                                    case Field::TIMESTAMP:
                                        $value = new \DateTime($field);
                                        break;

                                    default:
                                        $value = $field;
                                        break;
                                }
                            }
                            elseif (in_array($entityObject->getField($key)->foreign->type(), [ForeignKey::ONE_TO_MANY, ForeignKey::MANY_TO_MANY])) {
                                $value = $field;
                            }
                            else {
                                foreach ($entityObject->fields() as $fieldIsRightForeign) {
                                    if ($fieldIsRightForeign->foreign != null) {
                                        $parent = $fieldIsRightForeign->name . '_';
                                        $value = $this->_getDataRelation($line, $entityObject->getField(str_replace($fieldIsRightForeign->name . '_', '', $key))->foreign, $parent);
                                    }
                                }
                            }
                        }
                        else {
                            switch ($entityObject->getField($key)->type) {
                                case Field::FILE :
                                    $file = new File('', '', '', '');
                                    $file->hydrate($field);
                                    $value = $file;
                                    break;
                            }
                        }

                        $fieldName = str_replace($parent, '', $key);
                        $entityObject->set($fieldName, $value);
                    }
                }
            }
            else {
                $entityObject = new Multiple($line);
            }

            array_push($entities, $entityObject);
        }

        return new Collection($entities);
    }