/*
(non-Javadoc)

@see
com.impetus.client.hbase.admin.DataHandler#findParentEntityFromJoinTable
(com.impetus.kundera.metadata.model.EntityMetadata, java.lang.String,
java.lang.String, java.lang.String, java.lang.Object)
185600
@Override
    public List<Object> findParentEntityFromJoinTable(EntityMetadata parentMetadata, String joinTableName,
            String joinColumnName, String inverseJoinColumnName, Object childId)
    {
        throw new PersistenceException("Not applicable for HBase");
    }
272376
@Override
    public <E> List<E> getForeignKeysFromJoinTable(String schemaName, String joinTableName, Object rowKey,
            String inverseJoinColumnName)
    {
        List<E> foreignKeys = new ArrayList<E>();

        HTableInterface hTable = null;

        // Load raw data from Join Table in HBase
        try
        {
            hTable = gethTable(schemaName);

            List<HBaseData> results = hbaseReader.LoadData(hTable, joinTableName, rowKey, getFilter(joinTableName));

            // assuming rowKey is not null.
            if (results != null && !results.isEmpty())
            {

                HBaseData data = results.get(0);

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

                for (String columnName : columnNames)
                {
                    if (columnName.startsWith(inverseJoinColumnName) && data.getColumnFamily().equals(joinTableName))
                    {
                        byte[] columnValue = data.getColumnValue(columnName);

                        // TODO : Because no attribute class is present, so
                        // cannot be done.
                        String hbaseColumnValue = Bytes.toString(columnValue);

                        foreignKeys.add((E) hbaseColumnValue);
                    }
                }
            }
        }
        catch (IOException e)
        {
            return foreignKeys;
        }
        finally
        {
            try
            {
                if (hTable != null)
                {
                    puthTable(hTable);
                }
            }
            catch (IOException e)
            {

                // Do nothing.
            }
        }
        return foreignKeys;
    }
1312462
@Override
    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        // find by relational value !

        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        MetamodelImpl metamodel = (MetamodelImpl) KunderaMetadataManager.getMetamodel(kunderaMetadata,
                entityMetadata.getPersistenceUnit());

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

        Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());

        Iterator<Row> rowsIter = null;
        if (schemaTable.getPrimaryKey().contains(colName))
        {
            PrimaryKey rowKey = schemaTable.createPrimaryKey();
            NoSqlDBUtils.add(schemaTable.getField(colName), rowKey, colValue, colName);
            rowsIter = tableAPI.tableIterator(rowKey, null, null);
        }
        else
        {
            Index index = schemaTable.getIndex(colName);
            IndexKey indexKey = index.createIndexKey();
            NoSqlDBUtils.add(schemaTable.getField(colName), indexKey, colValue, colName);
            rowsIter = tableAPI.tableIterator(indexKey, null, null);
        }

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

            return scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap, null);
        }
        catch (Exception e)
        {
            log.error("Error while finding data for Key " + colName + ", Caused By :" + e + ".");
            throw new PersistenceException(e);
        }

    }
257353
@Override
    public List find(Class entityClass, List<String> relationNames, boolean isWrapReq, EntityMetadata metadata,
        Object... rowIds) {
        return findAll(entityClass, null, rowIds);
    }
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;
    }
111839
@Override
    protected EntityDecl findEntity(String id, Object arg)
        throws XMLStreamException
    {
        EntityDecl ed = mConfig.findCustomInternalEntity(id);
        if (ed == null && mGeneralEntities != null) {
            ed = mGeneralEntities.get(id);
        }
        /* 05-Mar-2006, TSa: Externally declared entities are illegal
         *   if we were declared as "standalone='yes'"...
         */
        if (mDocStandalone == DOC_STANDALONE_YES) {
            if (ed != null && ed.wasDeclaredExternally()) {
                throwParseError(ErrorConsts.ERR_WF_ENTITY_EXT_DECLARED, ed.getName(), null);
            }
        }
        return ed;
    }
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);
    }
215336
@Override
    public Object find(Class entityClass, Object key)
    {

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

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

        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getName();

        Field field = (Field) entityType.getAttribute(idColumnName).getJavaMember();

        Type idType = KuduDBValidationClassMapper.getValidTypeForClass(field.getType());

        KuduTable table;
        try
        {
            table = kuduClient.openTable(entityMetadata.getTableName());
        }
        catch (Exception e)
        {
            logger.error("Cannot open table : " + entityMetadata.getTableName(), e);
            throw new KunderaException("Cannot open table : " + entityMetadata.getTableName(), e);
        }

        KuduScannerBuilder scannerBuilder = kuduClient.newScannerBuilder(table);
        KuduScanner scanner = null;

        if (entityType.getAttribute(idColumnName).getJavaType().isAnnotationPresent(Embeddable.class))
        {
            // Composite Id
            EmbeddableType embeddableIdType = metaModel.embeddable(entityType.getAttribute(idColumnName).getJavaType());
            Field[] fields = entityType.getAttribute(idColumnName).getJavaType().getDeclaredFields();

            addPredicatesToScannerBuilder(scannerBuilder, embeddableIdType, fields, metaModel, key);
        }
        else
        {
            // Simple Id
            ColumnSchema column = new ColumnSchema.ColumnSchemaBuilder(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(), idType).build();

            KuduPredicate predicate = KuduDBDataHandler.getEqualComparisonPredicate(column, idType, key);
            scannerBuilder.addPredicate(predicate);
        }

        scanner = scannerBuilder.build();

        Object entity = null;
        while (scanner.hasMoreRows())
        {
            RowResultIterator results;
            try
            {
                results = scanner.nextRows();
            }
            catch (Exception e)
            {
                logger.error("Cannot get results from table : " + entityMetadata.getTableName(), e);
                throw new KunderaException("Cannot get results from table : " + entityMetadata.getTableName(), e);
            }

            while (results.hasNext())
            {
                RowResult result = results.next();
                entity = KunderaCoreUtils.createNewInstance(entityClass);
                populateEntity(entity, result, entityType, metaModel);
                logger.debug(result.rowToString());
            }
        }
        return entity;
    }
182213
@SuppressWarnings("unchecked")
    public <T> List<Serializable> findId(Class<T> clazz, SearchParameters sp, List<SingularAttribute<?, ?>> availableProperties) {
        //log.info("Searching {} with terms : {} with available Properties: {}", new Object[]{clazz.getSimpleName(), sp.getTerms(), availableProperties});
        FullTextEntityManager fullTextEntityManager = getFullTextEntityManager(entityManager);
        Query query = sp.getLuceneQueryBuilder().build(fullTextEntityManager, sp, availableProperties);

        if (query == null) {
            return null;
        }

        FullTextQuery ftq = fullTextEntityManager.createFullTextQuery( //
                query, clazz);
        ftq.setProjection("id");
        if (sp.getMaxResults() > 0) {
            ftq.setMaxResults(sp.getMaxResults());
        }
        List<Serializable> ids = newArrayList();
        List<Object[]> resultList = ftq.getResultList();
        for (Object[] result : resultList) {
            ids.add((Serializable) result[0]);
        }
        return ids;
    }
461445
public String getJoinColumnName(final KunderaMetadata kunderaMetadata)
    {
                
        if(joinColumnName == null && isJoinedByPrimaryKey)
        {
            EntityMetadata joinClassMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, targetEntity);
            joinColumnName  = ((AbstractAttribute)joinClassMetadata.getIdAttribute()).getJPAColumnName();
        }
        
        if(joinTableMetadata != null)
        {
            joinColumnName = joinTableMetadata.getJoinColumns() != null? joinTableMetadata.getJoinColumns().iterator().next():null;
        }
        
        if(isBiDirectional())
        {
            // Give precedence to join column name!
            if(biDirectionalField.isAnnotationPresent(JoinColumn.class))
            {
                joinColumnName = biDirectionalField.getAnnotation(JoinColumn.class).name();
            }
        }
        
        return joinColumnName !=null? joinColumnName:property.getName();
    }
244386
@Override
    protected List findUsingLucene(EntityMetadata m, Client client)
    {
        QueryTranslator translator = new QueryTranslator();
        translator.translate(getKunderaQuery(), m, true);
        List<Map<String, Object>> columns = translator.getColumnsToOutput(m, getKunderaQuery(), true);
        Object value = null;
        for (Object obj : getKunderaQuery().getFilterClauseQueue())
        {
            if (obj instanceof FilterClause)
            {
                value = ((FilterClause) obj).getValue().get(0);
            }
        }
        byte[] valueInBytes = HBaseUtils.getBytes(value,
                ((AbstractAttribute) m.getIdAttribute()).getBindableJavaType());
        return ((HBaseClient) client).findData(m, valueInBytes, null, null, columns, null);
    }
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;
    }
1291189
private EntityMetadata belongsToPersistenceUnit(EntityMetadata metadata)
    {

        // if pu is null and client is not rdbms OR metadata pu does not match
        // with configured one. don't process for anything.

        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata()
                .getPersistenceUnitMetadata(persistenceUnit);
        String keyspace = puProperties != null ? (String) puProperties.get(PersistenceProperties.KUNDERA_KEYSPACE):null;
        
        keyspace = keyspace == null ? puMetadata.getProperty(PersistenceProperties.KUNDERA_KEYSPACE):keyspace;

        if (metadata.getPersistenceUnit() != null && !metadata.getPersistenceUnit().equals(persistenceUnit)
                || (keyspace != null && metadata.getSchema() != null && !metadata.getSchema().equals(keyspace)))
        {
            metadata = null;
        }
        else
        {
            applyMetadataChanges(metadata);
        }

        /*
         * if ((metadata.getPersistenceUnit() == null &&
         * !(Constants.RDBMS_CLIENT_FACTORY.equalsIgnoreCase(client) ||
         * Constants.NEO4J_CLIENT_FACTORY .equalsIgnoreCase(client))) ||
         * metadata.getPersistenceUnit() != null &&
         * !metadata.getPersistenceUnit().equals(persistenceUnit)) { metadata =
         * null; }
         */

        return metadata;
    }
350258
@Override
    public Object find(Class entityClass, Object key)
    {

        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        JsonDocument doc;
        String id = generateJsonDocId(entityMetadata.getTableName(), key.toString());
        doc = bucket.get(id);
        LOGGER.debug("Found result for ID : " + key.toString() + " in the " + bucket.name() + " Bucket");

        if (doc == null)
        {
            return null;
        }
        else
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                    .getMetamodel(entityMetadata.getPersistenceUnit());
            EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
            return handler.getEntityFromDocument(entityClass, doc.content(), entityType);
        }
    }
215884
private Object find(Class entityClass, Object key, EntityMetadata entityMetadata, MetamodelImpl metaModel,
            AbstractManagedType managedType)
    {
        List<String> relationNames = entityMetadata.getRelationNames();

        BasicDBObject query = new BasicDBObject();

        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
        {
            MongoDBUtils.populateCompoundKey(query, entityMetadata, metaModel, key);
        }
        else
        {
            query.put("_id", MongoDBUtils.populateValue(key, key.getClass()));
        }

        // For secondary tables.
        List<String> secondaryTables = ((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation())
                .getSecondaryTablesName();
        secondaryTables.add(entityMetadata.getTableName());

        Object enhancedEntity = null;
        Map<String, Object> relationValue = null;
        // Here you need to fetch by sub managed type.

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

        for (String tableName : secondaryTables)
        {
            DBCollection dbCollection = mongoDb.getCollection(tableName);
            KunderaCoreUtils.printQuery("Find document:" + query, showQuery);
            DBObject fetchedDocument = dbCollection.findOne(query);

            if (fetchedDocument != null)
            {
                List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

                EntityMetadata subEntityMetadata = 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(entityClass, enhancedEntity);
                    relationValue = handler.getEntityFromDocument(entityMetadata.getEntityClazz(), enhancedEntity,
                            entityMetadata, fetchedDocument, relationNames, relationValue, kunderaMetadata);
                }

            }
        }

        if (relationValue != null && !relationValue.isEmpty())
        {
            EnhanceEntity entity = new EnhanceEntity(enhancedEntity, PropertyAccessorHelper.getId(enhancedEntity,
                    entityMetadata), relationValue);
            return entity;
        }
        else
        {
            return enhancedEntity;
        }
    }
1029479
private java.util.Iterator findParentGroupsForEntity(String memberKey, int type)
            throws GroupsException {
        Connection conn = null;
        Collection groups = new ArrayList();
        IEntityGroup eg = null;

        try {
            conn = RDBMServices.getConnection();
            String sql = getFindParentGroupsForEntitySql();
            PreparedStatement ps = conn.prepareStatement(sql);
            try {
                ps.setString(1, memberKey);
                ps.setInt(2, type);
                if (LOG.isDebugEnabled())
                    LOG.debug(
                            "RDBMEntityGroupStore.findParentGroupsForEntity(): "
                                    + ps
                                    + " ("
                                    + memberKey
                                    + ", "
                                    + type
                                    + ", memberIsGroup = F)");
                ResultSet rs = ps.executeQuery();
                try {
                    while (rs.next()) {
                        eg = instanceFromResultSet(rs);
                        groups.add(eg);
                    }
                } finally {
                    rs.close();
                }
            } finally {
                ps.close();
            }
        } catch (Exception e) {
            LOG.error("RDBMEntityGroupStore.findParentGroupsForEntity(): " + e);
            throw new GroupsException("Problem retrieving containing groups: " + e);
        } finally {
            RDBMServices.releaseConnection(conn);
        }

        return groups.iterator();
    }
459128
@Override
    public Object find(Class entityClass, Object key)
    {
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        GetResponse get = null;

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

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

        String keyAsString = getKeyAsString(key, metadata, metaModel);
        try
        {
            get = txClient.prepareGet(metadata.getSchema().toLowerCase(), metadata.getTableName(), keyAsString)
                    .setOperationThreaded(false).execute().get();
        }
        catch (InterruptedException iex)
        {
            logger.error("Error while find record of {}, Caused by :.", entityClass.getSimpleName(), iex);
            throw new PersistenceException(iex);
        }
        catch (ExecutionException eex)
        {
            logger.error("Error while find record of {}, Caused by :.", entityClass.getSimpleName(), eex);
            throw new PersistenceException(eex);
        }

        Map<String, Object> results = get.getSource();

        Object result = null;

        if (get.isExists())
        {
            result = KunderaCoreUtils.createNewInstance(entityClass);
            PropertyAccessorHelper.setId(result, metadata, key);
            result = esResponseReader.wrapFindResult(results, entityType, result, metadata, true);
        }

        return result;
    }