Gets the aggregation.

@param expression
the expression
@param entityMetadata
the entity metadata
@return the aggregation
438312
private MetricsAggregationBuilder getMetricsAggregation(Expression expression, EntityMetadata entityMetadata)
    {
        AggregateFunction function = (AggregateFunction) expression;
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());
        String jPAColumnName = KunderaCoreUtils.getJPAColumnName(function.toParsedText(), entityMetadata, metaModel);

        MetricsAggregationBuilder aggregationBuilder = null;

        switch (function.getIdentifier())
        {
        case Expression.MIN:
            aggregationBuilder = AggregationBuilders.min(function.toParsedText()).field(jPAColumnName);
            break;
        case Expression.MAX:
            aggregationBuilder = AggregationBuilders.max(function.toParsedText()).field(jPAColumnName);
            break;
        case Expression.SUM:
            aggregationBuilder = AggregationBuilders.sum(function.toParsedText()).field(jPAColumnName);
            break;
        case Expression.AVG:
            aggregationBuilder = AggregationBuilders.avg(function.toParsedText()).field(jPAColumnName);
            break;
        case Expression.COUNT:
            aggregationBuilder = AggregationBuilders.count(function.toParsedText()).field(jPAColumnName);
            break;
        }
        return aggregationBuilder;
    }
835222
public static <E extends Number> AbstractGroupExpression<E, E> avg(Expression<E> expression) {
        return new GAvg<E>(expression);
    }
999186
private TopHitsBuilder getTopHitsAggregation(SelectStatement selectStatement, Integer size,
            EntityMetadata entityMetadata)
    {
        TopHitsBuilder topHitsBuilder = AggregationBuilders.topHits(ESConstants.TOP_HITS);
        if (size != null)
        {
            topHitsBuilder.setSize(size);
        }

        return topHitsBuilder;
    }
1174666
@NonNull
    public static SelectResult.As expression(@NonNull Expression expression) {
        if (expression == null) {
            throw new IllegalArgumentException("expression cannot be null.");
        }
        return new SelectResult.As(expression);
    }
996774
public static <T> JPQLQuery<T> select(Expression<T> expr) {
        return new JPASubQuery<Void>().select(expr);
    }
413387
public List executeQuery(QueryBuilder filter, AggregationBuilder aggregation, final EntityMetadata entityMetadata,
            KunderaQuery query, int firstResult, int maxResults)
    {
        String[] fieldsToSelect = query.getResult();
        Class clazz = entityMetadata.getEntityClazz();

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

        FilteredQueryBuilder queryBuilder = QueryBuilders.filteredQuery(null, filter);
        SearchRequestBuilder builder = txClient.prepareSearch(entityMetadata.getSchema().toLowerCase())
                .setTypes(entityMetadata.getTableName());

        addFieldsToBuilder(fieldsToSelect, clazz, metaModel, builder);

        if (aggregation == null)
        {
            builder.setQuery(queryBuilder);
            builder.setFrom(firstResult);
            builder.setSize(maxResults);
            addSortOrder(builder, query, entityMetadata);
        }
        else
        {
            logger.debug("Aggregated query identified");
            builder.addAggregation(aggregation);

            if (fieldsToSelect.length == 1
                    || (query.isSelectStatement() && query.getSelectStatement().hasGroupByClause()))
            {
                builder.setSize(0);
            }
        }

        SearchResponse response = null;
        logger.debug("Query generated: " + builder);

        try
        {
            response = builder.execute().actionGet();
            logger.debug("Query execution response: " + response);
        }
        catch (ElasticsearchException e)
        {
            logger.error("Exception occured while executing query on Elasticsearch.", e);
            throw new KunderaException("Exception occured while executing query on Elasticsearch.", e);
        }

        return esResponseReader.parseResponse(response, aggregation, fieldsToSelect, metaModel, clazz, entityMetadata,
                query);
    }
690492
public static Object getProperty(Object bean, String expression) {
		return BeanPath.create(expression).get(bean);
	}
361240
public static EntityMetadata getEntityMetadata(final KunderaMetadata kunderaMetadata, String persistenceUnit,
            Class entityClass)
    {
        return getMetamodel(kunderaMetadata, persistenceUnit).getEntityMetadata(entityClass);
    }
131776
@NonNull
    @Override
    public GroupBy groupBy(@NonNull Expression... expressions) {
        if (expressions == null) {
            throw new IllegalArgumentException("expressions cannot be null.");
        }
        return new GroupBy(this, Arrays.asList(expressions));
    }
157677
@Override
    public List<Annotation> getAnnotations(String expression) {
        requireNotDisposed();
        requireArgument(AnnotationReader.isValid(expression), "Invalid annotation expression: " + expression);

        AnnotationReader<Annotation> reader = new AnnotationReader<Annotation>(_tsdbService);
        List<Annotation> annotations = new LinkedList<>();

        try {
            _logger.debug("Retrieving annotations using {}.", expression);
            annotations.addAll(reader.parse(expression, Annotation.class));
        } catch (ParseException ex) {
            throw new SystemException("Failed to parse the given expression", ex);
        }
        _monitorService.modifyCounter(Counter.ANNOTATION_READS, annotations.size(), null);
        return annotations;
    }
228173
public SubReportBuilder setDataSource(String expression) {
		return setDataSource(DJConstants.DATA_SOURCE_ORIGIN_PARAMETER, DJConstants.DATA_SOURCE_TYPE_JRDATASOURCE, expression);
	}
443583
public String getSqlQueryFromJPA(EntityMetadata entityMetadata, List<String> relations, Set<String> primaryKeys)
    {
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        Metamodel metaModel = appMetadata.getMetamodel(entityMetadata.getPersistenceUnit());

        if (jpaQuery != null)
        {
            String query = appMetadata.getQuery(jpaQuery);
            boolean isNative = kunderaQuery != null ? kunderaQuery.isNative() : false;

            if (isNative)
            {
                return query != null ? query : jpaQuery;
            }
        }

        // Suffixing the UNDERSCORE instead of prefix as Oracle 11g complains
        // about invalid characters error while executing the request.
        String aliasName = entityMetadata.getTableName() + "_";

        StringBuilder queryBuilder = new StringBuilder("Select ");

        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
        Set<Attribute> attributes = entityType.getAttributes();
        for (Attribute field : attributes)
        {
            if (!field.isAssociation() && !field.isCollection()
                    && !((Field) field.getJavaMember()).isAnnotationPresent(ManyToMany.class)
                    && !((Field) field.getJavaMember()).isAnnotationPresent(Transient.class)
                    && !((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) field).getBindableJavaType()))
            {
                queryBuilder.append(aliasName);
                queryBuilder.append(".");
                queryBuilder.append(((AbstractAttribute) field).getJPAColumnName());
                queryBuilder.append(", ");
            }
        }

        // Handle embedded columns, add them to list.
        Map<String, EmbeddableType> embeddedColumns = ((MetamodelImpl) metaModel).getEmbeddables(entityMetadata
                .getEntityClazz());
        for (EmbeddableType embeddedCol : embeddedColumns.values())
        {
            Set<Attribute> embeddedAttributes = embeddedCol.getAttributes();
            for (Attribute column : embeddedAttributes)
            {
                queryBuilder.append(aliasName);
                queryBuilder.append(".");
                queryBuilder.append(((AbstractAttribute) column).getJPAColumnName());
                queryBuilder.append(", ");
            }
        }

        if (relations != null)
        {
            for (String relation : relations)
            {
                Relation rel = entityMetadata.getRelation(entityMetadata.getFieldName(relation));
                String r = MetadataUtils.getMappedName(entityMetadata, rel, kunderaMetadata);
                if (!((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName().equalsIgnoreCase(
                        r != null ? r : relation)
                        && rel != null
                        && !rel.getProperty().isAnnotationPresent(ManyToMany.class)
                        && !rel.getProperty().isAnnotationPresent(OneToMany.class)
                        && (rel.getProperty().isAnnotationPresent(OneToOne.class)
                                && StringUtils.isBlank(rel.getMappedBy()) || rel.getProperty().isAnnotationPresent(
                                ManyToOne.class)))
                {
                    queryBuilder.append(aliasName);
                    queryBuilder.append(".");
                    queryBuilder.append(r != null ? r : relation);
                    queryBuilder.append(", ");
                }
            }
        }

        // Remove last ","
        queryBuilder.deleteCharAt(queryBuilder.lastIndexOf(","));

        queryBuilder.append(" From ");
        if (entityMetadata.getSchema() != null && !entityMetadata.getSchema().isEmpty())
        {
            queryBuilder.append(entityMetadata.getSchema() + ".");
        }
        queryBuilder.append(entityMetadata.getTableName());
        queryBuilder.append(" ");
        queryBuilder.append(aliasName);
        // add conditions
        if (filter != null)
        {
            queryBuilder.append(" Where ");
        }

        // Append conditions
        onCondition(entityMetadata, (MetamodelImpl) metaModel, primaryKeys, aliasName, queryBuilder, entityType);

        return queryBuilder.toString();
    }
182463
@SuppressWarnings("unchecked")
    public <V> ResultTransformer<Map<K, V>> as(Expression<V> expression) {
        final Expression<V> lookup = getLookup(expression);
        return new GroupByMap<K, V>(key, expression) {
            @Override
            protected Map<K, V> transform(Map<K, Group> groups) {
                Map<K, V> results = new LinkedHashMap<K, V>((int) Math.ceil(groups.size() / 0.75), 0.75f);
                for (Map.Entry<K, Group> entry : groups.entrySet()) {
                    results.put(entry.getKey(), entry.getValue().getOne(lookup));
                }
                return results;
            }
        };
    }
142561
@Override
	public List<Metric> getMetrics(String expression) {
		requireNotDisposed();
		return getMetrics(expression, System.currentTimeMillis());
	}
1070922
public <V> ResultTransformer<CloseableIterator<V>> iterate(Expression<V> expression) {
        final Expression<V> lookup = getLookup(expression);
        return new GroupByIterate<K, V>(key, expression) {
            @Override
            protected V transform(Group group) {
                return group.getOne(lookup);
            }
        };
    }
129240
private QueryBuilder getFilter(FilterClause clause, final EntityMetadata metadata)
    {
        String condition = clause.getCondition();
        Object value = condition.equals(Expression.IN) ? clause.getValue() : clause.getValue().get(0);
        String name = ((AbstractAttribute) ((MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                metadata.getPersistenceUnit())).entity(metadata.getEntityClazz()).getAttribute(clause.getProperty()))
                .getJPAColumnName();

        QueryBuilder filterBuilder = null;

        if (condition.equals(Expression.EQUAL))
        {
            filterBuilder = new TermQueryBuilder(name, value);
        }
        else if (condition.equals(Expression.GREATER_THAN))
        {
            filterBuilder = new RangeQueryBuilder(name).gt(value);
        }
        else if (condition.equals(Expression.LOWER_THAN))
        {
            filterBuilder = new RangeQueryBuilder(name).lt(value);
        }
        else if (condition.equals(Expression.GREATER_THAN_OR_EQUAL))
        {
            filterBuilder = new RangeQueryBuilder(name).gte(value);
        }
        else if (condition.equals(Expression.LOWER_THAN_OR_EQUAL))
        {
            filterBuilder = new RangeQueryBuilder(name).lte(value);
        }
        else if (condition.equals(Expression.DIFFERENT))
        {
            filterBuilder = new NotQueryBuilder(new TermQueryBuilder(name, value));
        }
        else if (condition.equals(Expression.IN))
        {
            filterBuilder = new TermsQueryBuilder(name, clause.getValue());
        }

        return filterBuilder;
    }
1221564
@Override
    public Expression<Long> count(Expression<?> arg0)
    {
        // TODO Auto-generated method stub
        String arg1 = "Count("+arg0.getAlias()+")";
        return new AggregateExpression(arg0, arg1);
    }