Search in sources :

Example 1 with BaseIdentifiableObject

use of org.hisp.dhis.common.BaseIdentifiableObject 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 2 with BaseIdentifiableObject

use of org.hisp.dhis.common.BaseIdentifiableObject in project dhis2-core by dhis2.

the class HibernateGenericStore method save.

@Override
public void save(T object, User user, boolean clearSharing) {
    String username = user != null ? user.getUsername() : "system-process";
    if (IdentifiableObject.class.isAssignableFrom(object.getClass())) {
        BaseIdentifiableObject identifiableObject = (BaseIdentifiableObject) object;
        identifiableObject.setAutoFields();
        identifiableObject.setLastUpdatedBy(user);
        if (clearSharing) {
            identifiableObject.setPublicAccess(AccessStringHelper.DEFAULT);
            if (identifiableObject.getUserGroupAccesses() != null) {
                identifiableObject.getUserGroupAccesses().clear();
            }
            if (identifiableObject.getUserAccesses() != null) {
                identifiableObject.getUserAccesses().clear();
            }
        }
        if (identifiableObject.getUser() == null) {
            identifiableObject.setUser(user);
        }
    }
    if (user != null && aclService.isShareable(clazz)) {
        BaseIdentifiableObject identifiableObject = (BaseIdentifiableObject) object;
        if (clearSharing) {
            if (aclService.canMakePublic(user, identifiableObject.getClass())) {
                if (aclService.defaultPublic(identifiableObject.getClass())) {
                    identifiableObject.setPublicAccess(AccessStringHelper.READ_WRITE);
                }
            } else if (aclService.canMakePrivate(user, identifiableObject.getClass())) {
                identifiableObject.setPublicAccess(AccessStringHelper.newInstance().build());
            }
        }
        if (!checkPublicAccess(user, identifiableObject)) {
            AuditLogUtil.infoWrapper(log, username, object, AuditLogUtil.ACTION_CREATE_DENIED);
            throw new CreateAccessDeniedException(object.toString());
        }
    }
    AuditLogUtil.infoWrapper(log, username, object, AuditLogUtil.ACTION_CREATE);
    getSession().save(object);
    if (MetadataObject.class.isInstance(object)) {
        deletedObjectService.deleteDeletedObjects(new DeletedObjectQuery((IdentifiableObject) object));
    }
}
Also used : BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) CreateAccessDeniedException(org.hisp.dhis.hibernate.exception.CreateAccessDeniedException) DeletedObjectQuery(org.hisp.dhis.deletedobject.DeletedObjectQuery) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject)

Example 3 with BaseIdentifiableObject

use of org.hisp.dhis.common.BaseIdentifiableObject in project dhis2-core by dhis2.

the class AbstractCrudController method putJsonObject.

//--------------------------------------------------------------------------
// PUT
//--------------------------------------------------------------------------
@RequestMapping(value = "/{uid}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public void putJsonObject(@PathVariable("uid") String pvUid, HttpServletRequest request, HttpServletResponse response) throws Exception {
    List<T> objects = getEntity(pvUid);
    if (objects.isEmpty()) {
        throw new WebMessageException(WebMessageUtils.notFound(getEntityClass(), pvUid));
    }
    User user = currentUserService.getCurrentUser();
    if (!aclService.canUpdate(user, objects.get(0))) {
        throw new UpdateAccessDeniedException("You don't have the proper permissions to update this object.");
    }
    T parsed = deserializeJsonEntity(request, response);
    ((BaseIdentifiableObject) parsed).setUid(pvUid);
    preUpdateEntity(objects.get(0), parsed);
    MetadataImportParams params = importService.getParamsFromMap(contextService.getParameterValuesMap()).setImportReportMode(ImportReportMode.FULL).setUser(user).setImportStrategy(ImportStrategy.UPDATE).addObject(parsed);
    ImportReport importReport = importService.importMetadata(params);
    WebMessage webMessage = WebMessageUtils.objectReport(importReport);
    if (importReport.getStatus() == Status.OK) {
        T entity = manager.get(getEntityClass(), pvUid);
        postUpdateEntity(entity);
    } else {
        webMessage.setStatus(Status.ERROR);
    }
    webMessageService.send(webMessage, response, request);
}
Also used : User(org.hisp.dhis.user.User) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) MetadataImportParams(org.hisp.dhis.dxf2.metadata.MetadataImportParams) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) UpdateAccessDeniedException(org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException) ImportReport(org.hisp.dhis.dxf2.metadata.feedback.ImportReport) WebMessage(org.hisp.dhis.dxf2.webmessage.WebMessage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with BaseIdentifiableObject

use of org.hisp.dhis.common.BaseIdentifiableObject in project dhis2-core by dhis2.

the class DefaultI18nLocaleService method init.

/**
     * Load all ISO languages and countries into mappings.
     */
@PostConstruct
public void init() {
    List<IdentifiableObject> langs = new ArrayList<>();
    List<IdentifiableObject> countrs = new ArrayList<>();
    for (String lang : Locale.getISOLanguages()) {
        langs.add(new BaseIdentifiableObject(lang, lang, new Locale(lang).getDisplayLanguage()));
    }
    for (String country : Locale.getISOCountries()) {
        countrs.add(new BaseIdentifiableObject(country, country, new Locale("en", country).getDisplayCountry()));
    }
    Collections.sort(langs);
    Collections.sort(countrs);
    for (IdentifiableObject lang : langs) {
        languages.put(lang.getCode(), lang.getName());
    }
    for (IdentifiableObject countr : countrs) {
        countries.put(countr.getCode(), countr.getName());
    }
}
Also used : Locale(java.util.Locale) I18nLocale(org.hisp.dhis.i18n.locale.I18nLocale) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) ArrayList(java.util.ArrayList) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) PostConstruct(javax.annotation.PostConstruct)

Example 5 with BaseIdentifiableObject

use of org.hisp.dhis.common.BaseIdentifiableObject in project dhis2-core by dhis2.

the class GetReportParamsAction method execute.

// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute() {
    if (mode == null || uid == null) {
        return SUCCESS;
    }
    RelativePeriods relatives = null;
    if (MODE_REPORT_TABLE.equals(mode)) {
        ReportTable reportTable = reportTableService.getReportTable(uid);
        if (reportTable != null) {
            reportParams = reportTable.getReportParams();
            relatives = reportTable.getRelatives();
        }
    } else if (MODE_REPORT.equals(mode)) {
        Report report = reportService.getReport(uid);
        if (report != null && report.isTypeReportTable()) {
            reportParams = report.getReportTable().getReportParams();
            relatives = report.getReportTable().getRelatives();
        } else if (report != null && (report.isTypeJdbc() || report.isTypeHtml())) {
            reportParams = report.getReportParams();
            relatives = report.getRelatives();
        }
        if (type == null && report != null) {
            // Set type based on report
            type = report.getType();
        }
    }
    if (reportParams != null && reportParams.isParamReportingMonth() && relatives != null) {
        CalendarPeriodType periodType = (CalendarPeriodType) relatives.getPeriodType();
        List<Period> periods = periodType.generateLast5Years(new Date());
        Collections.reverse(periods);
        FilterUtils.filter(periods, new PastAndCurrentPeriodFilter());
        Calendar calendar = PeriodType.getCalendar();
        for (Period period_ : periods) {
            BaseIdentifiableObject period = new BaseIdentifiableObject();
            if (calendar.isIso8601()) {
                period.setUid(period_.getIsoDate());
                period.setDisplayName(format.formatPeriod(period_));
            } else {
                DateTimeUnit dateTimeUnit = calendar.fromIso(period_.getStartDate());
                period.setUid(period_.getPeriodType().getIsoDate(dateTimeUnit));
                period.setDisplayName(format.formatPeriod(period_));
            }
            this.periods.add(period);
        }
    }
    return SUCCESS;
}
Also used : RelativePeriods(org.hisp.dhis.period.RelativePeriods) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) Report(org.hisp.dhis.report.Report) Calendar(org.hisp.dhis.calendar.Calendar) DateTimeUnit(org.hisp.dhis.calendar.DateTimeUnit) ReportTable(org.hisp.dhis.reporttable.ReportTable) Period(org.hisp.dhis.period.Period) CalendarPeriodType(org.hisp.dhis.period.CalendarPeriodType) PastAndCurrentPeriodFilter(org.hisp.dhis.system.filter.PastAndCurrentPeriodFilter) Date(java.util.Date)

Aggregations

BaseIdentifiableObject (org.hisp.dhis.common.BaseIdentifiableObject)13 IdentifiableObject (org.hisp.dhis.common.IdentifiableObject)5 User (org.hisp.dhis.user.User)4 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)3 UpdateAccessDeniedException (org.hisp.dhis.hibernate.exception.UpdateAccessDeniedException)3 Period (org.hisp.dhis.period.Period)3 Schema (org.hisp.dhis.schema.Schema)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 ArrayList (java.util.ArrayList)2 DeletedObjectQuery (org.hisp.dhis.deletedobject.DeletedObjectQuery)2 Property (org.hisp.dhis.schema.Property)2 UserGroup (org.hisp.dhis.user.UserGroup)2 Lists (com.google.common.collect.Lists)1 Collection (java.util.Collection)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Locale (java.util.Locale)1 Map (java.util.Map)1