Currently use similar access as for the entity.

Probably want to extend this to entity access based on the node grant
system when this is implemented.
See https://www.drupal.org/node/777578
340698
public function query() {
    $account = $this->view->getUser();
    $this->query->addTable('post__field_visibility');

    $and_condition = db_and();
    $should_add_where_clause = FALSE;
    if (!$account->hasPermission('view public posts')) {
      $and_condition->condition('post__field_visibility.field_visibility_value', '1', '!=');
      $should_add_where_clause = TRUE;
    }
    if (!$account->hasPermission('view community posts')) {
      $and_condition->condition('post__field_visibility.field_visibility_value', '2', '!=');
      $should_add_where_clause = TRUE;
    }
    if ($should_add_where_clause) {
      $this->query->addWhere('visibility', $and_condition);
    }
  }
198264
private void collectGroupValues(Entity obj, PathEntry entry, GroupSetEntry groupSetEntry, Set<String>[] groupKeys) {
		if(entry.query != null) {
			timers.start("Where", entry.queryText);
			boolean result = entry.checkCondition(obj);
			timers.stop("Where", entry.queryText, result ? 1 : 0);
			if (!result) return;
		}

		for(PathEntry field : entry.leafBranches) {
			String fieldName = field.name;
			int groupIndex = field.groupIndex;
			if(fieldName == PathEntry.ANY) {
			    groupSetEntry.m_groupPaths[groupIndex].addValueKeys(groupKeys[groupIndex], obj.id().toString());
			}
			else {
				String value = obj.get(fieldName);
				if(value == null || value.indexOf(CommonDefs.MV_SCALAR_SEP_CHAR) == -1) {
				    groupSetEntry.m_groupPaths[groupIndex].addValueKeys(groupKeys[groupIndex], value);
				}
				else {
					String[] values = value.split(CommonDefs.MV_SCALAR_SEP_CHAR);
					for(String collectionValue : values) {
					    groupSetEntry.m_groupPaths[groupIndex].addValueKeys(groupKeys[groupIndex], collectionValue);
					}
				}
			}
		}
        for(PathEntry child : entry.linkBranches) {
			boolean hasLinkedEntities = false;
            if(child.nestedLinks == null || child.nestedLinks.size() == 0) {
                for(Entity linkedObj : obj.getLinkedEntities(child.name, child.fieldNames)) {
    				hasLinkedEntities = true;
                    collectGroupValues(linkedObj, child, groupSetEntry, groupKeys);
                }
            }
            else {
                for(LinkInfo linkInfo : child.nestedLinks) {
                    for(Entity linkedObj : obj.getLinkedEntities(linkInfo.name, child.fieldNames)) {
        				hasLinkedEntities = true;
                        collectGroupValues(linkedObj, child, groupSetEntry, groupKeys);
                    }
                }
            }
			if(!hasLinkedEntities && !child.hasUnderlyingQuery())
				nullifyGroupKeys(child, groupSetEntry, groupKeys);
        }
    }
14204
def _get_value(self, entity):
    """"""
    value = self._get_user_value(entity)
    if value is None and entity._projection:
      # Invoke super _get_value() to raise the proper exception.
      return super(StructuredProperty, self)._get_value(entity)
    return value
1356931
function getEntity(urls, entityId) {
  // Add xhtml11.dtd to prevent missing entity errors with XHTML files
  urls.push("resource:///res/dtd/xhtml11.dtd");

  // Build a string of external entities
  var extEntities = "";
  for (i = 0; i < urls.length; i++) {
    extEntities += '<!ENTITY % dtd' + i + ' SYSTEM "' +
                   urls[i] + '">%dtd' + i + ';';
  }

  var parser = Cc["@mozilla.org/xmlextras/domparser;1"]
                  .createInstance(Ci.nsIDOMParser);
  var header = '<?xml version="1.0"?><!DOCTYPE elem [' + extEntities + ']>';
  var elem = '<elem id="elementID">&' + entityId + ';</elem>';
  var doc = parser.parseFromString(header + elem, 'text/xml');
  var elemNode = doc.querySelector('elem[id="elementID"]');

  if (elemNode == null)
    throw new Error(arguments.callee.name + ": Unknown entity - " + entityId);

  return elemNode.textContent;
}
1110406
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        if (!isUpdate)
        {
            r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
                    .insert(populateRmap(entityMetadata, entity)).run(connection);
        }
        else
        {
            r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
                    .update(populateRmap(entityMetadata, entity)).run(connection);
        }
    }
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;
    }
138056
private void selectEntity(Entity entity, Item<Entity> item, String sectionId) {
    	SectionContext sectionContext = NextServerSession.get().getSectionContext(sectionId);
    	if (sectionContext == null) {
    		return;
    	}

        String entityPath = SectionContextUtil.getSelectedEntityPath(sectionId);
        if ((entityPath != null) && entity.getPath().equals(entityPath)) {
            item.add(AttributeModifier.replace("class", "tr-selected"));
            // reset
            SectionContextUtil.setSelectedEntityPath(sectionId, null);
        }
    }
343930
function mergeEntity(mc, node, meta) {
    node._$meta = meta;
    var em = mc.entityManager;

    var entityType = meta.entityType;
    if (typeof (entityType) === 'string') {
      entityType = mc.metadataStore._getEntityType(entityType, false);
    }
    node.entityType = entityType;

    var mergeStrategy = mc.mergeOptions.mergeStrategy;
    var isSaving = mc.query == null;

    var entityKey = entityType.getEntityKeyFromRawEntity(node, mc.rawValueFn);
    var targetEntity = em.findEntityByKey(entityKey);
    if (targetEntity) {
      if (isSaving && targetEntity.entityAspect.entityState.isDeleted()) {
        em.detachEntity(targetEntity);
        return targetEntity;
      }
      var targetEntityState = targetEntity.entityAspect.entityState;
      if (mergeStrategy === MergeStrategy.Disallowed) {
        throw new Error("A MergeStrategy of 'Disallowed' prevents " + entityKey.toString() + " from being merged");
      } else if (mergeStrategy === MergeStrategy.SkipMerge) {
        updateEntityNoMerge(mc, targetEntity, node);
      } else {
        if (mergeStrategy === MergeStrategy.OverwriteChanges
            || targetEntityState.isUnchanged()) {
          updateEntity(mc, targetEntity, node);
          targetEntity.entityAspect.wasLoaded = true;
          if (meta.extraMetadata) {
            targetEntity.entityAspect.extraMetadata = meta.extraMetadata;
          }
          targetEntity.entityAspect.entityState = EntityState.Unchanged;
          clearOriginalValues(targetEntity);
          targetEntity.entityAspect.propertyChanged.publish({ entity: targetEntity, propertyName: null });
          var action = isSaving ? EntityAction.MergeOnSave : EntityAction.MergeOnQuery;
          em.entityChanged.publish({ entityAction: action, entity: targetEntity });
          // this is needed to handle an overwrite of a modified entity with an unchanged entity
          // which might in turn cause _hasChanges to change.
          if (!targetEntityState.isUnchanged()) {
            em._notifyStateChange(targetEntity, false);
          }
        } else {
          if (targetEntityState == EntityState.Deleted && !mc.mergeOptions.includeDeleted) {
            return null;
          }
          updateEntityNoMerge(mc, targetEntity, node);
        }
      }
    } else {
      targetEntity = entityType._createInstanceCore();

      updateEntity(mc, targetEntity, node);

      if (meta.extraMetadata) {
        targetEntity.entityAspect.extraMetadata = meta.extraMetadata;
      }
      // em._attachEntityCore(targetEntity, EntityState.Unchanged, MergeStrategy.Disallowed);
      em._attachEntityCore(targetEntity, EntityState.Unchanged, mergeStrategy);
      targetEntity.entityAspect.wasLoaded = true;
      em.entityChanged.publish({ entityAction: EntityAction.AttachOnQuery, entity: targetEntity });
    }
    return targetEntity;
  }
894144
@Override
    public boolean hasPermission(User user, E entity, Permission permission) {

        // always grant READ access to own user object (of the logged in user)
        if (user != null && user.equals(entity)
            && permission.equals(Permission.READ)) {
            LOG.trace("Granting READ access on own user object");
            return true;
        }

        // call parent implementation
        return super.hasPermission(user, entity, permission);
    }
1215069
private void onCheckRelation()
    {
        try
        {
            results = populateEntities(entityMetadata, client);

            if (entityMetadata.isRelationViaJoinTable()
                    || (entityMetadata.getRelationNames() != null && !(entityMetadata.getRelationNames().isEmpty())))
            {
                query.setRelationalEntities(results, client, entityMetadata);
            }
        }
        catch (Exception e)
        {
            throw new PersistenceException("Error while scrolling over results, Caused by :.", e);
        }
    }
431819
private void populateNodeProperties(Object entity, EntityMetadata m, Node node)
    {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());
        EntityType entityType = metaModel.entity(m.getEntityClazz());

        // Iterate over entity attributes
        Set<Attribute> attributes = entityType.getSingularAttributes();
        for (Attribute attribute : attributes)
        {
            Field field = (Field) attribute.getJavaMember();

            // Set Node level properties
            if (!attribute.isCollection() && !attribute.isAssociation() && !((SingularAttribute) attribute).isId())
            {
                String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
                Object value = PropertyAccessorHelper.getObject(entity, field);
                if (value != null)
                {
                    node.setProperty(columnName, toNeo4JProperty(value));
                }
            }
        }
    }
808367
public void persist(Node node)
    {
        Object entity = node.getData();
        Object id = node.getEntityId();
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());
        isUpdate = node.isUpdate();
        List<RelationHolder> relationHolders = getRelationHolders(node);
        onPersist(metadata, entity, id, relationHolders);
        id = PropertyAccessorHelper.getId(entity, metadata);
        node.setEntityId(id);
        indexNode(node, metadata);
    }
1294276
function () {
    var collisionEntities;
    var data = this.data;
    var el = this.el;

    if (!data.collisionEntities) {
      this.collisionEntities = [];
      return;
    }

    collisionEntities = [].slice.call(el.sceneEl.querySelectorAll(data.collisionEntities));
    this.collisionEntities = collisionEntities;

    // Update entity list on attach.
    this.childAttachHandler = function childAttachHandler (evt) {
      if (!evt.detail.el.matches(data.collisionEntities)) { return; }
      collisionEntities.push(evt.detail.el);
    };
    el.sceneEl.addEventListener('child-attached', this.childAttachHandler);

    // Update entity list on detach.
    this.childDetachHandler = function childDetachHandler (evt) {
      var index;
      if (!evt.detail.el.matches(data.collisionEntities)) { return; }
      index = collisionEntities.indexOf(evt.detail.el);
      if (index === -1) { return; }
      collisionEntities.splice(index, 1);
    };
    el.sceneEl.addEventListener('child-detached', this.childDetachHandler);
  }
1014100
static function appendRelatingNodeIDs( $object, &$nodeIDList )
    {
        $viewCacheIni = eZINI::instance( 'viewcache.ini' );
        if ( $viewCacheIni->hasVariable( 'ViewCacheSettings', 'ClearRelationTypes' ) )
        {
            $relTypes = $viewCacheIni->variable( 'ViewCacheSettings', 'ClearRelationTypes' );

            if ( !count( $relTypes ) )
                return;

            $relatedObjects = array();

            $relationsMask = 0;
            if ( in_array( 'object', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_COMMON | eZContentObject::RELATION_EMBED;

            if ( in_array( 'common', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_COMMON;

            if ( in_array( 'embedded', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_EMBED;

            if ( in_array( 'linked', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_LINK;

            if ( in_array( 'attribute', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_ATTRIBUTE;

            if ( $relationsMask )
            {
                $objects = $object->relatedContentObjectList( false, false, false, false,
                                                              array( 'AllRelations' => $relationsMask ) );
                $previousVersionObjects = array();
                $previousVersion = $object->previousVersion();
                if ( $previousVersion )
                {
                    $previousVersionObjects = $object->relatedContentObjectList( $previousVersion, false, false, false,
                                                              array( 'AllRelations' => $relationsMask ) );
                }
                $relatedObjects = array_merge( $relatedObjects, $objects, $previousVersionObjects );
            }

            $relationsMask = 0;
            if ( in_array( 'reverse_object', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_COMMON | eZContentObject::RELATION_EMBED;

            if ( in_array( 'reverse_common', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_COMMON;

            if ( in_array( 'reverse_embedded', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_EMBED;

            if ( in_array( 'reverse_linked', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_LINK;

            if ( in_array( 'reverse_attribute', $relTypes ) )
                $relationsMask |= eZContentObject::RELATION_ATTRIBUTE;

            if ( $relationsMask )
            {
                $objects = $object->reverseRelatedObjectList( false, false, false,
                                                              array( 'AllRelations' => $relationsMask ) );
                $previousVersionObjects = array();
                $previousVersion = $object->previousVersion();
                if ( $previousVersion )
                {
                    $previousVersionObjects = $object->relatedContentObjectList( $previousVersion, false, false, false,
                                                              array( 'AllRelations' => $relationsMask ) );
                }
                $relatedObjects = array_merge( $relatedObjects, $objects, $previousVersionObjects );
            }
        }
        else
        {
            $normalRelated = $object->relatedContentObjectArray();
            $reversedRelated = $object->contentObjectListRelatingThis();

            $relatedObjects = array_merge( $normalRelated, $reversedRelated );
        }

        foreach ( $relatedObjects as $relatedObject )
        {
            $assignedNodes = $relatedObject->assignedNodes( false );
            foreach ( $assignedNodes as $assignedNode )
            {
                $nodeIDList[] = $assignedNode['node_id'];
            }
        }
        $nodeIDList = array_unique( $nodeIDList );
    }
569783
function _fillAction(entity, actionObj, actionType) {

    if (!(entity instanceof Scope) && !entity.id) {
      throw new Error('This entity does not have an ID.');
    }

    var ret = actionObj;

    if (Utils.isArray(actionObj)) {

      ret = actionObj.map(function (singleAction) {
        return _fillAction(entity, singleAction, actionType);
      });

    } else {
      ret.type = actionType !== 'all' && actionType ||  actionObj.type || '';
      _addEntityIdentifier(entity, ret);
    }

    return ret;
  }
86442
function(instance) {
      var loadData = function(data) {
        return _.extend(instance, data);
      };

      if (instance.id) {
        // do PUT save
        return api
          .one(config.entity, instance.id)
          .put(instance)
          .then(loadData, console.error);
      } else {
        // no id is set, do a POST
        var endpoint = api;
        if (config.parent) {
          endpoint.one(config.parent.entity, instance[config.parent.key]);
        }
        endpoint.all(config.entity);

        return endpoint
          .post(instance)
          .then(loadData, console.error);
      }
    }
377188
@SuppressWarnings("unchecked")
    private void addPrivateFieldsAccessors(ClassNode node) {
        Set<ASTNode> accessedFields = (Set<ASTNode>) node.getNodeMetaData(StaticTypesMarker.PV_FIELDS_ACCESS);
        if (accessedFields==null) return;
        Map<String, MethodNode> privateConstantAccessors = (Map<String, MethodNode>) node.getNodeMetaData(PRIVATE_FIELDS_ACCESSORS);
        if (privateConstantAccessors!=null) {
            // already added
            return;
        }
        int acc = -1;
        privateConstantAccessors = new HashMap<String, MethodNode>();
        final int access = Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC;
        for (FieldNode fieldNode : node.getFields()) {
            if (accessedFields.contains(fieldNode)) {

                acc++;
                Parameter param = new Parameter(node.getPlainNodeReference(), "$that");
                Expression receiver = fieldNode.isStatic()?new ClassExpression(node):new VariableExpression(param);
                Statement stmt = new ExpressionStatement(new PropertyExpression(
                        receiver,
                        fieldNode.getName()
                ));
                MethodNode accessor = node.addMethod("pfaccess$"+acc, access, fieldNode.getOriginType(), new Parameter[]{param}, ClassNode.EMPTY_ARRAY, stmt);
                privateConstantAccessors.put(fieldNode.getName(), accessor);
            }
        }
        node.setNodeMetaData(PRIVATE_FIELDS_ACCESSORS, privateConstantAccessors);
    }