/*
(non-Javadoc)

@see com.impetus.kundera.client.Client#findByRelation(java.lang.String,
java.lang.Object, java.lang.Class)
13864
@Override
    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        Object[] ids = findIdsByColumn(m.getSchema(), m.getTableName(),
                ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName(), colName, colValue, m.getEntityClazz());
        List<Object> resultSet = new ArrayList<Object>();
        if (ids != null)
        {
            for (Object id : new HashSet(Arrays.asList(ids)))
            {
                Object object = find(entityClazz, id);
                if (object != null)
                {
                    resultSet.add(object);
                }
            }
        }
        return resultSet;
    }
1057476
public function findRelation($entity, $relationName, $orderColumn = null, $orderType = null) {
        $this->load();
        $mapper = MapperBuilder::buildFromClassName($this->mapping, get_class($entity));
        $relation = $mapper->getRelation($relationName);
        $relationMapper = MapperBuilder::buildFromName($this->mapping, $relation->getEntity());

        $selectQuery = "SELECT tmain.* FROM `" . $relationMapper->getTable() . "` tmain ";
        $joinQuery = QueryBuilder::buildJoinRelationQuery($relation, "tmain", "j1");
        $whereQuery = "WHERE j1." . $relation->getLocalColumn() . " = '" . $entity->getId() . "'";

        $orderQuery = "";
        if (!is_null($orderColumn)) {
            $orderQuery .= "ORDER BY $orderColumn ";
            if (!is_null($orderType)) {
                $orderQuery .= "$orderType";
            } else {
                $orderQuery .= "ASC";
            }
        }

        $query = $selectQuery . $joinQuery . $whereQuery . $orderQuery;
        $queryResult = $this->getDataSource()->query($query);
        if ($queryResult) {
            $collection = new Collection($relationMapper->getClass(), $queryResult, $relationMapper);
        } else {
            $collection = new Collection($relationMapper->getClass(), array(), $relationMapper);
        }

        return $collection;
    }
42303
public final Map<String, Object> search(Class<?> clazz, String query, int start, int count, boolean fetchRelation)
    {
        if (indexer != null)
        {
            if (indexer.getClass().getName().equals(IndexingConstants.LUCENE_INDEXER))
            {
                return indexer != null ? ((com.impetus.kundera.index.lucene.Indexer) indexer).search(query, start,
                        count, fetchRelation, kunderaMetadata,
                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz)) : null;
            }
            else
            {
                return indexer.search(clazz, KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz), query,
                        start, count);
            }
        }
        return new HashMap<String, Object>();
    }
1252327
@Override
    public Object find(Class entityClass, Object key)
    {
        return find(entityClass, key, null);
    }
77410
public final Map<String, Object> fetchRelation(Class<?> clazz, String query)
    {
        // TODO: need to return list.
        return search(clazz, query, Constants.INVALID, Constants.INVALID, true);
    }
853817
<T extends Entity> T getRelation(Class<T> valuesClass, String name) {
        return getRelation(valuesClass, name, true);
    }
1067509
public <T extends Relation> T add(T statement,
                                     int num,
                                     Collection<T> anonRelationCollection,
                                     HashMap<QualifiedName, Collection<T>> namedRelationMap,
                                     HashMap<QualifiedName, Collection<T>> effectRelationMap,
                                     HashMap<QualifiedName, Collection<T>> causeRelationMap) {
	QualifiedName aid2 = u.getEffect(statement); //wib.getInformed();
	QualifiedName aid1 = u.getCause(statement); //wib.getInformant();

	statement = pFactory.newStatement(statement); // clone
	
	QualifiedName id;
	if (statement instanceof Identifiable) {
	    id=((Identifiable)statement).getId();	
	} else {
	    id=null;
	}

	if (id == null) {

	    boolean found = false;
	    Collection<T> relationCollection = effectRelationMap.get(aid2);
	    if (relationCollection == null) {
		relationCollection = new LinkedList<T>();
		relationCollection.add(statement);
		effectRelationMap.put(aid2, relationCollection);
	    } else {
		for (T u : relationCollection) {
		    if (u.equals(statement)) {
			found = true;
			statement = u;
			break;
		    }
		}
		if (!found) {
		    relationCollection.add(statement);
		}
	    }

	    relationCollection = causeRelationMap.get(aid1);
	    if (relationCollection == null) {
		relationCollection = new LinkedList<T>();
		relationCollection.add(statement);
		causeRelationMap.put(aid1, relationCollection);
	    } else {
		if (!found) {
		    // if we had not found it in the first table, then we
		    // have to add it here too
		    relationCollection.add(statement);
		}
	    }

	    if (!found) {
		anonRelationCollection.add(statement);
	    }
	} else {
	    Collection<T> relationCollection=namedRelationMap.get(id);
	    if (relationCollection==null) {
		relationCollection=new LinkedList<T>();
		relationCollection.add(statement);
		namedRelationMap.put(id, relationCollection);
	    } else {
		boolean found=false;
		for (T u1: relationCollection) {
		    if (sameEdge(u1,statement,num)) {
			found=true;
			mergeAttributes(u1, statement);
			break;			
		    }
		}
		if (!found) {
		    relationCollection.add(statement);
		}
	    }
	}
	return statement;
}
381303
@Override
	public Links findLinksWithRel(LinkRelation relation, InputStream representation) {

		Assert.notNull(relation, "LinkRelation must not be null!");

		try {

			Object parseResult = getExpression(relation).read(representation);
			return createLinksFrom(parseResult, relation);

		} catch (IOException o_O) {
			throw new RuntimeException(o_O);
		} catch (PathNotFoundException o_O) {
			return Links.NONE;
		}
	}
71764
public List find(String nativeQuery, List<String> relations, EntityMetadata m)
    {
        List entities = new ArrayList();

        s = getStatelessSession();

        SQLQuery q = s.createSQLQuery(nativeQuery);
        q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);

        List result = q.list();

        try
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());

            EntityType entityType = metaModel.entity(m.getEntityClazz());

            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();
            for (Object o : result)
            {
                Map<String, Object> relationValue = null;
                Object entity = null;
                EntityMetadata subEntityMetadata = null;
                if (!subManagedType.isEmpty())
                {
                    for (AbstractManagedType subEntity : subManagedType)
                    {
                        String discColumn = subEntity.getDiscriminatorColumn();
                        String disColValue = subEntity.getDiscriminatorValue();
                        Object value = ((Map<String, Object>) o).get(discColumn);
                        if (value != null && value.toString().equals(disColValue))
                        {
                            subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                    subEntity.getJavaType());
                            break;
                        }
                    }
                    entity = instantiateEntity(subEntityMetadata.getEntityClazz(), entity);
                    relationValue = HibernateUtils.getTranslatedObject(kunderaMetadata, entity,
                            (Map<String, Object>) o, m);

                }
                else
                {
                    entity = instantiateEntity(m.getEntityClazz(), entity);
                    relationValue = HibernateUtils.getTranslatedObject(kunderaMetadata, entity,
                            (Map<String, Object>) o, m);
                }

                if (relationValue != null && !relationValue.isEmpty())
                {
                    entity = new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationValue);
                }
                entities.add(entity);
            }
            return entities;
        }
        catch (Exception e)
        {
            if (e.getMessage().equals("Can not be translated into entity."))
            {
                return result;
            }
            throw new EntityReaderException(e);
        }
    }
459777
public List findByRelation(String colName, Object colValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        String tableName = m.getTableName();

        // Suffixing the UNDERSCORE instead of prefix as Oracle 11g complains
        // about invalid characters error while executing the request.
        StringBuilder queryBuilder = new StringBuilder("Select ");

        queryBuilder.append("* ");
        queryBuilder.append("From ");
        queryBuilder.append(getFromClause(m.getSchema(), tableName));
        queryBuilder.append(" ");

        queryBuilder.append(" Where ");
        queryBuilder.append(colName);
        queryBuilder.append(" = ");
        queryBuilder.append("'");
        queryBuilder.append(colValue);
        queryBuilder.append("'");
        s = getStatelessSession();

        List results = find(queryBuilder.toString(), m.getRelationNames(), m);
        return populateEnhanceEntities(m, m.getRelationNames(), results);
    }
534740
@Override
    public Object find(Class entityClass, Object key)
    {
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());

        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(entityMetadata.getEntityClazz());

        return managedType.hasLobAttribute() ? findGFSEntity(entityMetadata, entityClass, key) : find(entityClass, key,
                entityMetadata, metaModel, managedType);
    }
556467
public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        // you got column name and column value.
        DBCollection dbCollection = mongoDb.getCollection(m.getTableName());

        BasicDBObject query = new BasicDBObject();

        query.put(colName, MongoDBUtils.populateValue(colValue, colValue.getClass()));
        KunderaCoreUtils.printQuery("Find by relation:" + query, showQuery);
        DBCursor cursor = dbCollection.find(query);
        DBObject fetchedDocument = null;
        List<Object> results = new ArrayList<Object>();
        while (cursor.hasNext())
        {
            fetchedDocument = cursor.next();
            populateEntity(m, results, fetchedDocument);
        }

        return results.isEmpty() ? null : results;
    }
1357654
@Override
    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        GetResponse get = null;

        List results = new ArrayList();

        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

        try
        {
            SearchResponse response = txClient
                    .prepareSearch(metadata.getSchema()
                            .toLowerCase())/*
                                            * . addFields ( "*" )
                                            */
                    .setTypes(metadata.getTableName()).setQuery(QueryBuilders.termQuery(colName, colValue)).execute()
                    .get();

            SearchHits hits = response.getHits();
            for (SearchHit hit : hits)
            {
                MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                        .getMetamodel(metadata.getPersistenceUnit());

                EntityType entityType = metaModel.entity(entityClazz);
                Map<String, Object> searchResults = hit.getSource();
                // hit
                Object result = null;
                result = KunderaCoreUtils.createNewInstance(entityClazz);
                result = esResponseReader.wrapFindResult(searchResults, entityType, result, metadata, false);
                if (result != null)
                {
                    results.add(result);
                }
            }
        }
        catch (InterruptedException iex)
        {
            logger.error("Error while find record of {}, Caused by :.", entityClazz.getSimpleName(), iex);
            throw new PersistenceException(iex);
        }
        catch (ExecutionException eex)
        {
            logger.error("Error while find record of {}, Caused by :.", entityClazz.getSimpleName(), eex);
            throw new PersistenceException(eex);
        }

        return results;
    }
336453
@Override
    public T findById(ID id)
            throws NoSuchItemException, JeppettoException {
        GetItemResult result;

        try {
            GetItemRequest getItemRequest = new GetItemRequest(tableName, getKeyFrom(id), consistentRead);

            getItemRequest.setProjectionExpression(projectionExpression);

            if (!projectionExpressionNames.isEmpty()) {
                getItemRequest.setExpressionAttributeNames(projectionExpressionNames);
            }

            result = dynamoDB.getItem(getItemRequest);
        } catch (AmazonClientException e) {
            throw new JeppettoException(e);
        }

        if (result.getItem() == null) {
            throw new NoSuchItemException(entityClass.getSimpleName(), id.toString());
        }

        T t = ConversionUtil.getObjectFromItem(result.getItem(), entityClass);

        ((DynamoDBPersistable) t).__markPersisted(dynamoDB.toString());

        return t;
    }
236937
@Override
	public Links findLinksWithRel(LinkRelation relation, String representation) {

		Assert.notNull(relation, "LinkRelation must not be null!");
		Assert.notNull(representation, "Representation must not be null!");

		return relation.isSameAs(IanaLinkRelations.SELF) //
				? addSelfLink(super.findLinksWithRel(relation, representation), representation) //
				: super.findLinksWithRel(relation, representation);
	}
546091
@Override
    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)
    {
        List<E> results = new ArrayList<E>();

        if (columnsToSelect == null)
        {
            columnsToSelect = new String[0];
        }

        if (keys == null)
        {
            EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
            MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,
                    entityMetadata.getPersistenceUnit());

            EntityType entityType = metamodel.entity(entityMetadata.getEntityClazz());

            Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());
            // KunderaCoreUtils.showQuery("Get all records for " +
            // entityMetadata.getTableName(), showQuery);
            Iterator<Row> rowsIter = tableAPI.tableIterator(schemaTable.createPrimaryKey(), null, null);

            Map<String, Object> relationMap = initialize(entityMetadata);

            try
            {
                results = scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap,
                        Arrays.asList(columnsToSelect));
            }
            catch (Exception e)
            {
                log.error("Error while finding records , Caused By :" + e + ".");
                throw new PersistenceException(e);
            }
        }
        else
        {

            for (Object key : keys)
            {
                results.add((E) find(entityClass, key, Arrays.asList(columnsToSelect)));
            }
        }

        return results;
    }
202323
@Override
    public Object find(Class entityClass, Object key)
    {

        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);

        Object e = r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName()).get(key).run(connection,
                entityClass);

        PropertyAccessorHelper.setId(e, entityMetadata, key);

        return e;
    }