/*
(non-Javadoc)

@see
com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera
.metadata.model.EntityMetadata, com.impetus.kundera.client.Client)
421465
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();

        try
        {
            String query = appMetadata.getQuery(getJPAQuery());

            boolean isNative = kunderaQuery.isNative();

            if (isNative)
            { // Native Query Support is enabled
                return ((MongoDBClient) client).executeQuery(query == null ? getJPAQuery() : query, m);
            }

            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                if (kunderaQuery.isAggregated())
                {
                    return ((MongoDBClient) client).aggregate(m,
                            createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), createAggregationLookup(m),
                            createAggregation(m), getAggregationOrderByClause(m), isSingleResult ? 1 : maxResult);
                }
                else
                {
                    BasicDBObject orderByClause = getOrderByClause(m);
                    return ((MongoDBClient) client).loadData(m,
                            createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), null, orderByClause,
                            isSingleResult ? 1 : maxResult, firstResult, isCountQuery(),
                            getKeys(m, getKunderaQuery().getResult()), getKunderaQuery().getResult());
                }
            }
            else
            {
                return populateUsingLucene(m, client, null, getKunderaQuery().getResult());
            }

        }
        catch (Exception e)
        {

            log.error("Error during executing query, Caused by:", e);
            throw new QueryHandlerException(e);
        }
    }
478176
private void populateQueryComponents(EntityMetadata m, QueryComponent sq)
    {
        boolean hasChildren = false;
        if (sq.children != null && sq.children.size() > 0)
        {
            hasChildren = true;
            for (QueryComponent subQ : sq.children)
            {
                populateQueryComponents(m, subQ);
            }
        }
        if (sq.clauses.size() > 0 || hasChildren)
        {
            if (sq.clauses.size() > 0)
            {
                sq.actualQuery = createSubMongoQuery(m, sq.clauses);
            }
            if (hasChildren)
            {
                List<BasicDBObject> childQs = new ArrayList<BasicDBObject>();
                if (sq.clauses.size() > 0)
                    childQs.add(sq.actualQuery);
                for (QueryComponent subQ : sq.children)
                {
                    childQs.add(subQ.actualQuery);
                }
                if (childQs.size() == 1)
                {
                    sq.actualQuery = childQs.get(0);
                }
                else if (sq.isAnd)
                {
                    BasicDBObject dbo = new BasicDBObject("$and", childQs);
                    sq.actualQuery = dbo;
                }
                else
                {
                    BasicDBObject dbo = new BasicDBObject("$or", childQs);
                    sq.actualQuery = dbo;
                }
            }
        }
    }
812433
private void populateGroupByResponse(Map<String, Object> aggregations, Iterable<Expression> resultOrderIterable,
            List<Object> results, Client client, EntityMetadata m)
    {
        List temp;
        Object entity = null;
        for (String entry : aggregations.keySet())
        {
            entity = null;
            Object obj = aggregations.get(entry);
            temp = new ArrayList<>();
            Iterator<Expression> resultOrder = resultOrderIterable.iterator();
            while (resultOrder.hasNext())
            {
                Expression expression = (Expression) resultOrder.next();

                if (AggregateFunction.class.isAssignableFrom(expression.getClass()))
                {
                    if (((Map) obj).get(expression.toParsedText()) != null)
                    {
                        temp.add(((Map) obj).get(expression.toParsedText()));
                    }
                }
                else
                {
                    if (entity == null)
                    {
                        entity = findUsingLucene(m, client, new Object[] { entry }).get(0);
                    }
                    temp.add(getEntityFieldValue(m, entity, expression.toParsedText()));
                }
            }
            results.add(temp.size() == 1 ? temp.get(0) : temp);
        }
    }
1155723
@Override
    protected List recursivelyPopulateEntities(EntityMetadata m, Client client)
    {
        List<EnhanceEntity> ls = populateEntities(m, client);
        return setRelationEntities(ls, client, m);
    }
914686
public void populate(Entity entity) {
    stream(entity.getEntityType().getAllAttributes())
        .filter(Attribute::hasDefaultValue)
        .forEach(attr -> populateDefaultValues(entity, attr));
  }
388820
public void setEntityTypes(java.util.Collection<EntityRecognizerMetadataEntityTypesListItem> entityTypes) {
        if (entityTypes == null) {
            this.entityTypes = null;
            return;
        }

        this.entityTypes = new java.util.ArrayList<EntityRecognizerMetadataEntityTypesListItem>(entityTypes);
    }
253363
public ResourceIterator<Node> findEntities(GraphDatabaseService executionEngine, EntityKey[] keys) {
		if ( singlePropertyKey ) {
			return singlePropertyIdFindEntities( executionEngine, keys );
		}
		else {
			return multiPropertiesIdFindEntities( executionEngine, keys );
		}
	}
1205861
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());
        EntityType entity = metaModel.entity(m.getEntityClazz());
        Expression whereExpression = KunderaQueryUtils.getWhereClause(kunderaQuery.getJpqlExpression());

        QueryBuilder filter = whereExpression == null || whereExpression instanceof NullExpression ? null
                : esFilterBuilder.populateFilterBuilder(((WhereClause) whereExpression).getConditionalExpression(), m);

        return ((ESClient) client).executeQuery(filter, buildAggregation(kunderaQuery, m, filter), m,
                getKunderaQuery(),this.firstResult, this.maxResult);
    }
11325
protected void populateAuthenticationMetadataAttributes(final AuthenticationBuilder builder,
                                                            final AuthenticationTransaction transaction) {
        LOGGER.debug("Invoking authentication metadata populators for authentication transaction");
        val pops = getAuthenticationMetadataPopulatorsForTransaction(transaction);
        pops.forEach(populator -> transaction.getCredentials()
            .stream()
            .filter(populator::supports)
            .forEach(credential -> populator.populateAttributes(builder, transaction)));
    }
281539
@Override
    public List<EnhanceEntity> populateRelation(EntityMetadata m, Client client, int maxResults)
    {
        // TODO: maxresults to be taken care after work on pagination.

        List<EnhanceEntity> ls = null;
        List<String> relationNames = m.getRelationNames();
        boolean isParent = m.isParent();
        if (!isParent)
        {
            // if it is not a parent.
            String sqlQuery = null;
            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                sqlQuery = getSqlQueryFromJPA(m, relationNames, null);
            }
            else
            {
                // prepare lucene query and find.
                Set<String> rSet = fetchDataFromLucene(m.getEntityClazz(), client);
                if (rSet != null && !rSet.isEmpty())
                {
                    filter = "WHERE";
                }
                sqlQuery = getSqlQueryFromJPA(m, relationNames, rSet);
            }
            // call client with relation name list and convert to sql query.

            ls = populateEnhanceEntities(m, relationNames, client, sqlQuery);
        }
        else
        {
            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                try
                {
                    List entities = ((HibernateClient) client).find(getSqlQueryFromJPA(m, relationNames, null),
                            new ArrayList<String>(), m);
                    ls = new ArrayList<EnhanceEntity>(entities.size());
                    ls = transform(m, ls, entities);
                }
                catch (Exception e)
                {
                    log.error("Error while executing handleAssociation for RDBMS, Caused by {}.", e);
                    throw new QueryHandlerException(e);
                }
            }
            else
            {
                ls = onAssociationUsingLucene(m, client, ls);
            }
        }

        return ls;
    }
1072653
private void populateId(EntityMetadata entityMetadata, Table schemaTable, Object entity, Row row)
    {
        FieldDef fieldMetadata;
        FieldValue value;
        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();

        fieldMetadata = schemaTable.getField(idColumnName);

        value = row.get(idColumnName);

        NoSqlDBUtils.get(fieldMetadata, value, entity, (Field) entityMetadata.getIdAttribute().getJavaMember());
    }
1118368
protected void populateData(final T selectedBaseEntity) {
        this.selectedBaseEntity = selectedBaseEntity;
        editButton.setEnabled(selectedBaseEntity != null);
        manageMetadataBtn.setEnabled(selectedBaseEntity != null);
        if (selectedBaseEntity == null) {
            setName(getDefaultCaption(), "");
        } else {
            setName(getDefaultCaption(), getName());
        }
        populateLog();
        populateDescription();
        populateDetailsWidget();
    }
307336
private void populateRelations(EntityMetadata m, Object entity, Map<String, Object> relationMap, Node node,
            Map<Long, Object> nodeIdToEntityMap)
    {
        // Populate all relationship entities that are in Neo4J
        for (Relation relation : m.getRelations())
        {
            if (relation != null)
            {
                Class<?> targetEntityClass = relation.getTargetEntity();
                EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                        targetEntityClass);
                Field property = relation.getProperty();
                if (relation.getPropertyType().isAssignableFrom(Map.class))
                {
                    Map<Object, Object> targetEntitiesMap = new HashMap<Object, Object>();

                    // If relationship entity is stored into Neo4J, fetch it
                    // immediately
                    if (isEntityForNeo4J(targetEntityMetadata))
                    {

                        for (Relationship relationship : node.getRelationships(Direction.OUTGOING,
                                DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                        {
                            if (relationship == null)
                            {
                                continue;
                            }

                            // Target Entity
                            Node endNode = relationship.getEndNode();
                            if (endNode == null)
                            {
                                continue;
                            }
                            Object targetEntity = nodeIdToEntityMap.get(endNode.getId());
                            if (targetEntity == null)
                            {
                                targetEntity = mapper.getEntityFromNode(endNode, targetEntityMetadata);
                            }

                            // Relationship Entity
                            Object relationshipEntity = mapper.getEntityFromRelationship(relationship, m, relation);

                            // If this relationship is bidirectional, put source
                            // entity into Map field for target entity
                            Field bidirectionalField = relation.getBiDirectionalField();
                            Map<Object, Object> sourceEntitiesMap = new HashMap<Object, Object>();
                            if (bidirectionalField != null)
                            {
                                for (Relationship incomingRelationship : endNode.getRelationships(Direction.INCOMING,
                                        DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                                {
                                    Node startNode = incomingRelationship.getStartNode();
                                    Object sourceEntity = nodeIdToEntityMap.get(startNode.getId());
                                    if (sourceEntity == null)
                                    {
                                        sourceEntity = mapper.getEntityFromNode(startNode, m);
                                        nodeIdToEntityMap.put(startNode.getId(), sourceEntity);
                                    }
                                    sourceEntitiesMap.put(relationshipEntity, sourceEntity);
                                }
                                PropertyAccessorHelper.set(targetEntity, bidirectionalField, sourceEntitiesMap);
                            }

                            // Set references to Target and owning entity in
                            // relationship entity
                            Class<?> relationshipClass = relation.getMapKeyJoinClass();
                            for (Field f : relationshipClass.getDeclaredFields())
                            {
                                if (!ReflectUtils.isTransientOrStatic(f))
                                {

                                    if (f.getType().equals(m.getEntityClazz()))
                                    {
                                        PropertyAccessorHelper.set(relationshipEntity, f, entity);
                                    }
                                    else if (f.getType().equals(targetEntityClass))
                                    {
                                        PropertyAccessorHelper.set(relationshipEntity, f, targetEntity);
                                    }
                                }
                            }
                            targetEntitiesMap.put(relationshipEntity, targetEntity);
                        }

                        PropertyAccessorHelper.set(entity, property, targetEntitiesMap);
                    }

                    /**
                     * If relationship entity is stored in a database other than
                     * Neo4J foreign keys are stored in "Proxy Nodes", retrieve
                     * these foreign keys and set into EnhanceEntity
                     */
                    else
                    {

                        for (Relationship relationship : node.getRelationships(Direction.OUTGOING,
                                DynamicRelationshipType.withName(relation.getJoinColumnName(kunderaMetadata))))
                        {
                            Node proxyNode = relationship.getEndNode();

                            String targetEntityIdColumnName = ((AbstractAttribute) targetEntityMetadata
                                    .getIdAttribute()).getJPAColumnName();
                            Object targetObjectId = proxyNode.getProperty(targetEntityIdColumnName);
                            Object relationshipEntity = mapper.getEntityFromRelationship(relationship, m, relation);

                            targetEntitiesMap.put(targetObjectId, relationshipEntity);
                        }

                        relationMap.put(relation.getJoinColumnName(kunderaMetadata), targetEntitiesMap);
                    }
                }
            }
        }
    }
1168636
public void populate(Entity entity) {
    // auto date
    generateAutoDateOrDateTime(singletonList(entity), entity.getEntityType().getAttributes());

    // auto id
    Attribute idAttr = entity.getEntityType().getIdAttribute();
    if (idAttr != null
        && idAttr.isAuto()
        && entity.getIdValue() == null
        && (idAttr.getDataType() == STRING)) {
      entity.set(idAttr.getName(), idGenerator.generateId());
    }
  }
622197
private List<EnhanceEntity> populateEnhanceEntities(EntityMetadata m, List<String> relationNames, Client client,
            String sqlQuery)
    {
        List<EnhanceEntity> ls = null;
        List result = ((HibernateClient) client).find(sqlQuery, relationNames, m);

        if (!result.isEmpty())
        {
            ls = new ArrayList<EnhanceEntity>(result.size());
            for (Object o : result)
            {
                EnhanceEntity entity = null;
                if (!o.getClass().isAssignableFrom(EnhanceEntity.class))
                {
                    entity = new EnhanceEntity(o, getId(o, m), null);
                }
                else
                {
                    entity = (EnhanceEntity) o;
                }
                ls.add(entity);
            }
        }
        return ls;
    }
1205968
public void setEntityTypes(java.util.Collection<EntityTypesListItem> entityTypes) {
        if (entityTypes == null) {
            this.entityTypes = null;
            return;
        }

        this.entityTypes = new java.util.ArrayList<EntityTypesListItem>(entityTypes);
    }
423299
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        RethinkDB r = ((RethinkDBClient) client).getR();
        Connection conn = ((RethinkDBClient) client).getConnection();

        Filter filter = null;
        Pluck pluck;
        Table table = r.db(m.getSchema()).table(m.getTableName());

        Cursor cursor = null;
        List results = new ArrayList();

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(m.getPersistenceUnit());
        EntityType entityType = metaModel.entity(m.getEntityClazz());

        JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();
        List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);

        if (KunderaQueryUtils.hasWhereClause(jpqlExp))
        {
            // add filters
            WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);
            Expression whereExp = whereClause.getConditionalExpression();
            filter = table.filter(parseAndBuildFilters(entityType, whereExp));
        }

        if (!selectColumns.isEmpty())
        {
            // select by specific columns, consider last for plucking
            pluck = filter == null ? table.pluck(selectColumns) : filter.pluck(selectColumns);
            cursor = pluck.run(conn);
        }

        if (cursor == null)
        {
            cursor = (Cursor) (filter == null ? table.run(conn) : filter.run(conn));
        }

        for (Object obj : cursor)
        {
            Object entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
            buildEntityFromCursor(entity, (HashMap) obj, entityType);
            results.add(entity);
        }

        return results;
    }