Creates MongoDB Query object from filterClauseQueue.

@param m
the m
@param filterClauseQueue
the filter clause queue
@return the basic db object
422301
public BasicDBObject createSubMongoQuery(EntityMetadata m, Queue filterClauseQueue)
    {
        BasicDBObject query = new BasicDBObject();
        BasicDBObject compositeColumns = new BasicDBObject();

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

        AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(m.getEntityClazz());

        for (Object object : filterClauseQueue)
        {
            boolean isCompositeColumn = false;

            boolean isSubCondition = false;

            if (object instanceof FilterClause)
            {
                FilterClause filter = (FilterClause) object;
                String property = filter.getProperty();
                String condition = filter.getCondition();
                boolean ignoreCase = filter.isIgnoreCase();

                Object value;
                if (filter.getValue().size() == 1)
                {
                    value = filter.getValue().get(0);
                }
                else
                {
                    value = filter.getValue();
                }

                // value is string but field.getType is different, then get
                // value using

                Field f = null;

                // if alias is still present .. means it is an enclosing
                // document search.

                if (managedType.hasLobAttribute())
                {
                    EntityType entity = metaModel.entity(m.getEntityClazz());
                    String fieldName = m.getFieldName(property);

                    f = (Field) entity.getAttribute(fieldName).getJavaMember();

                    if (value != null)
                    {
                        if (value.getClass().isAssignableFrom(String.class) && f != null
                                && !f.getType().equals(value.getClass()))
                        {
                            value = PropertyAccessorFactory.getPropertyAccessor(f).fromString(f.getType().getClass(),
                                    value.toString());
                        }
                        value = MongoDBUtils.populateValue(value, value.getClass());
                    }

                    property = "metadata." + property;
                }
                else
                {
                    if (((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equalsIgnoreCase(property))
                    {
                        if (value != null)
                        {
                            property = "_id";
                            f = (Field) m.getIdAttribute().getJavaMember();
                            if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())
                                    && value.getClass().isAssignableFrom(f.getType()))
                            {
                                EmbeddableType compoundKey = metaModel
                                        .embeddable(m.getIdAttribute().getBindableJavaType());
                                compositeColumns = MongoDBUtils.getCompoundKeyColumns(m, value, compoundKey, metaModel);
                                isCompositeColumn = true;
                                continue;
                            }
                        }
                    }
                    else if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())
                            && StringUtils.contains(property, '.'))
                    {
                        // Means it is a case of composite column.
                        property = property.substring(property.indexOf(".") + 1);
                        isCompositeColumn = true;
                    } /*
                       * if a composite key. "." assuming "." is part of
                       * property in case of embeddable only
                       */
                    else if (StringUtils.contains(property, '.'))
                    {
                        EntityType entity = metaModel.entity(m.getEntityClazz());
                        StringTokenizer tokenizer = new StringTokenizer(property, ".");
                        String embeddedAttributeAsStr = tokenizer.nextToken();
                        String embeddableAttributeAsStr = tokenizer.nextToken();
                        Attribute embeddedAttribute = entity.getAttribute(embeddedAttributeAsStr);

                        if (embeddedAttribute.isAssociation())
                        {
                            Relation relation = m.getRelation(embeddedAttributeAsStr);
                            f = relation.getProperty();

                            AbstractAttribute targetAttribute = (AbstractAttribute) metaModel
                                    .entity(relation.getTargetEntity()).getAttribute(embeddableAttributeAsStr);
                            String targetColumnName = targetAttribute.getJPAColumnName();

                            if (targetAttribute instanceof DefaultSingularAttribute
                                    && ((DefaultSingularAttribute) targetAttribute).isId())
                            {
                                property = relation.getJoinColumnName(kunderaMetadata);
                            }
                            else
                            {
                                property = embeddedAttributeAsStr + "." + targetColumnName;
                            }
                        }
                        else
                        {
                            EmbeddableType embeddableEntity = metaModel
                                    .embeddable(((AbstractAttribute) embeddedAttribute).getBindableJavaType());
                            f = (Field) embeddableEntity.getAttribute(embeddableAttributeAsStr).getJavaMember();
                            property = ((AbstractAttribute) embeddedAttribute).getJPAColumnName() + "."
                                    + ((AbstractAttribute) embeddableEntity.getAttribute(embeddableAttributeAsStr))
                                            .getJPAColumnName();
                        }
                    }
                    else
                    {
                        EntityType entity = metaModel.entity(m.getEntityClazz());
                        String discriminatorColumn = ((AbstractManagedType) entity).getDiscriminatorColumn();

                        if (!property.equals(discriminatorColumn))
                        {
                            String fieldName = m.getFieldName(property);
                            f = (Field) entity.getAttribute(fieldName).getJavaMember();
                        }
                    }

                    if (value != null)
                    {
                        if (value.getClass().isAssignableFrom(String.class) && f != null
                                && !f.getType().equals(value.getClass()))
                        {
                            value = PropertyAccessorFactory.getPropertyAccessor(f).fromString(f.getType(),
                                    value.toString());
                        }
                        value = MongoDBUtils.populateValue(value, value.getClass());
                    }

                }

                // Property, if doesn't exist in entity, may be there in a
                // document embedded within it, so we have to check that
                // TODO: Query should actually be in a format
                // documentName.embeddedDocumentName.column, remove below if
                // block once this is decided

                // Query could be geospatial in nature
                if (f != null && f.getType().equals(Point.class))
                {
                    GeospatialQuery geospatialQueryimpl = GeospatialQueryFactory
                            .getGeospatialQueryImplementor(condition, value);
                    query = (BasicDBObject) geospatialQueryimpl.createGeospatialQuery(property, value, query);

                }
                else
                {

                    if (isCompositeColumn)
                    {
                        EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());
                        AbstractAttribute attribute = (AbstractAttribute) embeddableType.getAttribute(property);

                        property = new StringBuffer("_id.").append(attribute.getJPAColumnName()).toString();
                    }

                    if (ignoreCase)
                    {
                        // let 'like' and 'not like' take care of this on its
                        // own
                        if (!condition.equalsIgnoreCase("like") && !condition.equalsIgnoreCase("not like"))
                        {

                            if (value instanceof String)
                            {
                                value = Pattern.compile(createLikeRegex((String) value, ignoreCase));

                            }
                            else if (value instanceof Collection)
                            {
                                Collection<?> original = (Collection<?>) value;
                                List<Pattern> values = new ArrayList<Pattern>(original.size());

                                for (Object item : original)
                                {
                                    values.add(Pattern.compile(createLikeRegex((String) item, ignoreCase)));
                                }

                                value = values;

                            }
                        }
                    }

                    if (condition.equals("="))
                    {

                        if (query.containsField(property))
                        {
                            appendToQuery(query, property, "$eq", value);
                        }
                        else
                        {
                            query.append(property, value);
                        }

                    }
                    else if (condition.equalsIgnoreCase("is null"))
                    {
                        if (query.containsField(property))
                        {
                            appendToQuery(query, property, "$eq", null);
                        }
                        else
                        {
                            query.append(property, null);
                        }
                    }
                    else if (condition.toLowerCase().contains("like"))
                    {

                        Pattern regEx = Pattern.compile(createLikeRegex((String) value, ignoreCase));
                        boolean negative = condition.toLowerCase().contains("not");

                        appendToQuery(query, property, negative ? "$not" : "$regex", regEx);

                    }
                    else if (condition.equalsIgnoreCase(">"))
                    {

                        appendToQuery(query, property, "$gt", value);

                    }
                    else if (condition.equalsIgnoreCase(">="))
                    {

                        appendToQuery(query, property, "$gte", value);

                    }
                    else if (condition.equalsIgnoreCase("<"))
                    {

                        appendToQuery(query, property, "$lt", value);

                    }
                    else if (condition.equalsIgnoreCase("<="))
                    {

                        appendToQuery(query, property, "$lte", value);

                    }
                    else if (condition.equalsIgnoreCase("in"))
                    {

                        if (value != null)
                        {
                            if (!value.getClass().isArray() && !(value instanceof Collection))
                            {
                                value = Collections.singletonList(value);
                            }
                        }

                        appendToQuery(query, property, "$in", value);

                    }
                    else if (condition.equalsIgnoreCase("not in"))
                    {

                        if (value != null)
                        {
                            if (!value.getClass().isArray() && !(value instanceof Collection))
                            {
                                value = Collections.singletonList(value);
                            }
                        }

                        appendToQuery(query, property, "$nin", value);

                    }
                    else if (condition.equalsIgnoreCase("<>"))
                    {

                        String operator = value instanceof Pattern ? "$not" : "$ne";

                        appendToQuery(query, property, operator, value);

                    }
                    else if (condition.equalsIgnoreCase("is not null"))
                    {

                        appendToQuery(query, property, "$not", null);

                    }
                }

                // TODO: Add support for other operators like >, <, >=, <=,
                // order by asc/ desc, limit, skip, count etc
            }
        }
        if (!compositeColumns.isEmpty())
        {
            query.append("_id", compositeColumns);
        }

        return query;
    }
887497
public Query<S> query(Filter<S> filter, OrderingList<S> ordering, QueryHints hints)
        throws FetchException
    {
        filter = filter.bind();

        Map<OrderingList<S>, Query<S>> map;
        synchronized (mFilterToQuery) {
            map = mFilterToQuery.get(filter);
            if (map == null) {
                if (filter == null) {
                    throw new IllegalArgumentException("Query filter must not be null");
                }
                map = new SoftValuedHashMap(7);
                mFilterToQuery.put(filter, map);
            }
        }

        Query<S> query;
        synchronized (map) {
            query = map.get(ordering);
            if (query == null) {
                FilterValues<S> values = filter.initialFilterValues();
                if (values == null && filter.isClosed()) {
                    query = new EmptyQuery<S>(this, ordering);
                } else {
                    StandardQuery<S> standardQuery = createQuery(filter, values, ordering, hints);
                    if (!mLazySetExecutor) {
                        try {
                            standardQuery.setExecutor();
                        } catch (RepositoryException e) {
                            throw e.toFetchException();
                        }
                    }
                    query = standardQuery;
                }
                map.put(ordering, query);
            }
        }

        return query;
    }
296822
public TypedQuery<T> select(Filter filter, OrderBy orderBy) {
        CriteriaQuery<T> query = cb.createQuery(getEntityClass());
        Root<T> from = query.from(getEntityClass());

        CriteriaMapper criteriaMapper = new CriteriaMapper(from, cb);

        if (orderBy != null) {
            query.orderBy(criteriaMapper.create(orderBy));
        }
        if (filter != null) {
            query.where(criteriaMapper.create(filter));
        }

        return getEntityManager().createQuery(query);
    }
275030
public static SearchFilter newSearchFilter(final String filterQuery, final String... params) {
        final SearchFilter filter = new SearchFilter();
        filter.setFilter(filterQuery);
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                if (filter.getFilter().contains("{" + i + "}")) {
                    filter.setParameter(i, params[i]);
                } else {
                    filter.setParameter("user", params[i]);
                }
            }
        }
        LOGGER.debug("Constructed LDAP search filter [{}]", filter.format());
        return filter;
    }
655770
@Override
    public Set<QueryableEntry<K, V>> filter(QueryContext queryContext) {
        if (!(predicate instanceof IndexAwarePredicate)) {
            return null;
        }

        Set<QueryableEntry<K, V>> set = ((IndexAwarePredicate<K, V>) predicate).filter(queryContext);
        if (set == null || set.isEmpty()) {
            return set;
        }
        List<QueryableEntry<K, V>> resultList = new ArrayList<QueryableEntry<K, V>>();
        Map.Entry<Integer, Map.Entry> nearestAnchorEntry = getNearestAnchorEntry();
        for (QueryableEntry<K, V> queryableEntry : set) {
            if (SortingUtil.compareAnchor(this, queryableEntry, nearestAnchorEntry)) {
                resultList.add(queryableEntry);
            }
        }

        List<QueryableEntry<K, V>> sortedSubList =
                (List) SortingUtil.getSortedSubList((List) resultList, this, nearestAnchorEntry);
        return new LinkedHashSet<QueryableEntry<K, V>>(sortedSubList);
    }
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);
        }
    }
1318657
private DBCursor parseAndScroll(String jsonClause, String collectionName) throws JSONParseException
    {
        BasicDBObject clause = (BasicDBObject) JSON.parse(jsonClause);
        DBCursor cursor = mongoDb.getCollection(collectionName).find(clause);
        return cursor;
    }
852550
function filter(mMap, fnFilter) {
			return Object.keys(mMap).filter(fnFilter).reduce(copyTo.bind(mMap), {});
		}
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;
    }
537082
public List executeNativeQuery(String jsonClause, EntityMetadata entityMetadata)
    {
        List entities = new ArrayList();
        String[] tempArray = jsonClause.split("\\.");
        String tempClause = tempArray[tempArray.length - 1];

        if (tempClause.contains("findOne(") || tempClause.contains("findAndModify("))
        {
            DBObject obj = (BasicDBObject) executeScript(jsonClause);
            populateEntity(entityMetadata, entities, obj);
            return entities;

        }
        else if (tempClause.contains("find(") || jsonClause.contains("aggregate("))
        {
            jsonClause = jsonClause.concat(".toArray()");
            BasicDBList list = (BasicDBList) executeScript(jsonClause);
            for (Object obj : list)
            {
                populateEntity(entityMetadata, entities, (DBObject) obj);
            }
            return entities;

        }
        else if (tempClause.contains("count(") || tempClause.contains("dataSize(")
                || tempClause.contains("storageSize(") || tempClause.contains("totalIndexSize(")
                || tempClause.contains("totalSize("))
        {
            Long count = ((Double) executeScript(jsonClause)).longValue();
            entities.add(count);
            return entities;

        }
        else if (tempClause.contains("distinct("))
        {
            BasicDBList list = (BasicDBList) executeScript(jsonClause);
            for (Object obj : list)
            {
                entities.add(obj);
            }
            return entities;

        }
        else if (jsonClause.contains("mapReduce("))
        {
            final MapReduceCommand command = parseMapReduceCommand(jsonClause);
            final MapReduceOutput output = mongoDb.getCollection(command.getInput()).mapReduce(command);

            final BasicDBList list = new BasicDBList();
            for (final DBObject item : output.results())
            {
                list.add(item);
            }
            return list;
        }
        else
        {
            BasicDBList list = (BasicDBList) executeScript(jsonClause);
            for (Object obj : list)
            {
                entities.add(obj);
            }
            return entities;
        }
    }
335281
private void onQuery(EntityMetadata m, Client client)
    {

        try
        {
            // Called only in case of standalone entity.
            FilterList filter = null;
            if (translator.getFilter() != null)
            {
                filter = new FilterList(translator.getFilter());
            }
            String[] columnAsArr = getColumnsAsArray();

            if (isFindKeyOnly(m, columnAsArr))
            {
                this.handler.setFilter(new KeyOnlyFilter());
            }

            if (filter == null && columns != null)
            {
                handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),
                        translator.getEndRow(), columnAsArr, null);
            }
            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                if (filter == null)
                {
                    // means complete scan without where clause, scan all
                    // records.
                    // findAll.
                    if (translator.isRangeScan())
                    {
                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),
                                translator.getEndRow(), columnAsArr, null);
                    }
                    else
                    {
                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, null, null, columnAsArr, null);
                    }
                }
                else
                {
                    // means WHERE clause is present.
                    if (translator.isRangeScan())
                    {
                        handler.readDataByRange(m.getSchema(), m.getEntityClazz(), m, translator.getStartRow(),
                                translator.getEndRow(), columnAsArr, filter);
                    }
                    else
                    {
                        // if range query. means query over id column. create
                        // range
                        // scan method.

                        handler.readData(m.getSchema(), entityMetadata.getEntityClazz(), entityMetadata, null,
                                m.getRelationNames(), filter, columnAsArr);
                    }
                }
            }
        }
        catch (IOException ioex)
        {
            log.error("Error while executing query{} , Caused by:", ioex);
            throw new QueryHandlerException("Error while executing , Caused by:", ioex);
        }
    }
723973
public static List<Map<String, Object>> readSelectClause(Expression selectExpression, EntityMetadata m,
            Boolean useLuceneOrES, KunderaMetadata kunderaMetadata)
    {
        List<Map<String, Object>> columnsToOutput = new ArrayList<Map<String, Object>>();
        if (StateFieldPathExpression.class.isAssignableFrom(selectExpression.getClass()))
        {
            Expression sfpExp = selectExpression;

            addToOutputColumns(selectExpression, m, columnsToOutput, kunderaMetadata);
        }
        else if (CollectionExpression.class.isAssignableFrom(selectExpression.getClass()))
        {
            CollectionExpression collExp = (CollectionExpression) selectExpression;
            ListIterator<Expression> itr = collExp.children().iterator();
            while (itr.hasNext())
            {
                Expression exp = itr.next();
                if (StateFieldPathExpression.class.isAssignableFrom(exp.getClass()))
                {
                    addToOutputColumns(exp, m, columnsToOutput, kunderaMetadata);
                }
            }
        }
        return columnsToOutput;
    }
961262
public static SearchExecutor newLdaptiveSearchExecutor(final String baseDn, final String filterQuery) {
        return newLdaptiveSearchExecutor(baseDn, filterQuery, new ArrayList<>(0));
    }
22780
public Query<S> query(Filter<S> filter) throws FetchException {
        return query(filter, null);
    }
1119720
@Override
    protected List findUsingLucene(EntityMetadata m, Client client)
    {
        try
        {
            BasicDBObject orderByClause = getOrderByClause(m);
            // find on id, so no need to add skip() [firstResult hardcoded 0]
            return ((MongoDBClient) client).loadData(m, createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()),
                    null, orderByClause, isSingleResult ? 1 : maxResult, 0, isCountQuery(),
                    getKeys(m, getKunderaQuery().getResult()), getKunderaQuery().getResult());
        }
        catch (Exception e)
        {
            log.error("Error during executing query, Caused by:", e);
            throw new QueryHandlerException(e);
        }

    }
416198
function (db, index, whereClause, sortBys, cb) {
			var query = encodeURIComponent(whereClause);
			var url = host +
				'databases/' + db +
				'/indexes/' + index +
				'?query=' + query +
				'&operator=AND&pageSize=0&start=0';
			var urlPartSort = sortBys.map(function (prop) {
				return '&sort=' + prop;
			}).join('');
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					var pageSize = 1024;
					var stats = _.reduce(result, function (memo, value, key) {
						if (key !== "Results") {
							memo[key] = value;
						}
						return memo;
					}, {});
					var totalResults = stats.TotalResults;
					var pageCount = parseInt(totalResults / pageSize);
					var delta = totalResults - pageCount * pageSize;
					if (delta > 0)
						pageCount++;
					var requests = [];
					for (var i = 0; i < pageCount; i++) {
						requests.push({
							Url: '/indexes/' + index,
							Query: 'start=' + i * pageSize + '&pageSize=' + pageSize + '&query=' + query + urlPartSort
						});
					}
					var multiGetBody = JSON.stringify(requests);
					var multiGetUrl = host + 'databases/' + db + '/multi_get';
					request.post({
							url: multiGetUrl,
							body: multiGetBody
						},
						function (err, resp, multiGetResponseBody) {
							if (!err && resp.statusCode === 200) {
								var multiGetResponse = JSON.parse(multiGetResponseBody);
								var results =
									_.flatten(_.reduce(multiGetResponse
										, function (memo, val) {
											if (val.Result && val.Result.Results)
												memo.push(val.Result.Results);
											return memo;
										}
										, []));
								cb(null, results);
							} else {
								cb(err || new Error(resp.statusCode), null);
							}
						});
				}
				else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		}
843484
public NetworkFilter where(Predicate<NetworkMetadata> filter) {
        checkNotNull(filter, "Filter predicate must be not a null");

        this.predicate = this.predicate.and(filter);

        return this;
    }