Search in sources :

Example 1 with CriteriaDefinition

use of org.springframework.data.mongodb.core.query.CriteriaDefinition in project oc-explorer by devgateway.

the class AwardsWonLostController method procurementsWonLost.

@ApiOperation(value = "Counts the won, lost procurements, flags and amounts. Receives any filters, " + "but most important here is the supplierId and bidderId. Requires bid extension. Use bidderId instead " + "of supplierId.")
@RequestMapping(value = "/api/procurementsWonLost", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json")
public List<ProcurementsWonLost> procurementsWonLost(@ModelAttribute @Valid final YearFilterPagingRequest filter) {
    Assert.notEmpty(filter.getBidderId(), "bidderId must not be empty!");
    Assert.isTrue(CollectionUtils.isEmpty(filter.getSupplierId()), "supplierId is not allowed here! Use bidderId to show results!");
    // supplier is the same thing as bidder for this particular query
    filter.setSupplierId(filter.getBidderId());
    Map<String, CriteriaDefinition> noSupplierCriteria = createDefaultFilterCriteriaMap(filter);
    noSupplierCriteria.remove(MongoConstants.Filters.SUPPLIER_ID);
    Aggregation agg1 = newAggregation(match(getYearDefaultFilterCriteria(filter, noSupplierCriteria, TENDER_PERIOD_START_DATE)), unwind("bids.details"), unwind("bids.details.tenderers"), match(getYearDefaultFilterCriteria(filter, noSupplierCriteria, TENDER_PERIOD_START_DATE)), group(BIDS_DETAILS_TENDERERS_ID).count().as("count").sum(BIDS_DETAILS_VALUE_AMOUNT).as("totalAmount").sum(FLAGS_TOTAL_FLAGGED).as("countFlags"), project("count", "totalAmount", "countFlags"));
    List<CountAmountFlags> applied = releaseAgg(agg1, CountAmountFlags.class);
    Aggregation agg2 = newAggregation(match(where(AWARDS_STATUS).is(Award.Status.active.toString()).andOperator(getYearDefaultFilterCriteria(filter, TENDER_PERIOD_START_DATE))), unwind("awards"), unwind("awards.suppliers"), match(where(AWARDS_STATUS).is(Award.Status.active.toString()).andOperator(getYearDefaultFilterCriteria(filter.awardFiltering(), TENDER_PERIOD_START_DATE))), group(MongoConstants.FieldNames.AWARDS_SUPPLIERS_ID).count().as("count").sum(MongoConstants.FieldNames.AWARDS_VALUE_AMOUNT).as("totalAmount").sum(FLAGS_TOTAL_FLAGGED).as("countFlags"), project("count", "totalAmount", "countFlags"));
    List<CountAmountFlags> won = releaseAgg(agg2, CountAmountFlags.class);
    ArrayList<ProcurementsWonLost> ret = new ArrayList<>();
    applied.forEach(a -> {
        ProcurementsWonLost r = new ProcurementsWonLost();
        r.setApplied(a);
        Optional<CountAmountFlags> optWon = won.stream().filter(w -> w.getId().equals(a.getId())).findFirst();
        if (optWon.isPresent()) {
            r.setWon(optWon.get());
            r.setLostAmount(r.getApplied().getTotalAmount().subtract(r.getWon().getTotalAmount()));
            r.setLostCount(r.getApplied().getCount() - r.getWon().getCount());
        } else {
            r.setLostAmount(r.getApplied().getTotalAmount());
            r.setLostCount(r.getLostCount());
        }
        ret.add(r);
    });
    return ret;
}
Also used : Aggregation.newAggregation(org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) YearFilterPagingRequest(org.devgateway.ocds.web.rest.controller.request.YearFilterPagingRequest) Aggregation.group(org.springframework.data.mongodb.core.aggregation.Aggregation.group) Aggregation.newAggregation(org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation) AWARDS_SUPPLIERS_NAME(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.AWARDS_SUPPLIERS_NAME) FLAGS_TOTAL_FLAGGED(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.FLAGS_TOTAL_FLAGGED) Cacheable(org.springframework.cache.annotation.Cacheable) TENDER_PROCURING_ENTITY_ID(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_ID) Aggregation.sort(org.springframework.data.mongodb.core.aggregation.Aggregation.sort) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Award(org.devgateway.ocds.persistence.mongo.Award) Aggregation.match(org.springframework.data.mongodb.core.aggregation.Aggregation.match) AggregationOperation(org.springframework.data.mongodb.core.aggregation.AggregationOperation) TENDER_PERIOD_START_DATE(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.TENDER_PERIOD_START_DATE) Fields(org.springframework.data.mongodb.core.aggregation.Fields) MongoConstants(org.devgateway.ocds.persistence.mongo.constants.MongoConstants) Fields.field(org.springframework.data.mongodb.core.aggregation.Fields.field) ArrayList(java.util.ArrayList) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) BigDecimal(java.math.BigDecimal) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) DBObject(com.mongodb.DBObject) BIDS_DETAILS_TENDERERS_ID(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.BIDS_DETAILS_TENDERERS_ID) AWARDS_STATUS(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.AWARDS_STATUS) Map(java.util.Map) TENDER_PROCURING_ENTITY_NAME(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.TENDER_PROCURING_ENTITY_NAME) Sort(org.springframework.data.domain.Sort) Aggregation.limit(org.springframework.data.mongodb.core.aggregation.Aggregation.limit) Criteria.where(org.springframework.data.mongodb.core.query.Criteria.where) Aggregation.skip(org.springframework.data.mongodb.core.aggregation.Aggregation.skip) AWARDS_SUPPLIERS_ID(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.AWARDS_SUPPLIERS_ID) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Aggregation.unwind(org.springframework.data.mongodb.core.aggregation.Aggregation.unwind) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) RestController(org.springframework.web.bind.annotation.RestController) Serializable(java.io.Serializable) List(java.util.List) BIDS_DETAILS_VALUE_AMOUNT(org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.BIDS_DETAILS_VALUE_AMOUNT) CriteriaDefinition(org.springframework.data.mongodb.core.query.CriteriaDefinition) CollectionUtils(org.springframework.util.CollectionUtils) Aggregation.project(org.springframework.data.mongodb.core.aggregation.Aggregation.project) CacheConfig(org.springframework.cache.annotation.CacheConfig) Optional(java.util.Optional) Assert(org.springframework.util.Assert) ArrayList(java.util.ArrayList) CriteriaDefinition(org.springframework.data.mongodb.core.query.CriteriaDefinition) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with CriteriaDefinition

use of org.springframework.data.mongodb.core.query.CriteriaDefinition in project spring-data-mongodb by spring-projects.

the class MongoQueryCreator method from.

/**
 * Populates the given {@link CriteriaDefinition} depending on the {@link Part} given.
 *
 * @param part
 * @param property
 * @param criteria
 * @param parameters
 * @return
 */
private Criteria from(Part part, MongoPersistentProperty property, Criteria criteria, Iterator<Object> parameters) {
    Type type = part.getType();
    switch(type) {
        case AFTER:
        case GREATER_THAN:
            return criteria.gt(parameters.next());
        case GREATER_THAN_EQUAL:
            return criteria.gte(parameters.next());
        case BEFORE:
        case LESS_THAN:
            return criteria.lt(parameters.next());
        case LESS_THAN_EQUAL:
            return criteria.lte(parameters.next());
        case BETWEEN:
            return criteria.gt(parameters.next()).lt(parameters.next());
        case IS_NOT_NULL:
            return criteria.ne(null);
        case IS_NULL:
            return criteria.is(null);
        case NOT_IN:
            return criteria.nin(nextAsArray(parameters));
        case IN:
            return criteria.in(nextAsArray(parameters));
        case LIKE:
        case STARTING_WITH:
        case ENDING_WITH:
        case CONTAINING:
            return createContainingCriteria(part, property, criteria, parameters);
        case NOT_LIKE:
            return createContainingCriteria(part, property, criteria.not(), parameters);
        case NOT_CONTAINING:
            return createContainingCriteria(part, property, criteria.not(), parameters);
        case REGEX:
            return criteria.regex(parameters.next().toString());
        case EXISTS:
            return criteria.exists((Boolean) parameters.next());
        case TRUE:
            return criteria.is(true);
        case FALSE:
            return criteria.is(false);
        case NEAR:
            Range<Distance> range = accessor.getDistanceRange();
            Optional<Distance> distance = range.getUpperBound().getValue();
            Optional<Distance> minDistance = range.getLowerBound().getValue();
            Point point = accessor.getGeoNearLocation();
            Point pointToUse = point == null ? nextAs(parameters, Point.class) : point;
            boolean isSpherical = isSpherical(property);
            return distance.map(it -> {
                if (isSpherical || !Metrics.NEUTRAL.equals(it.getMetric())) {
                    criteria.nearSphere(pointToUse);
                } else {
                    criteria.near(pointToUse);
                }
                criteria.maxDistance(it.getNormalizedValue());
                minDistance.ifPresent(min -> criteria.minDistance(min.getNormalizedValue()));
                return criteria;
            }).orElseGet(() -> isSpherical ? criteria.nearSphere(pointToUse) : criteria.near(pointToUse));
        case WITHIN:
            Object parameter = parameters.next();
            return criteria.within((Shape) parameter);
        case SIMPLE_PROPERTY:
            return isSimpleComparisionPossible(part) ? criteria.is(parameters.next()) : createLikeRegexCriteriaOrThrow(part, property, criteria, parameters, false);
        case NEGATING_SIMPLE_PROPERTY:
            return isSimpleComparisionPossible(part) ? criteria.ne(parameters.next()) : createLikeRegexCriteriaOrThrow(part, property, criteria, parameters, true);
        default:
            throw new IllegalArgumentException("Unsupported keyword!");
    }
}
Also used : MongoRegexCreator(org.springframework.data.mongodb.core.query.MongoRegexCreator) Arrays(java.util.Arrays) MongoPersistentProperty(org.springframework.data.mongodb.core.mapping.MongoPersistentProperty) IgnoreCaseType(org.springframework.data.repository.query.parser.Part.IgnoreCaseType) Metrics(org.springframework.data.geo.Metrics) LoggerFactory(org.slf4j.LoggerFactory) Shape(org.springframework.data.geo.Shape) Type(org.springframework.data.repository.query.parser.Part.Type) MappingContext(org.springframework.data.mapping.context.MappingContext) Part(org.springframework.data.repository.query.parser.Part) Distance(org.springframework.data.geo.Distance) AbstractQueryCreator(org.springframework.data.repository.query.parser.AbstractQueryCreator) Sort(org.springframework.data.domain.Sort) MatchMode(org.springframework.data.mongodb.core.query.MongoRegexCreator.MatchMode) Point(org.springframework.data.geo.Point) Logger(org.slf4j.Logger) ClassUtils(org.springframework.util.ClassUtils) Iterator(java.util.Iterator) GeoSpatialIndexType(org.springframework.data.mongodb.core.index.GeoSpatialIndexType) PotentiallyConvertingIterator(org.springframework.data.mongodb.repository.query.ConvertingParameterAccessor.PotentiallyConvertingIterator) PartTree(org.springframework.data.repository.query.parser.PartTree) Collection(java.util.Collection) Range(org.springframework.data.domain.Range) Criteria(org.springframework.data.mongodb.core.query.Criteria) Query(org.springframework.data.mongodb.core.query.Query) PersistentPropertyPath(org.springframework.data.mapping.context.PersistentPropertyPath) CriteriaDefinition(org.springframework.data.mongodb.core.query.CriteriaDefinition) Optional(java.util.Optional) PropertyPath(org.springframework.data.mapping.PropertyPath) GeoSpatialIndexed(org.springframework.data.mongodb.core.index.GeoSpatialIndexed) Assert(org.springframework.util.Assert) IgnoreCaseType(org.springframework.data.repository.query.parser.Part.IgnoreCaseType) Type(org.springframework.data.repository.query.parser.Part.Type) GeoSpatialIndexType(org.springframework.data.mongodb.core.index.GeoSpatialIndexType) Point(org.springframework.data.geo.Point) Distance(org.springframework.data.geo.Distance)

Aggregations

Optional (java.util.Optional)2 Sort (org.springframework.data.domain.Sort)2 CriteriaDefinition (org.springframework.data.mongodb.core.query.CriteriaDefinition)2 Assert (org.springframework.util.Assert)2 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)1 DBObject (com.mongodb.DBObject)1 ApiOperation (io.swagger.annotations.ApiOperation)1 Serializable (java.io.Serializable)1 BigDecimal (java.math.BigDecimal)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Map (java.util.Map)1 Valid (javax.validation.Valid)1 Award (org.devgateway.ocds.persistence.mongo.Award)1 MongoConstants (org.devgateway.ocds.persistence.mongo.constants.MongoConstants)1 AWARDS_STATUS (org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.AWARDS_STATUS)1 AWARDS_SUPPLIERS_ID (org.devgateway.ocds.persistence.mongo.constants.MongoConstants.FieldNames.AWARDS_SUPPLIERS_ID)1