Search in sources :

Example 1 with MergeParams

use of org.hisp.dhis.schema.MergeParams in project dhis2-core by dhis2.

the class DefaultPreheatService method collectObjectReferences.

@SuppressWarnings("unchecked")
private Map<Class<?>, Map<String, Map<String, Object>>> collectObjectReferences(Map<Class<?>, List<?>> objects) {
    Map<Class<?>, Map<String, Map<String, Object>>> map = new HashMap<>();
    if (objects.isEmpty()) {
        return map;
    }
    Map<Class<?>, List<?>> targets = new HashMap<>();
    // clone objects list, we don't want to modify it
    targets.putAll(objects);
    collectScanTargets(targets);
    for (Class<?> objectClass : targets.keySet()) {
        Schema schema = schemaService.getDynamicSchema(objectClass);
        if (!schema.isIdentifiableObject()) {
            continue;
        }
        List<Property> properties = schema.getProperties().stream().filter(p -> p.isPersisted() && p.isOwner() && (PropertyType.REFERENCE == p.getPropertyType() || PropertyType.REFERENCE == p.getItemPropertyType())).collect(Collectors.toList());
        List<IdentifiableObject> identifiableObjects = (List<IdentifiableObject>) targets.get(objectClass);
        Map<String, Map<String, Object>> refMap = new HashMap<>();
        map.put(objectClass, refMap);
        for (IdentifiableObject object : identifiableObjects) {
            refMap.put(object.getUid(), new HashMap<>());
            properties.forEach(p -> {
                if (!p.isCollection()) {
                    IdentifiableObject reference = ReflectionUtils.invokeMethod(object, p.getGetterMethod());
                    if (reference != null) {
                        try {
                            IdentifiableObject identifiableObject = (IdentifiableObject) p.getKlass().newInstance();
                            mergeService.merge(new MergeParams<>(reference, identifiableObject));
                            refMap.get(object.getUid()).put(p.getName(), identifiableObject);
                        } catch (InstantiationException | IllegalAccessException ignored) {
                        }
                    }
                } else {
                    Collection<IdentifiableObject> refObjects = ReflectionUtils.newCollectionInstance(p.getKlass());
                    Collection<IdentifiableObject> references = ReflectionUtils.invokeMethod(object, p.getGetterMethod());
                    if (references != null) {
                        for (IdentifiableObject reference : references) {
                            try {
                                IdentifiableObject identifiableObject = (IdentifiableObject) p.getItemKlass().newInstance();
                                mergeService.merge(new MergeParams<>(reference, identifiableObject));
                                refObjects.add(identifiableObject);
                            } catch (InstantiationException | IllegalAccessException ignored) {
                            }
                        }
                    }
                    refMap.get(object.getUid()).put(p.getCollectionName(), refObjects);
                }
            });
        }
    }
    return map;
}
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) HashMap(java.util.HashMap) Schema(org.hisp.dhis.schema.Schema) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) BaseAnalyticalObject(org.hisp.dhis.common.BaseAnalyticalObject) EmbeddedObject(org.hisp.dhis.common.EmbeddedObject) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) AnalyticalObject(org.hisp.dhis.common.AnalyticalObject) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) Property(org.hisp.dhis.schema.Property)

Example 2 with MergeParams

use of org.hisp.dhis.schema.MergeParams in project dhis2-core by dhis2.

the class MergeServiceTest method mergeOrgUnitGroupSet.

@Test
public void mergeOrgUnitGroupSet() {
    OrganisationUnit organisationUnitA = createOrganisationUnit('A');
    OrganisationUnit organisationUnitB = createOrganisationUnit('B');
    OrganisationUnit organisationUnitC = createOrganisationUnit('C');
    OrganisationUnit organisationUnitD = createOrganisationUnit('D');
    OrganisationUnitGroup organisationUnitGroupA = createOrganisationUnitGroup('A');
    organisationUnitGroupA.getMembers().add(organisationUnitA);
    organisationUnitGroupA.getMembers().add(organisationUnitB);
    organisationUnitGroupA.getMembers().add(organisationUnitC);
    organisationUnitGroupA.getMembers().add(organisationUnitD);
    OrganisationUnitGroupSet organisationUnitGroupSetA = createOrganisationUnitGroupSet('A');
    OrganisationUnitGroupSet organisationUnitGroupSetB = createOrganisationUnitGroupSet('B');
    organisationUnitGroupSetA.addOrganisationUnitGroup(organisationUnitGroupA);
    mergeService.merge(new MergeParams<>(organisationUnitGroupSetA, organisationUnitGroupSetB).setMergeMode(MergeMode.REPLACE));
    assertFalse(organisationUnitGroupSetB.getOrganisationUnitGroups().isEmpty());
    assertEquals(organisationUnitGroupSetA.getName(), organisationUnitGroupSetB.getName());
    assertEquals(organisationUnitGroupSetA.getDescription(), organisationUnitGroupSetB.getDescription());
    assertEquals(organisationUnitGroupSetA.isCompulsory(), organisationUnitGroupSetB.isCompulsory());
    assertEquals(organisationUnitGroupSetA.isIncludeSubhierarchyInAnalytics(), organisationUnitGroupSetB.isIncludeSubhierarchyInAnalytics());
    assertEquals(1, organisationUnitGroupSetB.getOrganisationUnitGroups().size());
}
Also used : OrganisationUnitGroup(org.hisp.dhis.organisationunit.OrganisationUnitGroup) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) MergeParams(org.hisp.dhis.schema.MergeParams) OrganisationUnitGroupSet(org.hisp.dhis.organisationunit.OrganisationUnitGroupSet) Test(org.junit.Test) DhisSpringTest(org.hisp.dhis.DhisSpringTest)

Example 3 with MergeParams

use of org.hisp.dhis.schema.MergeParams in project dhis2-core by dhis2.

the class MergeServiceTest method simpleCollection.

@Test
public void simpleCollection() {
    Date date = new Date();
    SimpleCollection source = new SimpleCollection("name");
    source.getSimples().add(new Simple("simple", 10, date, false, 123, 2.5f));
    source.getSimples().add(new Simple("simple", 20, date, false, 123, 2.5f));
    source.getSimples().add(new Simple("simple", 30, date, false, 123, 2.5f));
    SimpleCollection target = new SimpleCollection("target");
    mergeService.merge(new MergeParams<>(source, target).setMergeMode(MergeMode.MERGE));
    assertEquals("name", target.getName());
    assertEquals(3, target.getSimples().size());
    assertTrue(target.getSimples().contains(source.getSimples().get(0)));
    assertTrue(target.getSimples().contains(source.getSimples().get(1)));
    assertTrue(target.getSimples().contains(source.getSimples().get(2)));
}
Also used : MergeParams(org.hisp.dhis.schema.MergeParams) Date(java.util.Date) SimpleCollection(org.hisp.dhis.dxf2.metadata.merge.SimpleCollection) Simple(org.hisp.dhis.dxf2.metadata.merge.Simple) Test(org.junit.Test) DhisSpringTest(org.hisp.dhis.DhisSpringTest)

Example 4 with MergeParams

use of org.hisp.dhis.schema.MergeParams in project dhis2-core by dhis2.

the class UserController method replicateUser.

@SuppressWarnings("unchecked")
@PreAuthorize("hasRole('ALL') or hasRole('F_REPLICATE_USER')")
@RequestMapping(value = "/{uid}/replica", method = RequestMethod.POST)
public void replicateUser(@PathVariable String uid, HttpServletRequest request, HttpServletResponse response) throws IOException, WebMessageException {
    User existingUser = userService.getUser(uid);
    if (existingUser == null || existingUser.getUserCredentials() == null) {
        throw new WebMessageException(WebMessageUtils.conflict("User not found: " + uid));
    }
    User currentUser = currentUserService.getCurrentUser();
    if (!validateCreateUser(existingUser, currentUser)) {
        return;
    }
    Map<String, String> auth = renderService.fromJson(request.getInputStream(), Map.class);
    String username = StringUtils.trimToNull(auth != null ? auth.get(KEY_USERNAME) : null);
    String password = StringUtils.trimToNull(auth != null ? auth.get(KEY_PASSWORD) : null);
    if (auth == null || username == null) {
        throw new WebMessageException(WebMessageUtils.conflict("Username must be specified"));
    }
    if (userService.getUserCredentialsByUsername(username) != null) {
        throw new WebMessageException(WebMessageUtils.conflict("Username already taken: " + username));
    }
    if (password == null) {
        throw new WebMessageException(WebMessageUtils.conflict("Password must be specified"));
    }
    if (!ValidationUtils.passwordIsValid(password)) {
        throw new WebMessageException(WebMessageUtils.conflict("Password must have at least 8 characters, one digit, one uppercase"));
    }
    User userReplica = new User();
    mergeService.merge(new MergeParams<>(existingUser, userReplica).setMergeMode(MergeMode.MERGE));
    userReplica.setUid(CodeGenerator.generateUid());
    userReplica.setCode(null);
    userReplica.setCreated(new Date());
    UserCredentials credentialsReplica = new UserCredentials();
    mergeService.merge(new MergeParams<>(existingUser.getUserCredentials(), credentialsReplica).setMergeMode(MergeMode.MERGE));
    credentialsReplica.setUid(CodeGenerator.generateUid());
    credentialsReplica.setCode(null);
    credentialsReplica.setCreated(new Date());
    credentialsReplica.setLdapId(null);
    credentialsReplica.setOpenId(null);
    credentialsReplica.setUsername(username);
    userService.encodeAndSetPassword(credentialsReplica, password);
    userReplica.setUserCredentials(credentialsReplica);
    credentialsReplica.setUserInfo(userReplica);
    userService.addUser(userReplica);
    userService.addUserCredentials(credentialsReplica);
    userGroupService.addUserToGroups(userReplica, IdentifiableObjectUtils.getUids(existingUser.getGroups()), currentUser);
    // ---------------------------------------------------------------------
    // Replicate user settings
    // ---------------------------------------------------------------------
    List<UserSetting> settings = userSettingService.getUserSettings(existingUser);
    for (UserSetting setting : settings) {
        Optional<UserSettingKey> key = UserSettingKey.getByName(setting.getName());
        key.ifPresent(userSettingKey -> userSettingService.saveUserSetting(userSettingKey, setting.getValue(), userReplica));
    }
    response.addHeader("Location", UserSchemaDescriptor.API_ENDPOINT + "/" + userReplica.getUid());
    webMessageService.send(WebMessageUtils.created("User replica created"), response, request);
}
Also used : User(org.hisp.dhis.user.User) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) MergeParams(org.hisp.dhis.schema.MergeParams) UserSettingKey(org.hisp.dhis.user.UserSettingKey) UserCredentials(org.hisp.dhis.user.UserCredentials) Date(java.util.Date) UserSetting(org.hisp.dhis.user.UserSetting) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with MergeParams

use of org.hisp.dhis.schema.MergeParams in project dhis2-core by dhis2.

the class MapController method putJsonObject.

@Override
@RequestMapping(value = "/{uid}", method = RequestMethod.PUT, consumes = "application/json")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void putJsonObject(@PathVariable String uid, HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map map = mappingService.getMap(uid);
    if (map == null) {
        throw new WebMessageException(WebMessageUtils.notFound("Map does not exist: " + uid));
    }
    MetadataImportParams params = importService.getParamsFromMap(contextService.getParameterValuesMap());
    Map newMap = deserializeJsonEntity(request, response);
    newMap.setUid(uid);
    mergeService.merge(new MergeParams<>(newMap, map).setMergeMode(params.getMergeMode()));
    mappingService.updateMap(map);
}
Also used : MetadataImportParams(org.hisp.dhis.dxf2.metadata.MetadataImportParams) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) MergeParams(org.hisp.dhis.schema.MergeParams) Map(org.hisp.dhis.mapping.Map) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

MergeParams (org.hisp.dhis.schema.MergeParams)12 DhisSpringTest (org.hisp.dhis.DhisSpringTest)5 Test (org.junit.Test)5 Date (java.util.Date)4 User (org.hisp.dhis.user.User)4 Simple (org.hisp.dhis.dxf2.metadata.merge.Simple)3 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)3 UserCredentials (org.hisp.dhis.user.UserCredentials)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 MetadataImportParams (org.hisp.dhis.dxf2.metadata.MetadataImportParams)2 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)2 Lists (com.google.common.collect.Lists)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1