/*
(non-Javadoc)

@see com.impetus.client.cassandra.CassandraClientBase#findByRange(byte[],
byte[], com.impetus.kundera.metadata.model.EntityMetadata, boolean,
java.util.List, java.util.List, java.util.List, int)
339727
@Override
    public List findByRange(byte[] minVal, byte[] maxVal, EntityMetadata m, boolean isWrapReq, List<String> relations,
            List<String> columns, List<IndexExpression> conditions, int maxResults) throws Exception
    {
        SlicePredicate slicePredicate = new SlicePredicate();

        if (columns != null && !columns.isEmpty())
        {
            List asList = new ArrayList(32);
            for (String colName : columns)
            {
                if (colName != null)
                {
                    asList.add(UTF8Type.instance.decompose(colName));
                }
            }
            slicePredicate.setColumn_names(asList);
        }
        else
        {
            SliceRange sliceRange = new SliceRange();
            sliceRange.setStart(ByteBufferUtil.EMPTY_BYTE_BUFFER);
            sliceRange.setFinish(ByteBufferUtil.EMPTY_BYTE_BUFFER);
            slicePredicate.setSlice_range(sliceRange);
        }

        KeyRange keyRange = new KeyRange(maxResults);
        keyRange.setStart_key(minVal == null ? "".getBytes() : minVal);
        keyRange.setEnd_key(maxVal == null ? "".getBytes() : maxVal);
        ColumnParent cp = new ColumnParent(m.getTableName());

        if (conditions != null && !conditions.isEmpty())
        {
            keyRange.setRow_filter(conditions);
            keyRange.setRow_filterIsSet(true);
        }

        Connection conn = getConnection();

        List<KeySlice> keys = conn.getClient().get_range_slices(cp, slicePredicate, keyRange, getConsistencyLevel());

        releaseConnection(conn);

        List results = null;
        if (keys != null)
        {
            results = populateEntitiesFromKeySlices(m, isWrapReq, relations, keys, dataHandler);
        }
        return results;
    }
21132
public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
            Object columnValue, Class entityClazz)
    {
        // TODO Auto-generated method stub
        return null;
    }
1011920
public Dateitem findMatchingItem(DateRange range) {
        for (BaseComponent item : getChildren()) {
            if (range.equals(item.getData())) {
                return (Dateitem) item;
            }
        }
        
        return null;
    }
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;
    }
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);
        }

    }
132811
public <E> List<E> findData(EntityMetadata m, Object rowKey, byte[] startRow, byte[] endRow,
            List<Map<String, Object>> columnsToOutput, Filter filters)
    {
        String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());
        FilterList filterList = getFilterList(filters);
        try
        {
            return handler.readData(tableName, m, rowKey, startRow, endRow, columnsToOutput, filterList);
        }
        catch (IOException ioex)
        {
            log.error("Error during find by range, Caused by: .", ioex);
            throw new KunderaException("Error during find by range, Caused by: .", ioex);
        }
    }
775967
@Transactional
    public int findCount(E entity, SearchParameters sp) {
        checkNotNull(entity, "The entity cannot be null");
        checkNotNull(sp, "The searchParameters cannot be null");

        if (sp.hasNamedQuery()) {
            return byNamedQueryUtil.numberByNamedQuery(sp).intValue();
        }
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();

        CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
        Root<E> root = criteriaQuery.from(type);

        if (sp.getDistinct()) {
            criteriaQuery = criteriaQuery.select(builder.countDistinct(root));
        } else {
            criteriaQuery = criteriaQuery.select(builder.count(root));
        }

        // predicate
        Predicate predicate = getPredicate(criteriaQuery, root, builder, entity, sp);
        if (predicate != null) {
            criteriaQuery = criteriaQuery.where(predicate);
        }

        // construct order by to fetch or joins if needed
        orderByUtil.buildJpaOrders(sp.getOrders(), root, builder, sp);

        TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery);

        applyCacheHints(typedQuery, sp);
        return typedQuery.getSingleResult().intValue();
    }
643334
private void searchAndAddToResults(EntityMetadata m, String persistenceUnit, ConsistencyLevel consistencyLevel,
            String columnFamilyName, List<SearchResult> searchResults, IndexExpression expression, boolean isRowKeyQuery)
    {
        SearchResult searchResult = new SearchResult();

        byte[] superColumnName = expression.getValue();
        String superColumnNameStr = null;
        String rowKey = null;
        try
        {
            rowKey = ByteBufferUtil.string(ByteBuffer.wrap(expression.getColumn_name()),
                    Charset.forName(Constants.CHARSET_UTF8));
            superColumnNameStr = new String(expression.getValue(), Charset.forName(Constants.CHARSET_UTF8));
        }
        catch (CharacterCodingException e)
        {
            log.error("Error while retrieving records {}, Caused by:", e);
            throw new PersistenceException(e);
        }
        Object pk = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), superColumnName);
        IndexOperator condition = expression.getOp();

        if (log.isInfoEnabled())
        {
            log.info("RowKey: {} ; Super column Name: {} on condition.", rowKey, superColumnNameStr, condition);
        }

        // TODO: Second check unnecessary but unavoidable as filter clause
        // property is incorrectly passed as column name

        // Search based on Primary key
        if (isRowKeyQuery
                && (rowKey.equals(m.getIdAttribute().getName()) || rowKey.equals(((DefaultSingularAttribute) m
                        .getIdAttribute()).getJPAColumnName())))
        {
            if (searchResults.isEmpty())
            {
                searchResult.setPrimaryKey(pk);
                searchResults.add(searchResult);
            }
            else
            {
                SearchResult existing = searchResults.get(0);
                if (existing.getPrimaryKey() != null && existing.getPrimaryKey().equals(superColumnNameStr))
                {
                    searchResults.add(searchResult);
                }
                else
                {
                    searchResults.remove(0);
                }
            }
        }
        else
        {
            // Search results in the form of thrift super columns
            List<SuperColumn> thriftSuperColumns = new ArrayList<SuperColumn>();

            switch (condition)
            {
            // EQUAL Operator
            case EQ:
                SuperColumn thriftSuperColumn = getSuperColumnForRow(consistencyLevel, columnFamilyName, rowKey,
                        superColumnName, persistenceUnit);

                if (thriftSuperColumn != null)
                    thriftSuperColumns.add(thriftSuperColumn);
                break;

            // LIKE operation not available
            // Greater than operator
            case GT:
                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,
                        thriftSuperColumns, superColumnName, new byte[0]);
                break;
            // Less than Operator
            case LT:
                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,
                        thriftSuperColumns, new byte[0], superColumnName);
                break;
            // Greater than-equals to operator
            case GTE:
                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,
                        thriftSuperColumns, superColumnName, new byte[0]);
                break;
            // Less than equal to operator
            case LTE:
                searchSuperColumnsInRange(columnFamilyName, consistencyLevel, persistenceUnit, rowKey, superColumnName,
                        thriftSuperColumns, new byte[0], superColumnName);
                break;

            default:
                throw new QueryHandlerException(condition
                        + " comparison operator not supported currently for Cassandra Inverted Index.");
            }

            // Construct search results out of these thrift columns
            for (SuperColumn thriftSuperColumn : thriftSuperColumns)
            {

                for (Column column : thriftSuperColumn.getColumns())
                {
                    byte[] columnName = column.getName();
                    searchResult.setPrimaryKey(PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(),
                            columnName));
                    byte[] columnValue = column.getValue();
                    String ecValue = UTF8Type.instance.compose(ByteBuffer.wrap(columnValue));

                    if (ecValue != null && !"".equals(ecValue.trim()))
                    {
                        searchResult.setEmbeddedColumnName(rowKey.substring(0,
                                rowKey.indexOf(Constants.INDEX_TABLE_ROW_KEY_DELIMITER)));
                        searchResult.addEmbeddedColumnValue(ecValue);
                    }
                }

                if (searchResults.isEmpty())
                {
                    searchResults.add(searchResult);
                }
                else
                {
                    SearchResult existing = searchResults.get(0);
                    if (existing.getPrimaryKey() != null
                            && existing.getPrimaryKey().equals(searchResult.getPrimaryKey()))
                    {
                        searchResults.add(searchResult);
                    }
                    else
                    {
                        searchResults.remove(0);
                    }
                }

            }
        }
    }
572757
@Override
    public <E> List<E> getColumnsById(String schemaName, String joinTableName, String joinColumnName,
            String inverseJoinColumnName, Object parentId, Class columnJavaType)
    {
        List<Object> foreignKeys = new ArrayList<Object>();

        if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0))
        {
            foreignKeys = getColumnsByIdUsingCql(schemaName, joinTableName, joinColumnName, inverseJoinColumnName,
                    parentId, columnJavaType);
        }
        else
        {
            Selector selector = clientFactory.getSelector(pool);

            List<Column> columns = selector.getColumnsFromRow(joinTableName,
                    Bytes.fromByteArray(PropertyAccessorHelper.getBytes(parentId)),
                    Selector.newColumnsPredicateAll(true, 10), getConsistencyLevel());

            foreignKeys = dataHandler.getForeignKeysFromJoinTable(inverseJoinColumnName, columns, columnJavaType);

            if (log.isInfoEnabled())
            {
                log.info("Returning number of keys from join table", foreignKeys != null ? foreignKeys.size() : null);
            }
        }
        return (List<E>) foreignKeys;
    }
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;
    }
1309506
public <T> List<Entity> find(String field, T value) throws SQLException {
		return this.find(Entity.create(tableName).set(field, value));
	}
668564
@Override
    public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());
        String columnFamilyName = m.getTableName();
        byte[] valueInBytes = HBaseUtils.getBytes(colValue);
        SingleColumnValueFilter filter = new SingleColumnValueFilter(Bytes.toBytes(columnFamilyName),
                Bytes.toBytes(colName), CompareOp.EQUAL, valueInBytes);
        filter.setFilterIfMissing(true);
        try
        {
            return ((HBaseDataHandler) handler).readData(tableName, m, null, null, null, null, getFilterList(filter));
        }
        catch (IOException ex)
        {
            log.error("Error during find By Relation, Caused by: .", ex);
            throw new KunderaException("Error during find By Relation, Caused by: .", ex);
        }
    }
909988
@Override
    public <E> List<E> getColumnsById(String schemaName, String tableName, String pKeyColumnName,
            String inverseJoinColumnName, Object pKeyColumnValue, Class columnJavaType)
    {
        List<E> foreignKeys = new ArrayList<E>();

        URI uri = null;
        HttpResponse response = null;
        try
        {
            String q = "key=" + CouchDBUtils.appendQuotes(pKeyColumnValue);
            uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                    CouchDBConstants.URL_SEPARATOR + schemaName.toLowerCase() + CouchDBConstants.URL_SEPARATOR
                            + CouchDBConstants.DESIGN + tableName + CouchDBConstants.VIEW + pKeyColumnName, q, null);
            HttpGet get = new HttpGet(uri);
            get.addHeader("Accept", "application/json");
            response = httpClient.execute(get);

            InputStream content = response.getEntity().getContent();
            Reader reader = new InputStreamReader(content);
            JsonObject json = gson.fromJson(reader, JsonObject.class);

            JsonElement jsonElement = json.get("rows");

            if (jsonElement == null)
            {
                return foreignKeys;
            }

            JsonArray array = jsonElement.getAsJsonArray();
            for (JsonElement element : array)
            {
                JsonElement value = element.getAsJsonObject().get("value").getAsJsonObject().get(inverseJoinColumnName);
                if (value != null)
                {
                    foreignKeys.add((E) PropertyAccessorHelper.fromSourceToTargetClass(columnJavaType, String.class,
                            value.getAsString()));
                }
            }
        }
        catch (Exception e)
        {
            log.error("Error while fetching column by id {}, Caused by {}.", pKeyColumnValue, e);
            throw new KunderaException(e);
        }
        finally
        {
            closeContent(response);
        }
        return foreignKeys;
    }
63064
@Override
    public List<Person> findByQuery(String query) {
        //@formatter:off
        String queryStr = '%' + query.toLowerCase() + '%';
        String jpaQuery = "select e from Person e "
                + " where lower(e.firstname) like :query"
                + " or lower(e.lastname) like :query"
                + " or lower(e.address.city) like :query"
                + " or lower(e.address.street) like :query"
                + " or lower(e.address.postalCode) like :query";

        return entityManager
                .createQuery(jpaQuery, Person.class)
                .setParameter("query", queryStr)
                .getResultList();
        //@formatter:on
    }
1163723
@SuppressWarnings("unchecked")
	public <T> List<T> find(String riakQuery, Class<T> entity) {
		if (entity == null) {
			throw new ApitraryOrmException("Cannot access null entity");
		}
		log.debug("Searching " + entity.getName() + " " + riakQuery);

		QueriedGetRequest request = new QueriedGetRequest();
		request.setEntity(resolveApitraryEntity(entity));
		request.setQuery(riakQuery);
		QueriedGetResponse response = resolveApitraryClient().send(request);

		return (List<T>) new QueriedGetResponseUnmarshaller(this).unMarshall(response, entity);
	}
556467
public List<Object> findByRelation(String colName, Object colValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
        // you got column name and column value.
        DBCollection dbCollection = mongoDb.getCollection(m.getTableName());

        BasicDBObject query = new BasicDBObject();

        query.put(colName, MongoDBUtils.populateValue(colValue, colValue.getClass()));
        KunderaCoreUtils.printQuery("Find by relation:" + query, showQuery);
        DBCursor cursor = dbCollection.find(query);
        DBObject fetchedDocument = null;
        List<Object> results = new ArrayList<Object>();
        while (cursor.hasNext())
        {
            fetchedDocument = cursor.next();
            populateEntity(m, results, fetchedDocument);
        }

        return results.isEmpty() ? null : results;
    }
880338
private Object[] findIdsByColumn(String tableName, String columnName, Object columnValue)
    {
        Object connection = null;

        try
        {
            connection = getConnection();
            String valueAsStr = PropertyAccessorHelper.getString(columnValue);

            Set<String> results = null;

            if (resource != null && resource.isActive())
            {
                Response response = ((Transaction) connection).zrangeByScore(getHashKey(tableName, columnName),
                        getDouble(valueAsStr), getDouble(valueAsStr));
                // ((Transaction) connection).exec();
                ((RedisTransaction) resource).onExecute(((Transaction) connection));

                results = (Set<String>) response.get();
            }
            else
            {
                results = ((Jedis) connection).zrangeByScore(getHashKey(tableName, columnName), getDouble(valueAsStr),
                        getDouble(valueAsStr));

            }
            if (results != null)
            {
                return results.toArray(new Object[0]);
            }

        }
        finally
        {
            onCleanup(connection);
        }

        return null;
    }