Build the aggregation parameters.

@param group
@param expression
@param metadata
@param entityType
178455
private void buildAggregation(DBObject group, Expression expression, EntityMetadata metadata, EntityType entityType,
            boolean hasLob)
    {
        if (expression instanceof AggregateFunction)
        {
            AggregateFunction aggregateFunction = (AggregateFunction) expression;
            String identifier = aggregateFunction.getIdentifier().toLowerCase();

            Expression child = aggregateFunction.getExpression();

            if (child instanceof StateFieldPathExpression)
            {
                StateFieldPathExpression sfpExp = (StateFieldPathExpression) child;
                String columnName = getColumnName(metadata, entityType, sfpExp.toActualText());
                String actualColumnName = columnName;
                if (hasLob)
                {
                    actualColumnName = "metadata." + columnName;
                }
                else if (metadata.getIdAttribute().equals(entityType.getAttribute(metadata.getFieldName(columnName))))
                {
                    actualColumnName = "_id";
                }

                BasicDBObject item = new BasicDBObject("$" + identifier, "$" + actualColumnName);
                group.put(identifier + "_" + columnName, item);
            }
            else if (expression instanceof CountFunction)
            {
                group.put("count", new BasicDBObject("$sum", 1));
            }
        }
        else if (expression instanceof CollectionExpression)
        {
            for (Expression child : expression.children())
            {
                buildAggregation(group, child, metadata, entityType, hasLob);
            }
        }
        else if (expression instanceof StateFieldPathExpression)
        {
            StateFieldPathExpression sfpExp = (StateFieldPathExpression) expression;

            BasicDBObject idObject;
            Object existing = group.get("_id");
            if (existing != null)
            {
                idObject = (BasicDBObject) existing;
            }
            else
            {
                idObject = new BasicDBObject();
                group.put("_id", idObject);
            }

            String columnName = getColumnName(metadata, entityType, sfpExp.toActualText());
            String actualColumnName = columnName;
            if (hasLob)
            {
                actualColumnName = "metadata." + columnName;
            }

            idObject.put(columnName, "$" + actualColumnName);
        }
    }
738519
protected void addEntityClassToDocument(EntityMetadata metadata, Object entity, Document document,
        final MetamodelImpl metaModel) {
        try {
            Field luceneField;
            Object id;
            id = PropertyAccessorHelper.getId(entity, metadata);

            // Indexing composite keys
            if (metaModel != null && metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
                id = KunderaCoreUtils.prepareCompositeKey(metadata.getIdAttribute(), metaModel, id);
            }

            luceneField =
                new Field(IndexingConstants.ENTITY_ID_FIELD, id.toString(), Field.Store.YES, Field.Index.ANALYZED);

            // luceneField.set
            // adding class
            // namespace
            // /*Field.Store.YES, Field.Index.ANALYZED_NO_NORMS*/);
            document.add(luceneField);

            // index namespace for unique deletion
            luceneField =
                new Field(IndexingConstants.KUNDERA_ID_FIELD, getKunderaId(metadata, id), Field.Store.YES,
                    Field.Index.ANALYZED); // adding
            // class
            // namespace
            // Field.Store.YES/*, Field.Index.ANALYZED_NO_NORMS*/);
            document.add(luceneField);

            // index entity class
            luceneField =
                new Field(IndexingConstants.ENTITY_CLASS_FIELD, metadata.getEntityClazz().getCanonicalName()
                    .toLowerCase(), Field.Store.YES, Field.Index.ANALYZED);
            document.add(luceneField);
            //
            luceneField = new Field("timestamp", System.currentTimeMillis() + "", Field.Store.YES, Field.Index.NO);
            document.add(luceneField);

            // index index name
            luceneField =
                new Field(IndexingConstants.ENTITY_INDEXNAME_FIELD, metadata.getIndexName(), Field.Store.NO,
                    Field.Index.ANALYZED_NO_NORMS);
            document.add(luceneField);

            luceneField =
                new Field(getCannonicalPropertyName(metadata.getEntityClazz().getSimpleName(),
                    ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()), id.toString(),
                    Field.Store.YES, Field.Index.ANALYZED_NO_NORMS);
            document.add(luceneField);
        } catch (PropertyAccessException e) {
            throw new IllegalArgumentException("Id could not be read from object " + entity);
        }
    }
543847
private AggregationBuilder buildSelectAggregations(AggregationBuilder aggregationBuilder,
            SelectStatement selectStatement, EntityMetadata entityMetadata)
    {
        Expression expression = ((SelectClause) selectStatement.getSelectClause()).getSelectExpression();

        if (expression instanceof CollectionExpression)
        {
            aggregationBuilder = appendAggregation((CollectionExpression) expression, entityMetadata,
                    aggregationBuilder);
        }
        else
        {
            if (isAggregationExpression(expression) && checkIfKeyExists(expression.toParsedText()))
                aggregationBuilder.subAggregation(getMetricsAggregation(expression, entityMetadata));
        }
        return aggregationBuilder;
    }
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(")");
        }
    }
503504
private <T extends ProgramElementDoc> void mapTypeParameters(Map<String,List<T>> map, Object doc,
            T holder) {
        TypeVariable[] typeVariables;
        if (doc instanceof ClassDoc) {
            typeVariables = ((ClassDoc) doc).typeParameters();
        } else if (doc instanceof WildcardType) {
            Type[] extendsBounds = ((WildcardType) doc).extendsBounds();
            for (int k = 0; k < extendsBounds.length; k++) {
                addTypeParameterToMap(map, extendsBounds[k], holder);
            }
            Type[] superBounds = ((WildcardType) doc).superBounds();
            for (int k = 0; k < superBounds.length; k++) {
                addTypeParameterToMap(map, superBounds[k], holder);
            }
            return;
        } else if (doc instanceof ParameterizedType) {
            Type[] typeArguments = ((ParameterizedType) doc).typeArguments();
            for (int k = 0; k < typeArguments.length; k++) {
                addTypeParameterToMap(map, typeArguments[k], holder);
            }
            return;
        } else if (doc instanceof ExecutableMemberDoc) {
            typeVariables = ((ExecutableMemberDoc) doc).typeParameters();
        } else if (doc instanceof FieldDoc) {
            Type fieldType = ((FieldDoc) doc).type();
            mapTypeParameters(map, fieldType, holder);
            return;
        } else {
            return;
        }
        for (int i = 0; i < typeVariables.length; i++) {
            Type[] bounds = typeVariables[i].bounds();
            for (int j = 0; j < bounds.length; j++) {
                addTypeParameterToMap(map, bounds[j], holder);
            }
        }
    }
364071
private List parseAggregatedResponse(SearchResponse response, KunderaQuery query, MetamodelImpl metaModel,
            Class clazz, EntityMetadata entityMetadata)
    {
        List results, temp = new ArrayList<>();
        InternalAggregations internalAggs = ((InternalFilter) response.getAggregations().getAsMap()
                .get(ESConstants.AGGREGATION_NAME)).getAggregations();

        if (query.isSelectStatement() && KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))
        {
            Terms buckets = (Terms) (internalAggs).getAsMap().get(ESConstants.GROUP_BY);

            filterBuckets(buckets, query);

            results = onIterateBuckets(buckets, query, metaModel, clazz, entityMetadata);
        }
        else
        {
            results = new ArrayList<>();
            temp = buildRecords(internalAggs, response.getHits(), query, metaModel, clazz, entityMetadata);

            for (Object value : temp)
            {
                if (!value.toString().equalsIgnoreCase(ESConstants.INFINITY))
                {
                    results.add(value);
                }
            }
        }
        return results;
    }
436405
public static <E, F extends Comparable<? super F>> GroupExpression<E, SortedSet<F>> sortedSet(GroupExpression<E, F> groupExpression) {
        return new MixinGroupExpression<E, F, SortedSet<F>>(groupExpression, GSet.createSorted(groupExpression));
    }
269464
public static <K> GroupByBuilder<K> groupBy(Expression<K> key) {
        return new GroupByBuilder<K>(key);
    }
55011
void autoGenerateAlgorithms(
      EntityMapping mapping,
      EntityType sourceEntityType,
      EntityType targetEntityType,
      MappingProject project) {
    algorithmService.autoGenerateAlgorithm(sourceEntityType, targetEntityType, mapping);
    mappingService.updateMappingProject(project);
  }
768783
public static Map<String, Object> onInExpression(Expression expression, EntityMetadata m,
            KunderaMetadata kunderaMetadata, KunderaQuery kunderaQuery)
    {
        InExpression inExp = (InExpression) expression;
        Expression sfpExp = inExp.getExpression();
        Map<String, Object> map = KunderaQueryUtils.setFieldClazzAndColumnFamily(sfpExp, m, kunderaMetadata);
        kunderaQuery.addFilterClause(
              (String) map.get(Constants.COL_NAME), inExp.getIdentifier(), inExp.getInItems(),
              (String) map.get(Constants.FIELD_NAME), (Boolean) map.get(Constants.IGNORE_CASE));
        return map;
    }
1018330
private QueryBuilder populateLikeQuery(LikeExpression likeExpression, EntityMetadata metadata)
    {
        Expression patternValue = likeExpression.getPatternValue();
        String field = likeExpression.getStringExpression().toString();

        String likePattern = (patternValue instanceof InputParameter) ? kunderaQuery.getParametersMap()
                .get((patternValue).toParsedText()).toString() : patternValue.toParsedText().toString();
        String jpaField = getField(field);

        log.debug("Pattern value for field " + field + " is: " + patternValue);
        QueryBuilder filterBuilder = getQueryBuilder(kunderaQuery.new FilterClause(jpaField, Expression.LIKE,
                likePattern, field), metadata);

        return filterBuilder;
    }
1294668
public void buildGroup(ComponentGroup group, BuilderT builder, Context context)
    {
        for (Component component : group.getComponents())
        {
            buildAny(component, builder, context);
        }
    }
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;
    }
9960
public void serializeMerge(QueryMetadata metadata, RelationalPath<?> entity,
            List<Path<?>> keys, List<Path<?>> columns, List<Expression<?>> values,
            SubQueryExpression<?> subQuery, SQLSerializer context) {
        context.serializeForMerge(metadata, entity, keys, columns, values, subQuery);

        if (!metadata.getFlags().isEmpty()) {
            context.serialize(Position.END, metadata.getFlags());
        }
    }
1341205
protected <T> long processUpdateGroup(T obj, String groupType, String groupName, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions, Session sess) throws CpoException {
    Logger localLogger = obj == null ? logger : LoggerFactory.getLogger(obj.getClass());
    CpoClass cpoClass;

    if (obj == null) {
      throw new CpoException("NULL Object passed into insertObject, deleteObject, updateObject, or persistObject");
    }

    try {
      cpoClass = metaDescriptor.getMetaClass(obj);
      List<CpoFunction> cpoFunctions = cpoClass.getFunctionGroup(getGroupType(obj, groupType, groupName, sess), groupName).getFunctions();
      localLogger.info("=================== Class=<" + obj.getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");

      for (CpoFunction cpoFunction : cpoFunctions) {
        CassandraBoundStatementFactory boundStatementFactory = new CassandraBoundStatementFactory(sess, this, cpoClass, cpoFunction, obj, wheres, orderBy, nativeExpressions);
        executeBoundStatement(sess, boundStatementFactory);
      }
      localLogger.info("=================== " + " Updates - Class=<" + obj.getClass() + "> Type=<" + groupType + "> Name=<" + groupName + "> =========================");
    } catch (Throwable t) {
      String msg = "ProcessUpdateGroup failed:" + groupType + "," + groupName + "," + obj.getClass().getName();
      // TODO FIX THIS
      // localLogger.error("bound values:" + this.parameterToString(jq));
      localLogger.error(msg, t);
      throw new CpoException(msg, t);
    }

    return unknownModifyCount;
  }
274715
void parse(QEntityFactory entityFactory, EntityType<?> metadata, SessionFactoryImplementor sessionFactory)
	{
		this.metamodelEntity = metadata;
		this.name = metadata.getName();

		for (Attribute<?, ?> attribute : metadata.getAttributes())
		{
			parseFields(entityFactory, sessionFactory, null, attribute);
		}

		// Parse top-level properties

		// Add identifier property
		{
			if (!metadata.hasSingleIdAttribute())
				throw new IllegalArgumentException("@IdClass Entity not supported! " + metadata.getJavaType());

			Type idType = metadata.getIdType();

			switch (idType.getPersistenceType())
			{
				case BASIC:
					break; // No action necessary, will be processed like a normal field
				case EMBEDDABLE:
				{
					EmbeddableType<?> emb = (EmbeddableType<?>) idType;

					parseEmbeddable(entityFactory, sessionFactory, "id", emb);
					break;
				}
				default:
					throw new IllegalArgumentException("Cannot handle id type: " + idType.getPersistenceType() + ": " + idType);
			}
		}

		// Add links to descendants
		{
			final List<QEntity> descendants = entityFactory.getSubclasses(clazz);

			if (!descendants.isEmpty())
				this.descendants = descendants;
		}


		// Figure out the id method/field
		final String idPropertyName = getIdPropertyName();

		if (idPropertyName != null)
			this.idProperty = new PropertyWrapper(clazz, idPropertyName);
	}
243473
function(oModel, oEntityType, oEntitySet, oParameterization, oAssocFromParamsToResult) {
			this._oModel = oModel;
			this._oEntityType = oEntityType;
			this._oEntitySet = oEntitySet;
			this._oParameterization = oParameterization;

			this._oDimensionSet = {};
			this._oMeasureSet = {};

			// parse entity type for analytic semantics described by annotations
			var aProperty = oEntityType.getTypeDescription().property;
			var oAttributeForPropertySet = {};
			for (var i = -1, oProperty; (oProperty = aProperty[++i]) !== undefined;) {
				if (oProperty.extensions == undefined) {
					continue;
				}
				for (var j = -1, oExtension; (oExtension = oProperty.extensions[++j]) !== undefined;) {

					if (!oExtension.namespace == odata4analytics.constants.SAP_NAMESPACE) {
						continue;
					}

					switch (oExtension.name) {
					case "aggregation-role":
						switch (oExtension.value) {
						case "dimension": {
							var oDimension = new odata4analytics.Dimension(this, oProperty);
							this._oDimensionSet[oDimension.getName()] = oDimension;
							break;
							}
						case "measure": {
							var oMeasure = new odata4analytics.Measure(this, oProperty);
							this._oMeasureSet[oMeasure.getName()] = oMeasure;
							break;
							}
						case "totaled-properties-list":
							this._oTotaledPropertyListProperty = oProperty;
							break;
						default:
							}
						break;
					case "attribute-for": {
						var oDimensionAttribute = new odata4analytics.DimensionAttribute(this, oProperty);
						var oKeyProperty = oDimensionAttribute.getKeyProperty();
						oAttributeForPropertySet[oKeyProperty.name] = oDimensionAttribute;
						break;
						}
					default:
					}
				}
			}

			// assign dimension attributes to the respective dimension objects
			for ( var sDimensionAttributeName in oAttributeForPropertySet) {
				var oDimensionAttribute2 = oAttributeForPropertySet[sDimensionAttributeName];
				oDimensionAttribute2.getDimension().addAttribute(oDimensionAttribute2);
			}

			// apply workaround for missing text properties if requested
			if (oModel._oActivatedWorkarounds.IdentifyTextPropertiesByName) {
				var aMatchedTextPropertyName = [];
				for ( var oDimName in this._oDimensionSet) {
					var oDimension2 = this._oDimensionSet[oDimName];
					if (!oDimension2.getTextProperty()) {
						var oTextProperty = null; // order of matching is
						// significant!
						oTextProperty = oEntityType.findPropertyByName(oDimName + "Name");
						if (!oTextProperty) {
							oTextProperty = oEntityType.findPropertyByName(oDimName + "Text");
						}
						if (!oTextProperty) {
							oTextProperty = oEntityType.findPropertyByName(oDimName + "Desc");
						}
						if (!oTextProperty) {
							oTextProperty = oEntityType.findPropertyByName(oDimName + "Description");
						}
						if (oTextProperty) { // any match?
							oDimension2.setTextProperty(oTextProperty); // link
							// dimension
							// with text
							// property
							aMatchedTextPropertyName.push(oTextProperty.name);
						}
					}
				}
				// make sure that any matched text property is not exposed as
				// dimension (according to spec)
				for (var t = -1, sPropertyName; (sPropertyName = aMatchedTextPropertyName[++t]) !== undefined;) {
					delete this._oDimensionSet[sPropertyName];
				}
			}
		}