Search in sources :

Example 1 with Query

use of org.hisp.dhis.query.Query in project dhis2-core by dhis2.

the class DefaultQueryPlanner method getQuery.

/**
     * @param query Query
     * @return Query instance
     */
private Query getQuery(Query query, boolean persistedOnly) {
    Query pQuery = Query.from(query.getSchema(), query.getRootJunction().getType());
    Iterator<Criterion> iterator = query.getCriterions().iterator();
    while (iterator.hasNext()) {
        org.hisp.dhis.query.Criterion criterion = iterator.next();
        if (Junction.class.isInstance(criterion)) {
            Junction junction = handleJunction(pQuery, (Junction) criterion, persistedOnly);
            if (!junction.getCriterions().isEmpty()) {
                pQuery.getAliases().addAll(junction.getAliases());
                pQuery.add(junction);
            }
            if (((Junction) criterion).getCriterions().isEmpty()) {
                iterator.remove();
            }
        } else if (Restriction.class.isInstance(criterion)) {
            Restriction restriction = (Restriction) criterion;
            restriction.setQueryPath(getQueryPath(query.getSchema(), restriction.getPath()));
            if (restriction.getQueryPath().isPersisted() && !restriction.getQueryPath().haveAlias()) {
                pQuery.getAliases().addAll(Arrays.asList(((Restriction) criterion).getQueryPath().getAlias()));
                pQuery.getCriterions().add(criterion);
                iterator.remove();
            }
        }
    }
    if (query.ordersPersisted()) {
        pQuery.addOrders(query.getOrders());
        query.clearOrders();
    }
    return pQuery;
}
Also used : Restriction(org.hisp.dhis.query.Restriction) Query(org.hisp.dhis.query.Query) Criterion(org.hisp.dhis.query.Criterion) Criterion(org.hisp.dhis.query.Criterion) Junction(org.hisp.dhis.query.Junction)

Example 2 with Query

use of org.hisp.dhis.query.Query in project dhis2-core by dhis2.

the class DefaultPreheatService method preheat.

@Override
@SuppressWarnings("unchecked")
public Preheat preheat(PreheatParams params) {
    Timer timer = new SystemTimer().start();
    Preheat preheat = new Preheat();
    preheat.setUser(params.getUser());
    preheat.setDefaults(manager.getDefaults());
    if (preheat.getUser() == null) {
        preheat.setUser(currentUserService.getCurrentUser());
    }
    preheat.put(PreheatIdentifier.UID, preheat.getUser());
    preheat.put(PreheatIdentifier.CODE, preheat.getUser());
    for (Class<? extends IdentifiableObject> klass : params.getObjects().keySet()) {
        params.getObjects().get(klass).stream().filter(identifiableObject -> StringUtils.isEmpty(identifiableObject.getUid())).forEach(identifiableObject -> ((BaseIdentifiableObject) identifiableObject).setUid(CodeGenerator.generateUid()));
    }
    Map<Class<? extends IdentifiableObject>, List<IdentifiableObject>> uniqueCollectionMap = new HashMap<>();
    Set<Class<? extends IdentifiableObject>> klasses = new HashSet<>(params.getObjects().keySet());
    if (PreheatMode.ALL == params.getPreheatMode()) {
        if (params.getClasses().isEmpty()) {
            schemaService.getMetadataSchemas().stream().filter(Schema::isIdentifiableObject).forEach(schema -> params.getClasses().add((Class<? extends IdentifiableObject>) schema.getKlass()));
        }
        for (Class<? extends IdentifiableObject> klass : params.getClasses()) {
            Query query = Query.from(schemaService.getDynamicSchema(klass));
            query.setUser(preheat.getUser());
            List<? extends IdentifiableObject> objects = queryService.query(query);
            if (PreheatIdentifier.UID == params.getPreheatIdentifier() || PreheatIdentifier.AUTO == params.getPreheatIdentifier()) {
                preheat.put(PreheatIdentifier.UID, objects);
            }
            if (PreheatIdentifier.CODE == params.getPreheatIdentifier() || PreheatIdentifier.AUTO == params.getPreheatIdentifier()) {
                preheat.put(PreheatIdentifier.CODE, objects);
            }
            if (klasses.contains(klass) && !objects.isEmpty()) {
                uniqueCollectionMap.put(klass, new ArrayList<>(objects));
            }
        }
    } else if (PreheatMode.REFERENCE == params.getPreheatMode()) {
        Map<PreheatIdentifier, Map<Class<? extends IdentifiableObject>, Set<String>>> references = collectReferences(params.getObjects());
        Map<Class<? extends IdentifiableObject>, Set<String>> uidMap = references.get(PreheatIdentifier.UID);
        Map<Class<? extends IdentifiableObject>, Set<String>> codeMap = references.get(PreheatIdentifier.CODE);
        if (uidMap != null && (PreheatIdentifier.UID == params.getPreheatIdentifier() || PreheatIdentifier.AUTO == params.getPreheatIdentifier())) {
            for (Class<? extends IdentifiableObject> klass : uidMap.keySet()) {
                List<List<String>> identifiers = Lists.partition(Lists.newArrayList(uidMap.get(klass)), 20000);
                if (!identifiers.isEmpty()) {
                    for (List<String> ids : identifiers) {
                        Query query = Query.from(schemaService.getDynamicSchema(klass));
                        query.setUser(preheat.getUser());
                        query.add(Restrictions.in("id", ids));
                        List<? extends IdentifiableObject> objects = queryService.query(query);
                        preheat.put(PreheatIdentifier.UID, objects);
                    }
                }
            }
        }
        if (codeMap != null && (PreheatIdentifier.CODE == params.getPreheatIdentifier() || PreheatIdentifier.AUTO == params.getPreheatIdentifier())) {
            for (Class<? extends IdentifiableObject> klass : codeMap.keySet()) {
                List<List<String>> identifiers = Lists.partition(Lists.newArrayList(codeMap.get(klass)), 20000);
                if (!identifiers.isEmpty()) {
                    for (List<String> ids : identifiers) {
                        Query query = Query.from(schemaService.getDynamicSchema(klass));
                        query.setUser(preheat.getUser());
                        query.add(Restrictions.in("code", ids));
                        List<? extends IdentifiableObject> objects = queryService.query(query);
                        preheat.put(PreheatIdentifier.CODE, objects);
                    }
                }
            }
        }
        for (Class<? extends IdentifiableObject> klass : klasses) {
            Query query = Query.from(schemaService.getDynamicSchema(klass));
            query.setUser(preheat.getUser());
            List<? extends IdentifiableObject> objects = queryService.query(query);
            if (!objects.isEmpty()) {
                uniqueCollectionMap.put(klass, new ArrayList<>(objects));
            }
        }
    }
    if (uniqueCollectionMap.containsKey(User.class)) {
        List<IdentifiableObject> userCredentials = new ArrayList<>();
        for (IdentifiableObject identifiableObject : uniqueCollectionMap.get(User.class)) {
            User user = (User) identifiableObject;
            if (user.getUserCredentials() != null) {
                userCredentials.add(user.getUserCredentials());
            }
        }
        uniqueCollectionMap.put(UserCredentials.class, userCredentials);
    }
    preheat.setUniquenessMap(collectUniqueness(uniqueCollectionMap));
    // add preheat placeholders for objects that will be created and set mandatory/unique attributes
    for (Class<? extends IdentifiableObject> klass : params.getObjects().keySet()) {
        List<IdentifiableObject> objects = params.getObjects().get(klass);
        preheat.put(params.getPreheatIdentifier(), objects);
    }
    handleAttributes(params.getObjects(), preheat);
    handleSecurity(params.getObjects(), params.getPreheatIdentifier(), preheat);
    periodStore.getAll().forEach(period -> preheat.getPeriodMap().put(period.getName(), period));
    periodStore.getAllPeriodTypes().forEach(periodType -> preheat.getPeriodTypeMap().put(periodType.getName(), periodType));
    log.info("(" + preheat.getUsername() + ") Import:Preheat[" + params.getPreheatMode() + "] took " + timer.toString());
    return preheat;
}
Also used : ReflectionUtils(org.hisp.dhis.system.util.ReflectionUtils) BaseAnalyticalObject(org.hisp.dhis.common.BaseAnalyticalObject) Restrictions(org.hisp.dhis.query.Restrictions) PeriodService(org.hisp.dhis.period.PeriodService) MergeService(org.hisp.dhis.schema.MergeService) Autowired(org.springframework.beans.factory.annotation.Autowired) TrackedEntityAttributeDimension(org.hisp.dhis.trackedentity.TrackedEntityAttributeDimension) StringUtils(org.apache.commons.lang3.StringUtils) MergeParams(org.hisp.dhis.schema.MergeParams) EmbeddedObject(org.hisp.dhis.common.EmbeddedObject) CategoryDimension(org.hisp.dhis.dataelement.CategoryDimension) UserCredentials(org.hisp.dhis.user.UserCredentials) Map(java.util.Map) Period(org.hisp.dhis.period.Period) Query(org.hisp.dhis.query.Query) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) UserGroup(org.hisp.dhis.user.UserGroup) Collection(java.util.Collection) Set(java.util.Set) SchemaService(org.hisp.dhis.schema.SchemaService) QueryService(org.hisp.dhis.query.QueryService) Property(org.hisp.dhis.schema.Property) Collectors(java.util.stream.Collectors) DataDimensionItem(org.hisp.dhis.common.DataDimensionItem) List(java.util.List) AttributeService(org.hisp.dhis.attribute.AttributeService) Schema(org.hisp.dhis.schema.Schema) LogFactory(org.apache.commons.logging.LogFactory) AnalyticalObject(org.hisp.dhis.common.AnalyticalObject) PropertyType(org.hisp.dhis.schema.PropertyType) DataSetElement(org.hisp.dhis.dataset.DataSetElement) HashMap(java.util.HashMap) Attribute(org.hisp.dhis.attribute.Attribute) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) User(org.hisp.dhis.user.User) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) SystemTimer(org.hisp.dhis.commons.timer.SystemTimer) DataElementOperand(org.hisp.dhis.dataelement.DataElementOperand) TrackedEntityProgramIndicatorDimension(org.hisp.dhis.trackedentity.TrackedEntityProgramIndicatorDimension) Timer(org.hisp.dhis.commons.timer.Timer) CollectionUtils(org.hisp.dhis.commons.collection.CollectionUtils) CurrentUserService(org.hisp.dhis.user.CurrentUserService) PeriodStore(org.hisp.dhis.period.PeriodStore) TrackedEntityDataElementDimension(org.hisp.dhis.trackedentity.TrackedEntityDataElementDimension) Log(org.apache.commons.logging.Log) CodeGenerator(org.hisp.dhis.common.CodeGenerator) Transactional(org.springframework.transaction.annotation.Transactional) Set(java.util.Set) HashSet(java.util.HashSet) User(org.hisp.dhis.user.User) Query(org.hisp.dhis.query.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) SystemTimer(org.hisp.dhis.commons.timer.SystemTimer) Timer(org.hisp.dhis.commons.timer.Timer) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) SystemTimer(org.hisp.dhis.commons.timer.SystemTimer) HashSet(java.util.HashSet)

Example 3 with Query

use of org.hisp.dhis.query.Query in project dhis2-core by dhis2.

the class AbstractCrudController method getEntityList.

@SuppressWarnings("unchecked")
protected List<T> getEntityList(WebMetadata metadata, WebOptions options, List<String> filters, List<Order> orders) throws QueryParserException {
    List<T> entityList;
    Query query = queryService.getQueryFromUrl(getEntityClass(), filters, orders, options.getRootJunction());
    query.setDefaultOrder();
    if (options.getOptions().containsKey("query")) {
        entityList = Lists.newArrayList(manager.filter(getEntityClass(), options.getOptions().get("query")));
    } else {
        entityList = (List<T>) queryService.query(query);
    }
    return entityList;
}
Also used : Query(org.hisp.dhis.query.Query)

Example 4 with Query

use of org.hisp.dhis.query.Query in project dhis2-core by dhis2.

the class DimensionController method getItems.

@SuppressWarnings("unchecked")
@RequestMapping(value = "/{uid}/items", method = RequestMethod.GET)
@ResponseBody
public RootNode getItems(@PathVariable String uid, @RequestParam Map<String, String> parameters, Model model, HttpServletRequest request, HttpServletResponse response) throws QueryParserException {
    List<String> fields = Lists.newArrayList(contextService.getParameterValues("fields"));
    List<String> filters = Lists.newArrayList(contextService.getParameterValues("filter"));
    if (fields.isEmpty()) {
        fields.addAll(Preset.defaultPreset().getFields());
    }
    List<DimensionalItemObject> items = dimensionService.getCanReadDimensionItems(uid);
    Query query = queryService.getQueryFromUrl(getEntityClass(), filters, new ArrayList<>());
    query.setObjects(items);
    query.setDefaultOrder();
    items = (List<DimensionalItemObject>) queryService.query(query);
    RootNode rootNode = NodeUtils.createMetadata();
    CollectionNode collectionNode = rootNode.addChild(fieldFilterService.filter(getEntityClass(), items, fields));
    collectionNode.setName("items");
    for (Node node : collectionNode.getChildren()) {
        ((AbstractNode) node).setName("item");
    }
    return rootNode;
}
Also used : RootNode(org.hisp.dhis.node.types.RootNode) DimensionalItemObject(org.hisp.dhis.common.DimensionalItemObject) Query(org.hisp.dhis.query.Query) AbstractNode(org.hisp.dhis.node.AbstractNode) CollectionNode(org.hisp.dhis.node.types.CollectionNode) AbstractNode(org.hisp.dhis.node.AbstractNode) Node(org.hisp.dhis.node.Node) RootNode(org.hisp.dhis.node.types.RootNode) CollectionNode(org.hisp.dhis.node.types.CollectionNode) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 5 with Query

use of org.hisp.dhis.query.Query in project dhis2-core by dhis2.

the class DimensionController method getEntityList.

// -------------------------------------------------------------------------
// Controller
// -------------------------------------------------------------------------
@Override
@SuppressWarnings("unchecked")
@ResponseBody
protected List<DimensionalObject> getEntityList(WebMetadata metadata, WebOptions options, List<String> filters, List<Order> orders) throws QueryParserException {
    List<DimensionalObject> dimensionalObjects;
    Query query = queryService.getQueryFromUrl(DimensionalObject.class, filters, orders, options.getRootJunction());
    query.setDefaultOrder();
    query.setObjects(dimensionService.getAllDimensions());
    dimensionalObjects = (List<DimensionalObject>) queryService.query(query);
    return dimensionalObjects;
}
Also used : Query(org.hisp.dhis.query.Query) DimensionalObject(org.hisp.dhis.common.DimensionalObject) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

Query (org.hisp.dhis.query.Query)16 List (java.util.List)8 ArrayList (java.util.ArrayList)6 IdentifiableObject (org.hisp.dhis.common.IdentifiableObject)5 Pager (org.hisp.dhis.common.Pager)4 RootNode (org.hisp.dhis.node.types.RootNode)4 Schema (org.hisp.dhis.schema.Schema)4 User (org.hisp.dhis.user.User)4 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)4 HashMap (java.util.HashMap)3 WebOptions (org.hisp.dhis.webapi.webdomain.WebOptions)3 Map (java.util.Map)2 SystemTimer (org.hisp.dhis.commons.timer.SystemTimer)2 Timer (org.hisp.dhis.commons.timer.Timer)2 DataElementOperand (org.hisp.dhis.dataelement.DataElementOperand)2 OrderParams (org.hisp.dhis.dxf2.common.OrderParams)2 Order (org.hisp.dhis.query.Order)2 WebMetadata (org.hisp.dhis.webapi.webdomain.WebMetadata)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1