Retrieve a sub entity by its relationship.
@param entity cannot be <code>null</code>.
@param rel cannot be <code>null</code> or empty.
@return the located entity or <code>null</code> if not found.
496202
public static Entity getSubEntityByRel(Entity entity, String... rel) {
        if(entity == null) {
            throw new IllegalArgumentException("entity cannot be null.");
        }
        if(ArrayUtils.isEmpty(rel)) {
            throw new IllegalArgumentException("rel cannot be null or empty");
        }
        List<Entity> entities = entity.getEntities();
        if (entities == null)
            return null;
        Entity ent = null;
        for (Entity e : entities) {
            if (ArrayUtils.isNotEmpty(e.getRel()) && ArrayUtils.toString(rel).equals(ArrayUtils.toString(e.getRel()))) {
                ent = e;
                break;
            }
        }
        return ent;
    }
941302
@SuppressWarnings("unchecked")
    @Override
    public final V getEntity(final NamedParameterQueryData query) {
        final Query builtQuery; // Query created from the query data
        V entity; // Entity acquired from the query

        checkNotNull(query, "Received a null pointer as the query");

        // Builds the query
        builtQuery = buildQuery(query);

        // Tries to acquire the entity
        try {
            entity = (V) builtQuery.getSingleResult();
        } catch (final NoResultException exception) {
            entity = null;
        }

        return entity;
    }
608876
public EntityBuilder addSubEntity(Entity subEntity) {
    	if(subEntity == null) {
    		throw new IllegalArgumentException("subEntity cannot be null.");
    	}
        addStep("_addEntity", new Object[] { subEntity }, true);
        return this;
    }
1163723
@SuppressWarnings("unchecked")
	public <T> List<T> find(String riakQuery, Class<T> entity) {
		if (entity == null) {
			throw new ApitraryOrmException("Cannot access null entity");
		}
		log.debug("Searching " + entity.getName() + " " + riakQuery);

		QueriedGetRequest request = new QueriedGetRequest();
		request.setEntity(resolveApitraryEntity(entity));
		request.setQuery(riakQuery);
		QueriedGetResponse response = resolveApitraryClient().send(request);

		return (List<T>) new QueriedGetResponseUnmarshaller(this).unMarshall(response, entity);
	}
338776
@Override
    public Long get(Entity entity) {
        Objects.requireNonNull(entity, "entity cannot be null");
        // return property value
        return entity.get(idFieldName).asLong();
    }
632671
@Override
  public final <T> T retrieveEntity(final Map<String, Object> pAddParam,
    final Class<T> pEntityClass, final String pQuery) throws Exception {
    T entity = null;
    IRecordSet<RS> recordSet = null;
    try {
      recordSet = getSrvDatabase().retrieveRecords(pQuery);
      if (recordSet.moveToFirst()) {
        entity = retrieveEntity(pAddParam, pEntityClass, recordSet);
      }
    } finally {
      if (recordSet != null) {
        recordSet.close();
      }
    }
    return entity;
  }
482603
public final <T> T retrieveEntity(final Map<String, Object> pAddParam,
    final Class<T> pEntityClass,
      final IRecordSet<RS> pRecordSet) throws Exception {
    @SuppressWarnings("unchecked")
    IFactorySimple<T> facEn = (IFactorySimple<T>) this.entitiesFactoriesFatory
      .lazyGet(pAddParam, pEntityClass);
    T entity = facEn.create(pAddParam);
    String foreignFieldNmsNm = "foreignFieldNms";
    List<String> foreignFieldNms = new ArrayList<String>();
    pAddParam.put(foreignFieldNmsNm, foreignFieldNms);
    String currentLevelNm = "currentLevel";
    List<Integer> currentLevel = new ArrayList<Integer>();
    currentLevel.add(1);
    pAddParam.put(currentLevelNm, currentLevel);
    String deepLevelNm = "deepLevel";
    List<Integer> deepLevel = new ArrayList<Integer>();
    deepLevel.add(2); //default top level
    pAddParam.put(deepLevelNm, deepLevel);
    this.fillerEntitiesFromRs.fill(pAddParam, entity, pRecordSet);
    //(TODO itself) exit from all recursions:
    pAddParam.remove(currentLevelNm);
    pAddParam.remove(deepLevelNm);
    pAddParam.remove(foreignFieldNmsNm);
    return entity;
  }
638397
@Override
    protected EntityDecl findEntity(String id, Object arg)
    {
        // Expand a Parameter Entity?
        if (arg == ENTITY_EXP_PE) { // for attribute default
            EntityDecl ed = (mPredefdPEs == null) ? null : mPredefdPEs.get(id);
            if (ed != null) { // Entity from int. subset...
                mUsesPredefdEntities = true;
                /* No need to further keep track of internal references,
                 * since this subset can not be cached, so let's just free
                 * up Map if it has been created
                 */
                mRefdPEs = null;
            } else if (mParamEntities != null) {
                ed = mParamEntities.get(id);
                if (ed != null) {
                    if (!mUsesPredefdEntities) {
                        // Let's also mark down the fact we referenced the entity:
                        Set<String> used = mRefdPEs;
                        if (used == null) {
                            mRefdPEs = used = new HashSet<String>();
                        }
                        used.add(id);
                    }
                }
            }
            return ed;
        }

        // Nope, General Entity (within attribute default value)?
        if (arg == ENTITY_EXP_GE) {
            /* This is only complicated for external subsets, since
             * they may 'inherit' entity definitions from preceding
             * internal subset...
             */
            EntityDecl ed = (mPredefdGEs == null) ? null : mPredefdGEs.get(id);
            if (ed != null) {
                mUsesPredefdEntities = true;
                /* No need to further keep track of references,
                 * as this means this subset is not cachable...
                 * so let's just free up Map if it has been created
                 */
                mRefdGEs = null;
            } else if (mGeneralEntities != null) {
                ed = mGeneralEntities.get(id);
                if (ed != null) {
                    // Ok, just need to mark reference, if we still care:
                    if (!mUsesPredefdEntities) {
                        // Let's also mark down the fact we referenced the entity:
                        if (mRefdGEs == null) {
                            mRefdGEs = new HashSet<String>();
                        }
                        mRefdGEs.add(id);
                    }
                }
            }
            return ed;
        }

        throw new IllegalStateException(ErrorConsts.ERR_INTERNAL);
    }
832994
@Override
  public Entity findOne(Query<Entity> q) {
    Entity entity = delegate().findOne(q);
    return entity != null ? resolveEntityReferences(entity, q.getFetch()) : null;
  }
1208609
@Override
    public final V getEntity(final NamedParameterQueryData query) {
        V entity; // Entity acquired from the query

        checkNotNull(query, "Received a null pointer as the query");

        // Tries to acquire the entity
        try {
            entity = getTemplate().queryForObject(query.getQuery(),
                    query.getParameters(),
                    BeanPropertyRowMapper.newInstance(getType()));
        } catch (final EmptyResultDataAccessException exception) {
            entity = null;
        }

        return entity;
    }
110920
@SuppressWarnings("unchecked")
    public <T extends IEntity> T findById(T entity) throws FMSException {

        IntuitMessage intuitMessage = prepareFindById(entity);

        //execute interceptors
        executeInterceptors(intuitMessage);

        T returnEntity = null;
        IntuitResponse intuitResponse = (IntuitResponse) intuitMessage.getResponseElements().getResponse();
        if (intuitResponse != null) {
            //QBD service is returning object as QueryResponse while QBO is returning object as IntuitObject in IntuitResponse

            if (intuitResponse.getIntuitObject() != null) {
                JAXBElement<? extends IntuitEntity> intuitObject = intuitResponse.getIntuitObject();
                if (intuitObject != null) {
                    returnEntity = ((T) intuitObject.getValue());
                }
            } else if (intuitResponse.getQueryResponse() != null) {
                QueryResponse queryResponse = intuitResponse.getQueryResponse();
                List<JAXBElement<? extends IntuitEntity>> intuitObject = queryResponse.getIntuitObject();
                if (intuitObject != null && intuitObject.size() > 0) {
                    returnEntity = ((T) intuitObject.get(0).getValue());
                }
            }
        }
        return returnEntity;
    }
992849
private Entity innerRetrieveEntityFromRepository(Root root, Entity retEntDO, String uniqueId, boolean isAllowOperationIfReposDown,
                                                     Set<String> failureRepositoryIds) throws WIMException {
        String METHODNAME = "retrieveEntityFromRepository";

        List<String> reposIds = getRepositoryManager().getRepoIds();
        for (int i = 0; (i < reposIds.size() && retEntDO == null); i++) {
            String reposId = reposIds.get(i);

            try {
                Root retRoot = getRepositoryManager().getRepository(reposId).get(root);
                if (retRoot != null) {
                    List<Entity> entList = retRoot.getEntities();

                    if (entList.size() >= 1) {
                        retEntDO = entList.get(0);
                    }
                }
            } catch (EntityNotFoundException e) {
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, METHODNAME + " EntityNotFoundException[reposId=" + reposId + "] - " + uniqueId);
                }
            } catch (WIMSystemException wse) {
                String message = wse.getMessage();
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, METHODNAME + " WSE message = " + message);
                }
                if (message != null && message.contains("CWIML4520E") && message.contains("javax.naming.InvalidNameException")) {
                    if (tc.isDebugEnabled()) {
                        Tr.debug(tc, METHODNAME + " WIMSystemException [reposId=" + reposId + "] - " + message);
                    }
                } else
                    throw wse;
            } catch (Exception e) {
                if (!isAllowOperationIfReposDown) {
                    if (e instanceof WIMException) {
                        throw (WIMException) e;
                    }
                    throw new WIMException(e);
                } else {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, METHODNAME + " IGNORE: exception [" + e.getMessage()
                                     + "] when retrieve entity from repository [" + reposId + "]");
                    failureRepositoryIds.add(reposId);

                }
            }
        }
        return retEntDO;
    }
649058
@Override
    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)
    {
        // required in case of associated entities.
        List ls = onQuery(m, client);
        return setRelationEntities(ls, client, m);
    }
981685
@Override
    public String lookupEntityName(JsonEntityBean entity) {
        if (entity == null) {
            throw new IllegalArgumentException("Parameter cannot be null.");
        }
        EntityEnum entityEnum = entity.getEntityType();
        if (entityEnum == null) {
            throw new IllegalArgumentException(
                    String.format(
                            "Parameter's entityType has an unknown value of [%s]",
                            entity.getEntityType()));
        }
        IEntityNameFinder finder;
        if (entityEnum.isGroup()) {
            finder = EntityNameFinderService.instance().getNameFinder(IEntityGroup.class);
        } else {
            finder = EntityNameFinderService.instance().getNameFinder(entityEnum.getClazz());
        }

        try {
            return finder.getName(entity.getId());
        } catch (Exception e) {
            /* An exception here isn't the end of the world.  Just log it
            and return null. */
            log.warn("Couldn't find name for entity " + entity.getId(), e);
            return null;
        }
    }
344173
public void detach(Object entity)
    {
        Node node = getPersistenceCache().getMainCache().getNodeFromCache(entity, getMetadata(entity.getClass()), this);
        if (node != null)
        {
            node.detach();
        }
    }
949240
public <T> Key<T> getKey(final T entity) {
        T unwrapped = entity;
        if (unwrapped instanceof ProxiedEntityReference) {
            final ProxiedEntityReference proxy = (ProxiedEntityReference) unwrapped;
            return (Key<T>) proxy.__getKey();
        }

        unwrapped = ProxyHelper.unwrap(unwrapped);
        if (unwrapped instanceof Key) {
            return (Key<T>) unwrapped;
        }

        final Object id = getId(unwrapped);
        final Class<T> aClass = (Class<T>) unwrapped.getClass();
        return id == null ? null : new Key<T>(aClass, getCollectionName(aClass), id);
    }
1193381
public <T> T update(T entity) {
		if (entity == null) {
			throw new ApitraryOrmException("Cannot update null entity");
		}

		log.debug("Updating " + entity.getClass());

		PutRequest request = new PutRequest();
		request.setEntity(resolveApitraryEntity(entity));
		request.setId(resolveApitraryEntityId(entity));

		String payload = marshall(entity);

		request.setRequestPayload(payload);

		PutResponse response = resolveApitraryClient().send(request);

		if (HttpStatus.No_Content.ordinal() != response.getStatusCode()) {
			if (HttpStatus.Not_Found.ordinal() == response.getStatusCode()) {
				throw new ApitraryOrmUpdateException("Cannot update object: object with given id does not exist.");
			} else {
				String statusMessage = (String) new PutResponseUnmarshaller().unMarshall(response, entity);
				throw new ApitraryOrmUpdateException(statusMessage);
			}
		}
		return entity;
	}