Populate logical filter builder.

@param logicalExp
the logical exp
@param m
the m
@param entity
the entity
@return the filter builder
355775
private QueryBuilder populateLogicalFilterBuilder(Expression logicalExp, EntityMetadata m)
    {
        String identifier = ((LogicalExpression) logicalExp).getIdentifier();

        return (identifier.equalsIgnoreCase(LogicalExpression.AND)) ? getAndFilterBuilder(logicalExp, m) : (identifier
                .equalsIgnoreCase(LogicalExpression.OR)) ? getOrFilterBuilder(logicalExp, m) : null;
    }
932598
public void buildSetClause(EntityMetadata m, StringBuilder builder, String property, Object value)
    {
        builder = ensureCase(builder, property, false);
        builder.append(EQ_CLAUSE);

        if (m.isCounterColumnType())
        {
            builder = ensureCase(builder, property, false);
            builder.append(INCR_COUNTER);
            builder.append(value);
        }
        else
        {
            appendValue(builder, value.getClass(), value, false, false);
        }

        builder.append(COMMA_STR);
    }
644801
private static void addOrder(PersistentEntity entity,
                                 CriteriaQuery query,
                                 From queryRoot,
                                 CriteriaBuilder criteriaBuilder,
                                 String sort, String order, boolean ignoreCase) {
        if (sort.equalsIgnoreCase(entity.getIdentity().getName())) {
            Expression path = queryRoot;

            if (ignoreCase) {
                path = criteriaBuilder.upper(path);
            }
            if (DynamicFinder.ORDER_DESC.equals(order)) {
                query.orderBy(criteriaBuilder.desc(path));
            } else {
                query.orderBy(criteriaBuilder.asc(path));
            }
        } else {
            Expression path = queryRoot.get(sort);

            if (ignoreCase) {
                path = criteriaBuilder.upper(path);
            }
            if (DynamicFinder.ORDER_DESC.equals(order)) {
                query.orderBy(criteriaBuilder.desc(path));
            } else {
                query.orderBy(criteriaBuilder.asc(path));
            }
        }
    }
727392
private CouchDBQueryInterpreter onTranslation(Queue clauseQueue, EntityMetadata m)
    {

        CouchDBQueryInterpreter interpreter = new CouchDBQueryInterpreter(getColumns(getKunderaQuery().getResult(), m),
                getMaxResults(), m);
        interpreter.setColumnsToOutput(getColumnsToOutput(m, kunderaQuery));
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());

        EntityType entity = metaModel.entity(m.getEntityClazz());
        if (getKunderaQuery().isAggregated() && !useLuceneOrES)
        {
            return onAggregatedQuery(m, interpreter, getKunderaQuery());
        }
        // If there is no clause present, means we might need to scan complete
        // table.
        /**
         * TODOOOO: Create a sorted set with table name. and add row key as
         * score and value on persist. delete it out as well on delete call.
         */
        for (Object clause : clauseQueue)
        {
            if (clause.getClass().isAssignableFrom(FilterClause.class))
            {
                Object value = ((FilterClause) clause).getValue().get(0);
                String condition = ((FilterClause) clause).getCondition();
                String columnName = ((FilterClause) clause).getProperty();

                int indexOfDot = columnName.indexOf(".");
                if (indexOfDot >= 0)
                {
                    EmbeddableType embeddableType = metaModel.embeddable(m.getIdAttribute().getBindableJavaType());
                    String embeddedeFieldName = columnName.substring(0, indexOfDot);
                    if (embeddedeFieldName.equals(((AbstractAttribute) m.getIdAttribute()).getName()))
                    {
                        interpreter.setQueryOnCompositeKey(true);
                        interpreter.setKeyName(embeddedeFieldName);
                        String colName = columnName.substring(indexOfDot + 1);
                        Attribute attribute = embeddableType.getAttribute(colName);
                        interpreter.setIdQuery(true);
                        interpreter.setKeyValues(
                                colName,
                                PropertyAccessorHelper.fromSourceToTargetClass(attribute.getJavaType(),
                                        value.getClass(), value));
                    }
                    else
                    {
                        log.error("Query on embedded column/any field of embedded column, is not supported in CouchDB");
                        throw new QueryHandlerException(
                                "Query on embedded column/any field of embedded column, is not supported in CouchDB");
                    }
                }
                else
                {
                    Attribute col = entity.getAttribute(m.getFieldName(columnName));
                    interpreter.setKeyValues(columnName,
                            PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(), value.getClass(), value));
                    interpreter.setKeyName(columnName);
                    if (columnName.equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName()))
                    {
                        interpreter.setIdQuery(true);
                    }

                    if (condition.equals("="))
                    {
                        interpreter.setKeyValue(PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(),
                                value.getClass(), value));
                    }
                    else if (condition.equals(">=") || condition.equals(">"))
                    {
                        interpreter.setStartKeyValue(PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(),
                                value.getClass(), value));
                    }
                    else if (condition.equals("<="))
                    {
                        interpreter.setEndKeyValue(PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(),
                                value.getClass(), value));
                    }
                    else if (condition.equals("<"))
                    {
                        interpreter.setEndKeyValue(PropertyAccessorHelper.fromSourceToTargetClass(col.getJavaType(),
                                value.getClass(), value));
                        interpreter.setIncludeLastKey(false);
                    }
                    else
                    {
                        log.error("Condition:" + condition + " not supported for CouchDB");
                        throw new QueryHandlerException("Condition:" + condition + " not supported for CouchDB");
                    }
                }
            }
            else
            {
                String opr = clause.toString().trim();

                if (interpreter.getOperator() == null)
                {
                    if (opr.equalsIgnoreCase("AND"))
                    {
                        interpreter.setOperator("AND");
                    }
                    else if (opr.equalsIgnoreCase("OR"))
                    {
                        log.error("Condition: OR not supported in CouchDB");
                        throw new QueryHandlerException("Invalid intra clause OR is not supported in CouchDB");
                    }
                    else
                    {
                        log.error("Invalid intra clause:" + opr + " is not supported in CouchDB");
                        throw new QueryHandlerException("Invalid intra clause:" + opr + " not supported for CouchDB");
                    }
                }
                else if (interpreter.getOperator() != null && !interpreter.getOperator().equalsIgnoreCase(opr))
                {
                    log.error("Multiple combination of AND/OR clause not supported in CouchDB");
                    throw new QueryHandlerException("Multiple combination of AND/OR clause not supported in CouchDB");
                }
                // it is a case of "AND", "OR" clause
            }
        }
        return interpreter;
    }
678409
public static void populate(Object entity, Map<String, Object> params) {
    meta.getPopulator().populate(entity, meta.getEntityType(entity.getClass()), params);
  }
68466
@Override
    protected LogicalFilterWrapper appendAttributeToQuery(LogicalFilterWrapper queryBuilder, final String dataAttribute, final List<Object> queryValues) {
        if (queryBuilder == null) {
            queryBuilder = new LogicalFilterWrapper(this.queryType);
        }

        for (final Object queryValue : queryValues) {
            final String queryValueString = queryValue == null ? null : queryValue.toString();

            if (StringUtils.isNotBlank(queryValueString)) {
                final Filter filter;
                if (!queryValueString.contains("*")) {
                    filter = new EqualsFilter(dataAttribute, queryValueString);
                } else {
                    filter = new LikeFilter(dataAttribute, queryValueString);
                }

                queryBuilder.append(filter);
            }
        }

        return queryBuilder;
    }
1155723
@Override
    protected List recursivelyPopulateEntities(EntityMetadata m, Client client)
    {
        List<EnhanceEntity> ls = populateEntities(m, client);
        return setRelationEntities(ls, client, m);
    }
401219
@Override
	public boolean filter(Object entity) {
		for (Filter filter : filters) {
			if (filter.filter(entity)) {
				return true;
			}
		}

		return false;
	}
129386
private ReqlFunction1 parseAndBuildFilters(EntityType entityType, Expression whereExp)
    {
        if (whereExp instanceof ComparisonExpression)
        {
            String left = ((ComparisonExpression) whereExp).getLeftExpression().toActualText();

            String right = ((ComparisonExpression) whereExp).getRightExpression().toActualText();
            right = right.replaceAll("['\"]", "");
            if (right.startsWith(POSITIONAL_PREFIX) || right.startsWith(PARAMETERIZED_PREFIX))
            {
                right = kunderaQuery.getParametersMap().get(right) + "";
            }
            Attribute attribute = entityType.getAttribute(left.split(DOT_REGEX)[1]);
            boolean isId = ((Field) attribute.getJavaMember()).isAnnotationPresent(Id.class);
          
            return buildFunction(isId ? ID : ((AbstractAttribute) attribute).getJPAColumnName(),
                    ConvertUtils.convert(right, attribute.getJavaType()),
                    ((ComparisonExpression) whereExp).getActualIdentifier());
        }
        else
        {
            logger.error("Operation not supported");
            throw new KunderaException("Operation not supported");
        }
    }
1297318
public QueryBuilder populateFilterBuilder(Expression condtionalExp, EntityMetadata m)
    {
        log.info("Populating filter for expression: " + condtionalExp);
        QueryBuilder filter = null;

        if (condtionalExp instanceof SubExpression)
        {
            filter = populateFilterBuilder(((SubExpression) condtionalExp).getExpression(), m);
        }
        else if (condtionalExp instanceof ComparisonExpression)
        {
            filter = getFilter(populateFilterClause((ComparisonExpression) condtionalExp), m);
        }
        else if (condtionalExp instanceof BetweenExpression)
        {
            filter = populateBetweenFilter((BetweenExpression) condtionalExp, m);
        }
        else if (condtionalExp instanceof LogicalExpression)
        {
            filter = populateLogicalFilterBuilder(condtionalExp, m);
        }
        else if (condtionalExp instanceof LikeExpression)
        {
            filter = populateLikeQuery((LikeExpression) condtionalExp, m);
        }
        else if (condtionalExp instanceof InExpression)
        {
            filter = populateInQuery((InExpression) condtionalExp, m);
        }
        else
        {
            log.error(condtionalExp.toParsedText() + "found in where clause. Not supported in elasticsearch.");
            throw new KunderaException(condtionalExp.toParsedText() + " not supported in ElasticSearch");
        }

        log.debug("Following is the populated filter for required query: " + filter);
        return filter;
    }
1205861
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());
        EntityType entity = metaModel.entity(m.getEntityClazz());
        Expression whereExpression = KunderaQueryUtils.getWhereClause(kunderaQuery.getJpqlExpression());

        QueryBuilder filter = whereExpression == null || whereExpression instanceof NullExpression ? null
                : esFilterBuilder.populateFilterBuilder(((WhereClause) whereExpression).getConditionalExpression(), m);

        return ((ESClient) client).executeQuery(filter, buildAggregation(kunderaQuery, m, filter), m,
                getKunderaQuery(),this.firstResult, this.maxResult);
    }
428991
public function scopeFiltersApply(Builder $query, $entity = null): Builder
    {
        if (! is_null($entity)) {
            try {
                $this->getEntity($entity);
            } catch (EntityTypeException $e) {
            }
        }

        return $this->filter($query);
    }
1080379
public function getQueryBuilder(VictoireQueryInterface $containerEntity, EntityManager $em)
    {
        if ($containerEntity === null) {
            throw new \Exception('The container entity parameter must not be null.');
        }

        //the business name of the container entity
        $businessEntityId = $containerEntity->getBusinessEntityId();

        //test that there is a business entity name
        if ($businessEntityId === null || $businessEntityId === '') {
            $containerId = $containerEntity->getId();

            throw new \Exception('The container entity ['.$containerId.'] does not have any businessEntityId.');
        }

        //the business class of the container entity
        $businessEntity = $this->businessEntityHelper->findById(strtolower($businessEntityId));

        //test that there was a businessEntity
        if ($businessEntity === null) {
            throw new \Exception('The business entity was not found for the id:['.$businessEntityId.']');
        }

        $businessClass = $businessEntity->getClass();

        $itemsQueryBuilder = $em
            ->createQueryBuilder()
            ->select('main_item')
            ->from($businessClass, 'main_item')
            ->andWhere('main_item.visibleOnFront = 1');

        $view = null;
        if ($containerEntity instanceof View) {
            $view = $containerEntity;
        } elseif ($containerEntity instanceof Widget) {
            $view = $containerEntity->getCurrentView();
        }

        // when the businessClass is translatable, join translations for the current locale
        if ($view && in_array(Translatable::class, class_uses($businessClass))) {
            $itemsQueryBuilder->join('main_item.translations', 'translation')
                ->andWhere('translation.locale = :locale')
                ->setParameter(':locale', $view->getCurrentLocale());
        }

        $refClass = new \ReflectionClass($businessClass);
        if ($refClass->hasMethod('getDeletedAt')) {
            $itemsQueryBuilder->andWhere('main_item.deletedAt IS NULL');
        }

        return $itemsQueryBuilder;
    }
598990
public static Object initialize(EntityMetadata m, Object entity, Object id)
    {
        try
        {
            if (entity == null)
            {
                entity = createNewInstance(m.getEntityClazz());
            }
            if (id != null)
            {
                PropertyAccessorHelper.setId(entity, m, id);
            }
            return entity;
        }
        catch (Exception e)
        {
            throw new PersistenceException("Error occured while instantiating entity.", e);
        }
    }
333191
public static void onLogicalExpression(Expression expression, EntityMetadata m, KunderaMetadata kunderaMetadata,
            KunderaQuery kunderaQuery)
    {
        if (expression instanceof OrExpression)
        {
            kunderaQuery.addFilterClause("(");
        }

        traverse(((LogicalExpression) expression).getLeftExpression(), m, kunderaMetadata, kunderaQuery, false);

        if (expression instanceof OrExpression)
        {
            kunderaQuery.addFilterClause(")");
        }

        kunderaQuery.addFilterClause(((LogicalExpression) expression).getIdentifier());

        if (expression instanceof OrExpression)
        {
            kunderaQuery.addFilterClause("(");
        }

        traverse(((LogicalExpression) expression).getRightExpression(), m, kunderaMetadata, kunderaQuery, false);

        if (expression instanceof OrExpression)
        {
            kunderaQuery.addFilterClause(")");
        }
    }
173158
public BasicDBObject createMongoQuery(EntityMetadata m, Queue filterClauseQueue)
    {
        QueryComponent sq = getQueryComponent(filterClauseQueue);
        populateQueryComponents(m, sq);
        return sq.actualQuery == null ? new BasicDBObject() : sq.actualQuery;
    }
638789
private void generateDaoPart(M2MEntity entity) {
		String daoClassName = entity.daoName.simpleName();

		String daoPackageName = entity.daoName.packageName();
		String entityPackageName = entity.getPackageName();
		String generatedDaoClassName = "Generated" + daoClassName;

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDaoMany2Many.class, daoPackageName, generatedDaoClassName);
		// @formatter:off
		classBuilder = TypeSpec.interfaceBuilder(generatedDaoClassName).addModifiers(Modifier.PUBLIC)
				.addAnnotation(AnnotationSpec.builder(BindDao.class)
						.addMember("value", "$T.class", TypeUtility.className(entityPackageName, entity.name)).build())
				.addAnnotation(AnnotationSpec.builder(BindGeneratedDao.class)
						.addMember("dao", "$T.class", entity.daoName).build())
				.addAnnotation(AnnotationSpec.builder(BindDaoMany2Many.class)
						.addMember("entity1", "$T.class", entity.entity1Name)
						.addMember("entity2", "$T.class", entity.entity2Name).build())
				.addSuperinterface(entity.daoName);
		// @formatter:on

		JavadocUtility.generateJavadocGeneratedBy(classBuilder);

		if (entity.generateMethods) {
			generateSelects(entity, entityPackageName);
			generateDeletes(entity, entityPackageName);
			generateInsert(entity, entityPackageName);
		}

		TypeSpec typeSpec = classBuilder.build();

		try {
			JavaWriterHelper.writeJava2File(filer, daoPackageName, typeSpec);
		} catch (IOException e) {
			throw new KriptonRuntimeException(e);
		}

		GeneratedTypeElement daoPartElement = new GeneratedTypeElement(daoPackageName, classBuilder.build(), null,
				null);
		daoResult.add(daoPartElement);
	}