/*
(non-Javadoc)

@see
com.impetus.kundera.query.QueryImpl#populateEntities(com.impetus.kundera.
metadata.model.EntityMetadata, com.impetus.kundera.client.Client)
496938
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        if (kunderaQuery.isNative())
        {
            return ((CouchbaseClient) client).executeNativeQuery(getJPAQuery(), m);
        }
        else
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                    .getMetamodel(m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());
            JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();
            List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);
            AsPath asPath;
            if (selectColumns.isEmpty())
            {
                asPath = select(CouchbaseConstants.STAR).from(i(m.getSchema()));
            }
            else
            {
                asPath = select(selectColumns.toArray(new String[selectColumns.size()])).from(i(m.getSchema()));
            }
            Statement statement;

            if (KunderaQueryUtils.hasWhereClause(jpqlExp))
            {
                WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);
                Expression whereExp = whereClause.getConditionalExpression();

                if (whereExp instanceof ComparisonExpression)
                {
                    String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();
                    String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();
                    if (right.startsWith(CouchbaseConstants.POSITIONAL_PREFIX)
                            || right.startsWith(CouchbaseConstants.PARAMETERIZED_PREFIX))
                    {
                        right = kunderaQuery.getParametersMap().get(right) + "";
                    }
                    Attribute attribute = entityType.getAttribute(left.split(CouchbaseConstants.DOT_REGEX)[1]);

                    statement = addWhereCondition(asPath, ((ComparisonExpression) whereExp).getActualIdentifier(),
                            ((AbstractAttribute) attribute).getJPAColumnName(), right, m.getTableName());
                }

            }
            else
            {
                asPath.where(x(CouchbaseConstants.KUNDERA_ENTITY).eq(x("'" + m.getTableName() + "'")));
            }

            statement = asPath;
            return ((CouchbaseClient) client).executeQuery(statement, m);
        }
    }
720769
protected void onColumn(EntityMetadata m, boolean isRelation, List<String> relations, List<Object> entities,
        List<Column> columns, List<AbstractManagedType> subManagedType, ByteBuffer key) {
        if (!columns.isEmpty()) {
            Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key.array());
            ThriftRow tr = new ThriftRow(id, m.getTableName(), columns, new ArrayList<SuperColumn>(0),
                new ArrayList<CounterColumn>(0), new ArrayList<CounterSuperColumn>(0));
            Object o = null;

            if (!subManagedType.isEmpty()) {
                for (AbstractManagedType subEntity : subManagedType) {
                    EntityMetadata subEntityMetadata =
                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, subEntity.getJavaType());

                    o = getDataHandler().populateEntity(tr, subEntityMetadata, KunderaCoreUtils.getEntity(o),
                        subEntityMetadata.getRelationNames(), isRelation);
                    if (o != null) {
                        break;
                    }
                }
            } else {
                o = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(o), relations, isRelation);
            }

            if (log.isInfoEnabled()) {
                log.info("Populating data for entity of clazz {} and row key {}.", m.getEntityClazz(), tr.getId());
            }

            if (o != null) {
                entities.add(o);
            }
        }
    }
671102
private List<EnhanceEntity> populateEnhanceEntities(EntityMetadata m, List<String> relationNames, List result)
    {

        List<EnhanceEntity> ls = null;
        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, PropertyAccessorHelper.getId(o, m), null);
                }
                else
                {
                    entity = (EnhanceEntity) o;
                }
                ls.add(entity);
            }
        }
        return ls;
    }
1051807
@Override
    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)
    {
        List<EnhanceEntity> ls = new ArrayList<EnhanceEntity>();
        RedisQueryInterpreter interpreter = onTranslation(getKunderaQuery().getFilterClauseQueue(), m);
        ls = ((RedisClient) client).onExecuteQuery(interpreter, m.getEntityClazz());
        return setRelationEntities(ls, client, m);
    }
1236396
private void updateEntityMappers() {
    for (Entry<Integer, EntitySchema> entry : schemaManager.getEntitySchemas(
        tableName, entityName).entrySet()) {
      if (!entityMappers.containsKey(entry.getKey())) {
        AvroEntitySchema writtenSchema = (AvroEntitySchema) entry.getValue();
        EntityMapper<ENTITY> entityMapper = constructWrappedEntityMapper(
            keySchema, entitySchema, writtenSchema, entityClass);
        entityMappers.put(entry.getKey(), entityMapper);
      }
    }
  }
1037801
@SuppressWarnings("unchecked")
  public static <T> T populate(Class<T> clazz, String name) {
    EntityType type = null;
    if (clazz.isInterface()) {
      type = Model.getType(clazz.getName());
    } else {
      type = Model.getType(clazz);
    }
    return (T) populate(type.newInstance(), type.getEntityName(), name);
  }
1177605
private void populateEntity(EntityMetadata entityMetadata, List entities, DBObject fetchedDocument)
    {

        // handler.getEntityFromGFSDBFile(entityClazz, entity, m, outputFile,
        // kunderaMetadata)
        Map<String, Object> relationValue = null;
        if (fetchedDocument != null)
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    entityMetadata.getPersistenceUnit());

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

            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

            EntityMetadata subEntityMetadata = null;
            Object enhancedEntity = null;
            if (!subManagedType.isEmpty())
            {
                for (AbstractManagedType subEntity : subManagedType)
                {
                    String discColumn = subEntity.getDiscriminatorColumn();
                    String disColValue = subEntity.getDiscriminatorValue();
                    Object value = fetchedDocument.get(discColumn);
                    if (value != null && value.toString().equals(disColValue))
                    {
                        subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                subEntity.getJavaType());
                        break;
                    }
                }
                enhancedEntity = instantiateEntity(subEntityMetadata.getEntityClazz(), enhancedEntity);
                relationValue = handler.getEntityFromDocument(subEntityMetadata.getEntityClazz(), enhancedEntity,
                        subEntityMetadata, fetchedDocument, subEntityMetadata.getRelationNames(), relationValue,
                        kunderaMetadata);

            }
            else
            {
                enhancedEntity = instantiateEntity(entityMetadata.getEntityClazz(), enhancedEntity);
                relationValue = handler.getEntityFromDocument(entityMetadata.getEntityClazz(), enhancedEntity,
                        entityMetadata, fetchedDocument, entityMetadata.getRelationNames(), relationValue,
                        kunderaMetadata);
            }

            if (relationValue != null && !relationValue.isEmpty())
            {
                enhancedEntity = new EnhanceEntity(enhancedEntity, PropertyAccessorHelper.getId(enhancedEntity,
                        entityMetadata), relationValue);
            }

            if (enhancedEntity != null)
            {
                entities.add(enhancedEntity);
            }
        }
    }
878255
private void iterateAndPopulateEntity(Object entity, RowResult result, MetamodelImpl metaModel,
            Iterator<Attribute> iterator)
    {
        while (iterator.hasNext())
        {
            Attribute attribute = iterator.next();
            Field field = (Field) attribute.getJavaMember();
            // handle for embeddables
            if (attribute.getJavaType().isAnnotationPresent(Embeddable.class))
            {
                EmbeddableType emb = metaModel.embeddable(attribute.getJavaType());
                Object embeddableObj = KunderaCoreUtils.createNewInstance(attribute.getJavaType());
                populateEmbeddedColumn(embeddableObj, result, emb, metaModel);
                PropertyAccessorHelper.set(entity, field, embeddableObj);
            }
            else
            {
                if (KuduDBDataHandler.hasColumn(result.getSchema(), ((AbstractAttribute) attribute).getJPAColumnName()))
                {
                    PropertyAccessorHelper.set(entity, field, KuduDBDataHandler.getColumnValue(result,
                            ((AbstractAttribute) attribute).getJPAColumnName()));
                }
            }
        }
    }
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();
    }
1069887
@Override
    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)
    {
        List result = populateEntities(m, client);
        return setRelationEntities(result, client, m);
    }
678409
public static void populate(Object entity, Map<String, Object> params) {
    meta.getPopulator().populate(entity, meta.getEntityType(entity.getClass()), params);
  }
1144556
public void addEntities(String[][] entityArray) {
        for (String[] anEntityArray : entityArray) {
            addEntity(anEntityArray[0], Integer.parseInt(anEntityArray[1]));
        }
    }
1193337
@Override
    public void populateClientProperties(Client client, Map<String, Object> properties)
    {
        // All client properties currently are those that are specified in
        // neo4j.properties (or custom XML configuration file according to
        // Kundera format)
        // No custom property currently defined by Kundera, leaving empty
        if (log.isDebugEnabled())
            log.debug("No custom property to set for Neo4J");
        for (String key : properties.keySet())
        {
            Object value = properties.get(key);
            if (key.equals(PersistenceProperties.KUNDERA_BATCH_SIZE) && value instanceof Integer)
            {
                Integer batchSize = (Integer) value;
                ((Neo4JClient) client).setBatchSize(batchSize);
            }
        }
    }
395402
private List onQuery(EntityMetadata m, Client client)
    {
        boolean useLuceneOrES = !MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata());
        QueryTranslator translator = new QueryTranslator();
        List<Map<String, Object>> columnsToOutput = translator.getColumnsToOutput(m, getKunderaQuery(), useLuceneOrES);
        translator.translate(getKunderaQuery(), m, useLuceneOrES);
        Filter filters = translator.getFilters();
        if (!translator.isWhereOrAggregationQuery() || !useLuceneOrES)
        {
            return ((HBaseClient) client).findData(m, null, translator.getStartRow(), translator.getEndRow(),
                    columnsToOutput, filters);
        }
        else
        {
            return populateUsingLucene(m, client, null, null);
        }
    }
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);
        }
    }
102211
@Override
    public EnhanceEntity findById(Object primaryKey, EntityMetadata m, Client client)
    {
        List<String> relationNames = m.getRelationNames();
        if (relationNames != null && !relationNames.isEmpty())
        {
            Set<String> keys = new HashSet<String>(1);
            keys.add(primaryKey.toString());
            String query = getSqlQueryFromJPA(m, relationNames, keys);
            List<EnhanceEntity> results = populateEnhanceEntities(m, relationNames, client, query);
            return results != null && !results.isEmpty() ? results.get(0) : null;
        }
        else
        {
            Object o;
            try
            {
                o = client.find(m.getEntityClazz(), primaryKey);
            }
            catch (Exception e)
            {
                throw new PersistenceException(e);
            }
            return o != null ? new EnhanceEntity(o, getId(o, m), null) : null;
        }

        // return super.findById(primaryKey, m, client);
    }
144332
private List getEntityObjects(Class clazz, final EntityMetadata entityMetadata, EntityType entityType,
            SearchHits hits)
    {
        List results = new ArrayList();

        Object entity = null;
        for (SearchHit hit : hits.getHits())
        {
            entity = KunderaCoreUtils.createNewInstance(clazz);
            Map<String, Object> hitResult = hit.sourceAsMap();
            results.add(wrap(hitResult, entityType, entity, entityMetadata, false));
        }

        return results;
    }