/*
(non-Javadoc)

@see
com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera.
metadata.model.EntityMetadata, com.impetus.kundera.client.Client)
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;
    }
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);
        }
    }
1144556
public void addEntities(String[][] entityArray) {
        for (String[] anEntityArray : entityArray) {
            addEntity(anEntityArray[0], Integer.parseInt(anEntityArray[1]));
        }
    }
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());
    }
679277
private Object populateEntityFromHbaseData(Object entity, HBaseData hbaseData, EntityMetadata m, Object rowKey,
            List<String> relationNames)
    {

        try
        {

            // Raw data retrieved from HBase for a particular row key (contains
            // all column families)

            Map<String, Object> relations = new HashMap<String, Object>();

            if (entity.getClass().isAssignableFrom(EnhanceEntity.class))
            {
                relations = ((EnhanceEntity) entity).getRelations();
                entity = ((EnhanceEntity) entity).getEntity();

            }

            // Populate columns data

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

            Set<Attribute> attributes = entityType.getAttributes();

            String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
            String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();

            if (discrColumn != null && hbaseData.getColumnValue(discrColumn) != null && discrValue != null)
            {
                byte[] discrimnatorValue = hbaseData.getColumnValue(discrColumn);
                String actualDiscriminatorValue = Bytes.toString(discrimnatorValue);
                if (actualDiscriminatorValue != null && !actualDiscriminatorValue.equals(discrValue))
                {
                    entity = null;
                    return entity;
                }
            }

            for (Attribute attribute : attributes)
            {
                Class javaType = ((AbstractAttribute) attribute).getBindableJavaType();
                String key = ((AbstractAttribute) attribute).getJPAColumnName();
                if (metaModel.isEmbeddable(javaType))
                {
                    EmbeddableType columnFamily = metaModel.embeddable(javaType);

                    Field columnFamilyFieldInEntity = (Field) attribute.getJavaMember();
                    Class<?> columnFamilyClass = columnFamilyFieldInEntity.getType();

                    // Get a name->field map for columns in this column family
                    Map<String, Field> columnNameToFieldMap = MetadataUtils.createColumnsFieldMap(m, columnFamily);

                    // Column family can be either @Embedded or
                    // @EmbeddedCollection
                    if (Collection.class.isAssignableFrom(columnFamilyClass))
                    {
                        Map<Integer, Object> elementCollectionObjects = new HashMap<Integer, Object>();

                        Field embeddedCollectionField = (Field) attribute.getJavaMember();
                        Object[] embeddedObjectArr = new Object[hbaseData.getColumns().size()];
                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);

                        Map<String, byte[]> hbaseValues = hbaseData.getColumns();

                        Set<String> columnNames = hbaseValues.keySet();

                        for (String columnName : columnNames)
                        {
                            byte[] columnValue = hbaseData.getColumnValue(columnName);

                            if (columnName.startsWith(((AbstractAttribute) attribute).getJPAColumnName()))
                            {
                                String cfNamePostfix = MetadataUtils.getEmbeddedCollectionPostfix(columnName);
                                int cfNameCounter = Integer.parseInt(cfNamePostfix);
                                embeddedObject = elementCollectionObjects.get(cfNameCounter);

                                if (embeddedObject == null)
                                {

                                    embeddedObject = MetadataUtils
                                            .getEmbeddedGenericObjectInstance(embeddedCollectionField);
                                }

                                // Set Hbase data into the embedded object
                                setHBaseDataIntoObject(columnName, columnValue, columnNameToFieldMap, embeddedObject,
                                        metaModel.isEmbeddable(javaType));

                                elementCollectionObjects.put(cfNameCounter, embeddedObject);

                            }

                            if (relationNames != null && relationNames.contains(hbaseData.getColumnFamily())
                                    && columnValue.length != 0)
                            {
                                relations
                                        .put(hbaseData.getColumnFamily(),
                                                getObjectFromByteArray(entityType, columnValue,
                                                        hbaseData.getColumnFamily(), m));
                            }

                            // Save embedded object into Cache, needed while
                            // updation and deletion
                            ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(rowKey,
                                    embeddedObject, hbaseData.getColumnFamily());
                        }

                        for (Integer integer : elementCollectionObjects.keySet())
                        {
                            embeddedObjectArr[integer] = elementCollectionObjects.get(integer);
                        }

                        Collection embeddedCollection = MetadataUtils
                                .getEmbeddedCollectionInstance(embeddedCollectionField);
                        embeddedCollection.addAll(Arrays.asList(embeddedObjectArr));
                        embeddedCollection.removeAll(Collections.singletonList(null));
                        embeddedObjectArr = null; // Eligible for GC

                        // Now, set the embedded collection into entity
                        if (embeddedCollection != null && !embeddedCollection.isEmpty())
                        {
                            PropertyAccessorHelper.set(entity, embeddedCollectionField, embeddedCollection);
                        }
                    }
                    else
                    {
                        Object existsColumnFamilyObj = PropertyAccessorHelper.getObject(entity,
                                columnFamilyFieldInEntity);
                        Object columnFamilyObj = existsColumnFamilyObj != null ? existsColumnFamilyObj
                                : columnFamilyClass.newInstance();

                        Map<String, byte[]> hbaseValues = hbaseData.getColumns();
                        Set<String> columnNames = hbaseValues.keySet();

                        for (String columnName : columnNames)
                        {
                            byte[] columnValue = hbaseData.getColumnValue(columnName);
                            if (relationNames != null && relationNames.contains(hbaseData.getColumnFamily())
                                    && columnValue.length != 0)
                            {
                                relations
                                        .put(hbaseData.getColumnFamily(),
                                                getObjectFromByteArray(entityType, columnValue,
                                                        hbaseData.getColumnFamily(), m));
                            }
                            // Set Hbase data into the column family object
                            // Get Column from metadata
                            Field columnField = columnNameToFieldMap.get(columnName);
                            if (columnField != null && columnValue.length != 0)
                            {
                                if (columnFamilyFieldInEntity.isAnnotationPresent(Embedded.class)
                                        || columnFamilyFieldInEntity.isAnnotationPresent(EmbeddedId.class)
                                        || columnFamilyFieldInEntity.isAnnotationPresent(ElementCollection.class))
                                {
                                    PropertyAccessorHelper.set(columnFamilyObj, columnField,
                                            HBaseUtils.fromBytes(columnValue, columnField.getType()));
                                }
                                else
                                {
                                    columnFamilyObj = getObjectFromByteArray(entityType, columnValue,
                                            hbaseData.getColumnFamily(), m);
                                }
                            }
                        }

                        PropertyAccessorHelper.set(entity, columnFamilyFieldInEntity, columnFamilyObj);
                    }
                }
                else if (!attribute.getName().equals(m.getIdAttribute().getName()))
                {
                    Field columnField = (Field) attribute.getJavaMember();
                    String columnName = ((AbstractAttribute) attribute).getJPAColumnName();

                    byte[] columnValue = hbaseData.getColumnValue(columnName);

                    if (relationNames != null && relationNames.contains(columnName) && columnValue != null
                            && columnValue.length > 0)
                    {
                        relations.put(columnName, getObjectFromByteArray(entityType, columnValue, columnName, m));
                    }
                    else if (columnValue != null && columnValue.length > 0)

                    {
                        PropertyAccessorHelper.set(entity, columnField,
                                HBaseUtils.fromBytes(columnValue, columnField.getType()));
                    }
                }
            }

            if (!relations.isEmpty())
            {

                return new EnhanceEntity(entity, rowKey, relations);
            }

            return entity;
        }
        catch (PropertyAccessException e1)
        {
            throw new RuntimeException(e1);
        }
        catch (InstantiationException e1)
        {
            throw new RuntimeException(e1);
        }
        catch (IllegalAccessException e1)
        {
            throw new RuntimeException(e1);
        }
    }
869799
protected List populateEntitiesFromKeySlices(EntityMetadata m, boolean isWrapReq, List<String> relations,
        List<KeySlice> keys, CassandraDataHandler dataHandler) throws Exception {
        List results;
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());

        Set<String> superColumnAttribs = metaModel.getEmbeddables(m.getEntityClazz()).keySet();
        results = new ArrayList(keys.size());

        ThriftDataResultHelper dataGenerator = new ThriftDataResultHelper();
        for (KeySlice key : keys) {
            List<ColumnOrSuperColumn> columns = key.getColumns();

            byte[] rowKey = key.getKey();

            Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), rowKey);

            Object e = null;
            Map<ByteBuffer, List<ColumnOrSuperColumn>> data = new HashMap<ByteBuffer, List<ColumnOrSuperColumn>>(1);
            data.put(ByteBuffer.wrap(rowKey), columns);
            ThriftRow tr = new ThriftRow();
            tr.setId(id);
            tr.setColumnFamilyName(m.getTableName());
            tr = dataGenerator.translateToThriftRow(data, m.isCounterColumnType(), m.getType(), tr);

            e = dataHandler.populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isWrapReq);

            if (e != null) {
                results.add(e);
            }
        }
        return results;
    }
509330
protected final void populateIdAccessorMethods(EntityMetadata metadata, Class<?> clazz, Field f)
    {
        try
        {
            BeanInfo info = Introspector.getBeanInfo(clazz);

            for (PropertyDescriptor descriptor : info.getPropertyDescriptors())
            {
                if (descriptor.getName().equals(f.getName()))
                {
                    metadata.setReadIdentifierMethod(descriptor.getReadMethod());
                    metadata.setWriteIdentifierMethod(descriptor.getWriteMethod());
                    return;
                }
            }
        }
        catch (IntrospectionException e)
        {
            throw new RuntimeException(e);
        }
    }
258668
private List<Object> populateEmbeddedIdUsingLucene(EntityMetadata m, Client client, List<Object> result,
            Map<String, Object> searchFilter, MetamodelImpl metaModel)
    {
        List<Object> compositeIds = new ArrayList<Object>();

        for (String compositeIdName : searchFilter.keySet())
        {
            Object compositeId = null;
            Map<String, String> uniquePKs = (Map<String, String>) searchFilter.get(compositeIdName);
            compositeId = KunderaCoreUtils.initialize(m.getIdAttribute().getBindableJavaType(), compositeId);

            prepareCompositeIdObject(m.getIdAttribute(), compositeId, uniquePKs, metaModel);
            compositeIds.add(compositeId);
        }
        return findUsingLucene(m, client, compositeIds.toArray());
    }
146672
private List<?> populateEntityObjectsList(DataFrame dataFrame, EntityMetadata m)
    {
        List results = new ArrayList();
        String[] columns = dataFrame.columns();
        Map<String, Integer> map = createMapOfColumnIndex(columns);
        for (Row row : dataFrame.collectAsList())
        {
            Object entity = populateEntityFromDataFrame(m, map, row);
            results.add(entity);
        }
        return results;
    }
903914
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        try
        {
            String query = appMetadata.getQuery(getJPAQuery());
            if (kunderaQuery.isNative())
            {
                // Native Query Support is enabled
                kunderaQuery.setAggregated(isAggregatedQuery());
                return ((SparkClient) client).executeQuery(query == null ? getJPAQuery() : query, m, kunderaQuery);
            }
        }
        catch (Exception e)
        {

            logger.error("Error during executing query, Caused by:", e);
            throw new QueryHandlerException(e);
        }
        return null;
    }
1365509
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        ClientMetadata clientMetadata = ((ClientBase) client).getClientMetadata();
        this.useLuceneOrES = !MetadataUtils.useSecondryIndex(clientMetadata);
        if (useLuceneOrES)
        {
            return populateUsingLucene(m, client, null, kunderaQuery.getResult());
        }
        else
        {
            CouchDBQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), m);
            return ((CouchDBClient) client).createAndExecuteQuery(interpreter);
        }
    }
255602
private Object populateEntityFromHBaseData(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m,
            Object rowKey)
    {
        try
        {
            Map<String, Object> relations = new HashMap<String, Object>();
            if (entity.getClass().isAssignableFrom(EnhanceEntity.class))
            {
                relations = ((EnhanceEntity) entity).getRelations();
                entity = ((EnhanceEntity) entity).getEntity();
            }
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());
            Set<Attribute> attributes = ((AbstractManagedType) entityType).getAttributes();

            writeValuesToEntity(entity, hbaseData, m, metaModel, attributes, m.getRelationNames(), relations, -1, "");
            if (!relations.isEmpty())
            {
                return new EnhanceEntity(entity, rowKey, relations);
            }
            return entity;
        }
        catch (PropertyAccessException e1)
        {
            throw new RuntimeException(e1);
        }
    }
121673
void populateRelationForM2M(Object entity, EntityMetadata entityMetadata, PersistenceDelegator delegator,
            Relation relation, Object relObject, Map<String, Object> relationsMap)
    {
        // For M-M relationship of Collection type, relationship entities are
        // always fetched from Join Table.
        if (relation.getPropertyType().isAssignableFrom(List.class)
                || relation.getPropertyType().isAssignableFrom(Set.class))
        {
            if (relation.isRelatedViaJoinTable() && (relObject == null || ProxyHelper.isProxyOrCollection(relObject)))
            {
                populateCollectionFromJoinTable(entity, entityMetadata, delegator, relation);
            }

        }
        else if (relation.getPropertyType().isAssignableFrom(Map.class))
        {
            if (relation.isRelatedViaJoinTable())
            {
                // TODO: Implement Map relationships via Join Table (not
                // supported as of now)
            }
            else
            {
                populateCollectionFromMap(entity, delegator, relation, relObject, relationsMap);
            }
        }
    }
1607
public function populateEntitiesFromInstall()
    {
        if ($this->automaticallyPopulated) {
            // already run
            return;
        }

        foreach (scandir(BASE_PATH) as $key => $entity) {
            if ($key == "themes") {
                continue;
            }

            $dir = DocumentationHelper::normalizePath(Controller::join_links(BASE_PATH, $entity));

            if (is_dir($dir)) {
                // check to see if it has docs
                $docs = Controller::join_links($dir, 'docs');

                if (is_dir($docs)) {
                    $entities[] = array(
                        'Path' => $docs,
                        'Title' => DocumentationHelper::clean_page_name($entity),
                        'Version' => 'master',
                        'Branch' => 'master',
                        'Stable' => true
                    );
                }
            }
        }

        Config::inst()->update(
            'DocumentationManifest',
            'register_entities',
            $entities
        );

        $this->automaticallyPopulated = true;
    }
224650
@Override
    public CreateUpdateEntitiesResult updateEntities(String entityInstanceDefinition) throws AtlasException {
        entityInstanceDefinition = ParamChecker.notEmpty(entityInstanceDefinition, "Entity instance definition");
        ITypedReferenceableInstance[] typedInstances = deserializeClassInstances(entityInstanceDefinition);

        CreateUpdateEntitiesResult result = repository.updateEntities(typedInstances);
        onEntitiesAddedUpdated(result.getEntityResult());
        return result;
    }
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());
    }
  }
651575
private List populateData(EntityMetadata m, Map<Bytes, List<Column>> qResults, List<Object> entities,
            boolean isRelational, List<String> relationNames, CassandraDataHandler dataHandler)
    {
        if (m.getType().isSuperColumnFamilyMetadata())
        {
            Set<Bytes> primaryKeys = qResults.keySet();

            if (primaryKeys != null && !primaryKeys.isEmpty())
            {
                Object[] rowIds = new Object[primaryKeys.size()];
                int i = 0;
                for (Bytes b : primaryKeys)
                {
                    rowIds[i] = PropertyAccessorHelper.getObject(b, (Field) m.getIdAttribute().getJavaMember());
                    i++;
                }
                entities.addAll(findAll(m.getEntityClazz(), null, rowIds));
            }

        }
        else
        {
            Iterator<Bytes> rowIter = qResults.keySet().iterator();
            while (rowIter.hasNext())
            {
                Bytes rowKey = rowIter.next();
                List<Column> columns = qResults.get(rowKey);
                try
                {
                    Object id = PropertyAccessorHelper
                            .getObject(m.getIdAttribute().getJavaType(), rowKey.toByteArray());
                    Object e = null;
                    e = dataHandler.populateEntity(new ThriftRow(id, m.getTableName(), columns,
                            new ArrayList<SuperColumn>(0), new ArrayList<CounterColumn>(0),
                            new ArrayList<CounterSuperColumn>(0)), m, KunderaCoreUtils.getEntity(e), relationNames,
                            isRelational);
                    if (e != null)
                    {
                        entities.add(e);
                    }
                }
                catch (IllegalStateException e)
                {
                    log.error("Error while returning entities for {}, Caused by: .", m.getEntityClazz(), e);
                    throw new KunderaException(e);
                }
                catch (Exception e)
                {
                    log.error("Error while returning entities for {}, Caused by: .", m.getEntityClazz(), e);
                    throw new KunderaException(e);
                }
            }
        }
        return entities;
    }