/*
(non-Javadoc)

@see com.impetus.client.cassandra.CassandraClientBase#findAll(java.lang.Class, java.lang.String[],
java.lang.Object[])
779957
@Override
    public final <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds) {
        // TODO: need to think about selected column case.
        // Bring in IN Clause in place of each read.

        List results = new ArrayList<E>();
        if (rowIds != null) {
            for (Object rowId : rowIds) {
                Object result = find(entityClass, rowId);
                if (result != null) {
                    results.add(result);
                }
            }
        }
        return results;
    }
202323
@Override
    public Object find(Class entityClass, Object key)
    {

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

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

        PropertyAccessorHelper.setId(e, entityMetadata, key);

        return e;
    }
686536
@Override
    public Object find(Class entityClass, Object key)
    {
        GraphDatabaseService graphDb = null;
        if (resource != null)
        {
            graphDb = getConnection();
        }

        if (graphDb == null)
            graphDb = factory.getConnection();

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

        Object entity = null;
        Node node = mapper.searchNode(key, m, graphDb, true);

        if (node != null && !((Neo4JTransaction) resource).containsNodeId(node.getId()))

        {
            entity = getEntityWithAssociationFromNode(m, node);
        }

        return entity;
    }
71764
public List find(String nativeQuery, List<String> relations, EntityMetadata m)
    {
        List entities = new ArrayList();

        s = getStatelessSession();

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

        List result = q.list();

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

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

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

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

                if (relationValue != null && !relationValue.isEmpty())
                {
                    entity = new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationValue);
                }
                entities.add(entity);
            }
            return entities;
        }
        catch (Exception e)
        {
            if (e.getMessage().equals("Can not be translated into entity."))
            {
                return result;
            }
            throw new EntityReaderException(e);
        }
    }
771564
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
            Object columnValue, Class entityClazz)
    {
        return getColumnsById(schemaName, tableName, columnName, pKeyName, columnValue, entityClazz).toArray();
    }
746702
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client) {
        if (log.isDebugEnabled()) {
            log.debug("Populating entities for Cassandra query {}.", getJPAQuery());
        }
        List<Object> result = new ArrayList<Object>();
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        externalProperties = ((CassandraClientBase) client).getExternalProperties();

        // if id attribute is embeddable, it is meant for CQL translation.
        // make it independent of embedded stuff and allow even to add non
        // composite into where clause and let cassandra complain for it.

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m != null ? m.getPersistenceUnit() : client.getPersistenceUnit());

        String query = appMetadata.getQuery(getJPAQuery());
        boolean isNative = kunderaQuery.isNative();
        if (!isNative && !MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {
            result = populateUsingLucene(m, client, result, getKunderaQuery().getResult());
        }
        // change for embeddable
        else if (!isNative && ((CassandraClientBase) client).isCql3Enabled(m)
            && MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {
            result = ((CassandraClientBase) client).executeQuery(m.getEntityClazz(), null, isNative,
                onQueryOverCQL3(m, client, metaModel, null));
        } else {
            if (isNative) {
                // XXX
                if (!kunderaQuery.getBindParameters().isEmpty()) {
                    result = ((CassandraClientBase) client).executeQuery(null, null, isNative,
                        query != null ? query : getJPAQuery(), kunderaQuery.getBindParameters());
                } else {
                    result = ((CassandraClientBase) client).executeQuery(m != null ? m.getEntityClazz() : null, null,
                        isNative, query != null ? query : getJPAQuery());
                }
            } else {
                if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata())) {
                    // Index in Inverted Index table if applicable
                    boolean useInvertedIndex = CassandraIndexHelper.isInvertedIndexingApplicable(m,
                        MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()));
                    Map<Boolean, List<IndexClause>> ixClause = prepareIndexClause(m, useInvertedIndex);
                    if (useInvertedIndex && !getKunderaQuery().getFilterClauseQueue().isEmpty()) {
                        result = (List) ((CassandraEntityReader) getReader()).readFromIndexTable(m, client, ixClause);
                    } else {
                        boolean isRowKeyQuery = ixClause.keySet().iterator().next();
                        if (!isRowKeyQuery) {
                            result = ((CassandraClientBase) client).find(ixClause.get(isRowKeyQuery), m, false, null,
                                isSingleResult ? 1 : this.maxResult,
                                getColumnList(m, metaModel, getKunderaQuery().getResult(), null));
                        } else {
                            result =
                                ((CassandraEntityReader) getReader()).handleFindByRange(m, client, result, ixClause,
                                    isRowKeyQuery, getColumnList(m, metaModel, getKunderaQuery().getResult(), null),
                                    isSingleResult ? 1 : this.maxResult);
                        }
                    }
                }

            }
        }
        return result;
    }
647522
@Override
    public Object find(Class entityClass, Object rowId) {
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        StringBuilder builder = createSelectQuery(rowId, metadata, metadata.getTableName());
        ResultSet rSet = this.execute(builder.toString(), null);
        List results = iterateAndReturn(rSet, metadata);
        return results.isEmpty() ? null : results.get(0);
    }
153391
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
            Object columnValue, Class entityClazz)
    {
        List<Object> rowKeys = new ArrayList<Object>();

        if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
        {
            rowKeys = findIdsByColumnUsingCql(schemaName, tableName, pKeyName, columnName, columnValue, entityClazz);
        }
        else
        {
            Selector selector = clientFactory.getSelector(pool);
            SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, 10000);
            EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

            IndexClause ix = Selector.newIndexClause(Bytes.EMPTY, 10000, Selector.newIndexExpression(columnName
                    + Constants.JOIN_COLUMN_NAME_SEPARATOR + columnValue, IndexOperator.EQ,
                    Bytes.fromByteArray(PropertyAccessorHelper.getBytes(columnValue))));

            Map<Bytes, List<Column>> qResults = selector.getIndexedColumns(tableName, ix, slicePredicate,
                    getConsistencyLevel());

            // iterate through complete map and
            Iterator<Bytes> rowIter = qResults.keySet().iterator();
            while (rowIter.hasNext())
            {
                Bytes rowKey = rowIter.next();

                PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor((Field) metadata
                        .getIdAttribute().getJavaMember());
                Object value = accessor.fromBytes(metadata.getIdAttribute().getJavaType(), rowKey.toByteArray());

                rowKeys.add(value);
            }
        }
        if (rowKeys != null && !rowKeys.isEmpty())
        {
            return rowKeys.toArray(new Object[0]);
        }

        if (log.isInfoEnabled())
        {
            log.info("No row keys found, returning null.");
        }
        return null;
    }
499807
@Override
    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds)
    {
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        if (rowIds == null)
        {
            return null;
        }
        List results = new ArrayList<E>();

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

        EntityType entityType = metaModel.entity(entityClass);

        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();
        try
        {
            if (!subManagedType.isEmpty())
            {
                for (AbstractManagedType subEntity : subManagedType)
                {
                    EntityMetadata subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            subEntity.getJavaType());
                    results = handler.readAll(subEntityMetadata.getSchema(), subEntityMetadata.getEntityClazz(),
                            subEntityMetadata, Arrays.asList(rowIds), subEntityMetadata.getRelationNames());
                    // Result will not be empty for match sub entity.
                    if (!results.isEmpty())
                    {
                        break;
                    }
                }
            }
            else
            {

                results = handler.readAll(entityMetadata.getSchema(), entityMetadata.getEntityClazz(), entityMetadata,
                        Arrays.asList(rowIds), entityMetadata.getRelationNames());
            }
        }
        catch (IOException ioex)
        {
            log.error("Error during find All , Caused by: .", ioex);
            throw new KunderaException(ioex);
        }

        return results;
    }
195687
@Override
    public <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... keys)
    {
        List entities = new ArrayList<E>();
        for (Object key : keys)
        {
            entities.add(find(entityClass, key));
        }
        return entities;
    }
243747
@Override
    public Object find(Class entityClass, Object key)
    {
        HttpResponse response = null;
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());
        try
        {
            if (key instanceof JsonElement)
            {
                key = ((JsonElement) key).getAsString();
            }
            String _id = null;
            if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
            {
                Field field = (Field) entityMetadata.getIdAttribute().getJavaMember();
                EmbeddableType embeddableType = metaModel.embeddable(entityMetadata.getIdAttribute()
                        .getBindableJavaType());
                _id = CouchDBObjectMapper.get_Id(field, key, embeddableType, entityMetadata.getTableName());
            }
            else
            {
                _id = entityMetadata.getTableName() + PropertyAccessorHelper.getString(key);
            }

            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                    CouchDBConstants.URL_SEPARATOR + entityMetadata.getSchema().toLowerCase()
                            + CouchDBConstants.URL_SEPARATOR + _id, null, null);
            HttpGet get = new HttpGet(uri);
            get.addHeader("Accept", "application/json");
            response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));

            InputStream content = response.getEntity().getContent();
            Reader reader = new InputStreamReader(content);

            JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);

            // Check for deleted object. if object is deleted then return null.
            if (jsonObject.get(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()) == null)
            {
                return null;
            }

            return CouchDBObjectMapper.getEntityFromJson(entityClass, entityMetadata, jsonObject,
                    entityMetadata.getRelationNames(), kunderaMetadata);
        }
        catch (Exception e)
        {
            log.error("Error while finding object by key {}, Caused by {}.", key, e);
            throw new KunderaException(e);
        }
        finally
        {
            closeContent(response);
        }
    }
402155
private <T> Iterator<T> getAll(String entityType, IUnmarshaller<T> unmarshaller) throws StorageException {
        String query = matchAllQuery();
        return getAll(entityType, unmarshaller, query);
    }
615689
@Override
    public final <E> List<E> findAll(Class<E> entityClass, String[] columnsToSelect, Object... rowIds)
    {
        return super.findAll(entityClass, columnsToSelect, rowIds);
    }
876813
public @NotNull <T> List<T> findAll(@NotNull Class<T> cl, @NotNull @SQL String sql, Object... args) {
        return findAll(cl, SqlQuery.query(sql, args));
    }
709250
@Override
    public <E> List<E> find(Class<E> entityClass, Map<String, String> col)
    {
        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, getPersistenceUnit(),
                entityClass);
        List<E> entities = new ArrayList<E>();
        Map<String, Field> columnFamilyNameToFieldMap = MetadataUtils.createSuperColumnsFieldMap(entityMetadata,
                kunderaMetadata);
        for (String columnFamilyName : col.keySet())
        {
            String entityId = col.get(columnFamilyName);
            if (entityId != null)
            {
                E e = null;
                try
                {
                    List results = new ArrayList();
                    fetchEntity(entityClass, entityId, entityMetadata, entityMetadata.getRelationNames(),
                            entityMetadata.getSchema(), results, null, null);
                    if (results != null)
                    {
                        e = (E) results.get(0);
                    }
                }
                catch (IOException ioex)
                {
                    log.error("Error during find for embedded entities, Caused by: .", ioex);

                    throw new KunderaException(ioex);
                }

                Field columnFamilyField = columnFamilyNameToFieldMap.get(columnFamilyName.substring(0,
                        columnFamilyName.indexOf("|")));
                Object columnFamilyValue = PropertyAccessorHelper.getObject(e, columnFamilyField);
                if (Collection.class.isAssignableFrom(columnFamilyField.getType()))
                {
                    entities.addAll((Collection) columnFamilyValue);
                }
                else
                {
                    entities.add((E) columnFamilyValue);
                }
            }
        }
        return entities;
    }
428988
public List<Entity> findAll(String tableName) throws SQLException {
		return findAll(Entity.create(tableName));
	}
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);
        }
    }