Search in sources :

Example 31 with ResourceTO

use of org.apache.syncope.common.lib.to.ResourceTO in project syncope by apache.

the class ResourceDataBinderImpl method update.

@Override
public ExternalResource update(final ExternalResource resource, final ResourceTO resourceTO) {
    if (resource.getKey() != null) {
        ResourceTO current = getResourceTO(resource);
        if (!current.equals(resourceTO)) {
            // 1. save the current configuration, before update
            ExternalResourceHistoryConf resourceHistoryConf = entityFactory.newEntity(ExternalResourceHistoryConf.class);
            resourceHistoryConf.setCreator(AuthContextUtils.getUsername());
            resourceHistoryConf.setCreation(new Date());
            resourceHistoryConf.setEntity(resource);
            resourceHistoryConf.setConf(current);
            resourceHistoryConfDAO.save(resourceHistoryConf);
            // 2. ensure the maximum history size is not exceeded
            List<ExternalResourceHistoryConf> history = resourceHistoryConfDAO.findByEntity(resource);
            long maxHistorySize = confDAO.find("resource.conf.history.size", 10L);
            if (maxHistorySize < history.size()) {
                // always remove the last item since history was obtained  by a query with ORDER BY creation DESC
                for (int i = 0; i < history.size() - maxHistorySize; i++) {
                    resourceHistoryConfDAO.delete(history.get(history.size() - 1).getKey());
                }
            }
        }
    }
    resource.setKey(resourceTO.getKey());
    if (resourceTO.getConnector() != null) {
        ConnInstance connector = connInstanceDAO.find(resourceTO.getConnector());
        resource.setConnector(connector);
        if (!connector.getResources().contains(resource)) {
            connector.add(resource);
        }
    }
    resource.setEnforceMandatoryCondition(resourceTO.isEnforceMandatoryCondition());
    resource.setPropagationPriority(resourceTO.getPropagationPriority());
    resource.setRandomPwdIfNotProvided(resourceTO.isRandomPwdIfNotProvided());
    // 1. add or update all (valid) provisions from TO
    resourceTO.getProvisions().forEach(provisionTO -> {
        AnyType anyType = anyTypeDAO.find(provisionTO.getAnyType());
        if (anyType == null) {
            LOG.debug("Invalid {} specified {}, ignoring...", AnyType.class.getSimpleName(), provisionTO.getAnyType());
        } else {
            Provision provision = resource.getProvision(anyType).orElse(null);
            if (provision == null) {
                provision = entityFactory.newEntity(Provision.class);
                provision.setResource(resource);
                resource.add(provision);
                provision.setAnyType(anyType);
            }
            if (provisionTO.getObjectClass() == null) {
                SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidProvision);
                sce.getElements().add("Null " + ObjectClass.class.getSimpleName());
                throw sce;
            }
            provision.setObjectClass(new ObjectClass(provisionTO.getObjectClass()));
            // add all classes contained in the TO
            for (String name : provisionTO.getAuxClasses()) {
                AnyTypeClass anyTypeClass = anyTypeClassDAO.find(name);
                if (anyTypeClass == null) {
                    LOG.warn("Ignoring invalid {}: {}", AnyTypeClass.class.getSimpleName(), name);
                } else {
                    provision.add(anyTypeClass);
                }
            }
            // remove all classes not contained in the TO
            provision.getAuxClasses().removeIf(anyTypeClass -> !provisionTO.getAuxClasses().contains(anyTypeClass.getKey()));
            if (provisionTO.getMapping() == null) {
                provision.setMapping(null);
            } else {
                Mapping mapping = provision.getMapping();
                if (mapping == null) {
                    mapping = entityFactory.newEntity(Mapping.class);
                    mapping.setProvision(provision);
                    provision.setMapping(mapping);
                } else {
                    mapping.getItems().clear();
                }
                AnyTypeClassTO allowedSchemas = new AnyTypeClassTO();
                for (Iterator<AnyTypeClass> itor = new IteratorChain<>(provision.getAnyType().getClasses().iterator(), provision.getAuxClasses().iterator()); itor.hasNext(); ) {
                    AnyTypeClass anyTypeClass = itor.next();
                    allowedSchemas.getPlainSchemas().addAll(anyTypeClass.getPlainSchemas().stream().map(s -> s.getKey()).collect(Collectors.toList()));
                    allowedSchemas.getDerSchemas().addAll(anyTypeClass.getDerSchemas().stream().map(s -> s.getKey()).collect(Collectors.toList()));
                    allowedSchemas.getVirSchemas().addAll(anyTypeClass.getVirSchemas().stream().map(s -> s.getKey()).collect(Collectors.toList()));
                }
                populateMapping(provisionTO.getMapping(), mapping, allowedSchemas);
            }
            if (provisionTO.getVirSchemas().isEmpty()) {
                for (VirSchema schema : virSchemaDAO.findByProvision(provision)) {
                    virSchemaDAO.delete(schema.getKey());
                }
            } else {
                for (String schemaName : provisionTO.getVirSchemas()) {
                    VirSchema schema = virSchemaDAO.find(schemaName);
                    if (schema == null) {
                        LOG.debug("Invalid {} specified: {}, ignoring...", VirSchema.class.getSimpleName(), schemaName);
                    } else {
                        schema.setProvision(provision);
                    }
                }
            }
        }
    });
    // 2. remove all provisions not contained in the TO
    for (Iterator<? extends Provision> itor = resource.getProvisions().iterator(); itor.hasNext(); ) {
        Provision provision = itor.next();
        if (resourceTO.getProvision(provision.getAnyType().getKey()) == null) {
            virSchemaDAO.findByProvision(provision).forEach(schema -> {
                virSchemaDAO.delete(schema.getKey());
            });
            itor.remove();
        }
    }
    // 3. orgUnit
    if (resourceTO.getOrgUnit() == null && resource.getOrgUnit() != null) {
        resource.getOrgUnit().setResource(null);
        resource.setOrgUnit(null);
    } else if (resourceTO.getOrgUnit() != null) {
        OrgUnitTO orgUnitTO = resourceTO.getOrgUnit();
        OrgUnit orgUnit = resource.getOrgUnit();
        if (orgUnit == null) {
            orgUnit = entityFactory.newEntity(OrgUnit.class);
            orgUnit.setResource(resource);
            resource.setOrgUnit(orgUnit);
        }
        if (orgUnitTO.getObjectClass() == null) {
            SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidOrgUnit);
            sce.getElements().add("Null " + ObjectClass.class.getSimpleName());
            throw sce;
        }
        orgUnit.setObjectClass(new ObjectClass(orgUnitTO.getObjectClass()));
        if (orgUnitTO.getConnObjectLink() == null) {
            SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidOrgUnit);
            sce.getElements().add("Null connObjectLink");
            throw sce;
        }
        orgUnit.setConnObjectLink(orgUnitTO.getConnObjectLink());
        SyncopeClientCompositeException scce = SyncopeClientException.buildComposite();
        SyncopeClientException invalidMapping = SyncopeClientException.build(ClientExceptionType.InvalidMapping);
        SyncopeClientException requiredValuesMissing = SyncopeClientException.build(ClientExceptionType.RequiredValuesMissing);
        orgUnit.getItems().clear();
        for (ItemTO itemTO : orgUnitTO.getItems()) {
            if (itemTO == null) {
                LOG.error("Null {}", ItemTO.class.getSimpleName());
                invalidMapping.getElements().add("Null " + ItemTO.class.getSimpleName());
            } else if (itemTO.getIntAttrName() == null) {
                requiredValuesMissing.getElements().add("intAttrName");
                scce.addException(requiredValuesMissing);
            } else {
                if (!"name".equals(itemTO.getIntAttrName()) && !"fullpath".equals(itemTO.getIntAttrName())) {
                    LOG.error("Only 'name' and 'fullpath' are supported for Realms");
                    invalidMapping.getElements().add("Only 'name' and 'fullpath' are supported for Realms");
                } else {
                    // no mandatory condition implies mandatory condition false
                    if (!JexlUtils.isExpressionValid(itemTO.getMandatoryCondition() == null ? "false" : itemTO.getMandatoryCondition())) {
                        SyncopeClientException invalidMandatoryCondition = SyncopeClientException.build(ClientExceptionType.InvalidValues);
                        invalidMandatoryCondition.getElements().add(itemTO.getMandatoryCondition());
                        scce.addException(invalidMandatoryCondition);
                    }
                    OrgUnitItem item = entityFactory.newEntity(OrgUnitItem.class);
                    BeanUtils.copyProperties(itemTO, item, ITEM_IGNORE_PROPERTIES);
                    item.setOrgUnit(orgUnit);
                    if (item.isConnObjectKey()) {
                        orgUnit.setConnObjectKeyItem(item);
                    } else {
                        orgUnit.add(item);
                    }
                    itemTO.getTransformers().forEach(transformerKey -> {
                        Implementation transformer = implementationDAO.find(transformerKey);
                        if (transformer == null) {
                            LOG.debug("Invalid " + Implementation.class.getSimpleName() + " {}, ignoring...", transformerKey);
                        } else {
                            item.add(transformer);
                        }
                    });
                    // remove all implementations not contained in the TO
                    item.getTransformers().removeIf(implementation -> !itemTO.getTransformers().contains(implementation.getKey()));
                }
            }
        }
        if (!invalidMapping.getElements().isEmpty()) {
            scce.addException(invalidMapping);
        }
        if (scce.hasExceptions()) {
            throw scce;
        }
    }
    resource.setCreateTraceLevel(resourceTO.getCreateTraceLevel());
    resource.setUpdateTraceLevel(resourceTO.getUpdateTraceLevel());
    resource.setDeleteTraceLevel(resourceTO.getDeleteTraceLevel());
    resource.setProvisioningTraceLevel(resourceTO.getProvisioningTraceLevel());
    resource.setPasswordPolicy(resourceTO.getPasswordPolicy() == null ? null : (PasswordPolicy) policyDAO.find(resourceTO.getPasswordPolicy()));
    resource.setAccountPolicy(resourceTO.getAccountPolicy() == null ? null : (AccountPolicy) policyDAO.find(resourceTO.getAccountPolicy()));
    resource.setPullPolicy(resourceTO.getPullPolicy() == null ? null : (PullPolicy) policyDAO.find(resourceTO.getPullPolicy()));
    resource.setConfOverride(new HashSet<>(resourceTO.getConfOverride()));
    resource.setOverrideCapabilities(resourceTO.isOverrideCapabilities());
    resource.getCapabilitiesOverride().clear();
    resource.getCapabilitiesOverride().addAll(resourceTO.getCapabilitiesOverride());
    resourceTO.getPropagationActions().forEach(propagationActionKey -> {
        Implementation propagationAction = implementationDAO.find(propagationActionKey);
        if (propagationAction == null) {
            LOG.debug("Invalid " + Implementation.class.getSimpleName() + " {}, ignoring...", propagationActionKey);
        } else {
            resource.add(propagationAction);
        }
    });
    // remove all implementations not contained in the TO
    resource.getPropagationActions().removeIf(implementation -> !resourceTO.getPropagationActions().contains(implementation.getKey()));
    return resource;
}
Also used : OrgUnit(org.apache.syncope.core.persistence.api.entity.resource.OrgUnit) Mapping(org.apache.syncope.core.persistence.api.entity.resource.Mapping) ItemTO(org.apache.syncope.common.lib.to.ItemTO) ConnInstance(org.apache.syncope.core.persistence.api.entity.ConnInstance) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation) PasswordPolicy(org.apache.syncope.core.persistence.api.entity.policy.PasswordPolicy) AnyTypeClassTO(org.apache.syncope.common.lib.to.AnyTypeClassTO) PullPolicy(org.apache.syncope.core.persistence.api.entity.policy.PullPolicy) AnyType(org.apache.syncope.core.persistence.api.entity.AnyType) AnyTypeClass(org.apache.syncope.core.persistence.api.entity.AnyTypeClass) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) SyncopeClientCompositeException(org.apache.syncope.common.lib.SyncopeClientCompositeException) ObjectClass(org.identityconnectors.framework.common.objects.ObjectClass) ExternalResourceHistoryConf(org.apache.syncope.core.persistence.api.entity.resource.ExternalResourceHistoryConf) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) OrgUnitItem(org.apache.syncope.core.persistence.api.entity.resource.OrgUnitItem) IteratorChain(org.apache.syncope.common.lib.collections.IteratorChain) Date(java.util.Date) AccountPolicy(org.apache.syncope.core.persistence.api.entity.policy.AccountPolicy) OrgUnitTO(org.apache.syncope.common.lib.to.OrgUnitTO) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO)

Example 32 with ResourceTO

use of org.apache.syncope.common.lib.to.ResourceTO in project syncope by apache.

the class MembershipITCase method pull.

@Test
public void pull() {
    // 0. create ad-hoc resource, with adequate mapping
    ResourceTO newResource = resourceService.read(RESOURCE_NAME_DBPULL);
    newResource.setKey(getUUIDString());
    ItemTO item = newResource.getProvision("USER").get().getMapping().getItems().stream().filter(object -> "firstname".equals(object.getIntAttrName())).findFirst().get();
    assertNotNull(item);
    assertEquals("ID", item.getExtAttrName());
    item.setIntAttrName("memberships[additional].aLong");
    item.setPurpose(MappingPurpose.BOTH);
    item = newResource.getProvision("USER").get().getMapping().getItems().stream().filter(object -> "fullname".equals(object.getIntAttrName())).findFirst().get();
    item.setPurpose(MappingPurpose.PULL);
    PullTaskTO newTask = null;
    try {
        newResource = createResource(newResource);
        assertNotNull(newResource);
        // 1. create user with new resource assigned
        UserTO user = UserITCase.getUniqueSampleTO("memb@apache.org");
        user.setRealm("/even/two");
        user.getPlainAttrs().remove(user.getPlainAttr("ctype").get());
        user.getResources().clear();
        user.getResources().add(newResource.getKey());
        MembershipTO membership = new MembershipTO.Builder().group("034740a9-fa10-453b-af37-dc7897e98fb1").build();
        membership.getPlainAttrs().add(new AttrTO.Builder().schema("aLong").value("5432").build());
        user.getMemberships().add(membership);
        user = createUser(user).getEntity();
        assertNotNull(user);
        // 2. verify that user was found on resource
        JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
        String idOnResource = queryForObject(jdbcTemplate, 50, "SELECT id FROM testpull WHERE id=?", String.class, "5432");
        assertEquals("5432", idOnResource);
        // 3. unlink user from resource, then remove it
        DeassociationPatch patch = new DeassociationPatch();
        patch.setKey(user.getKey());
        patch.setAction(ResourceDeassociationAction.UNLINK);
        patch.getResources().add(newResource.getKey());
        assertNotNull(userService.deassociate(patch).readEntity(BulkActionResult.class));
        userService.delete(user.getKey());
        // 4. create pull task and execute
        newTask = taskService.read(TaskType.PULL, "7c2242f4-14af-4ab5-af31-cdae23783655", true);
        newTask.setResource(newResource.getKey());
        newTask.setDestinationRealm("/even/two");
        Response response = taskService.create(TaskType.PULL, newTask);
        newTask = getObject(response.getLocation(), TaskService.class, PullTaskTO.class);
        assertNotNull(newTask);
        ExecTO execution = AbstractTaskITCase.execProvisioningTask(taskService, TaskType.PULL, newTask.getKey(), 50, false);
        assertEquals(PropagationTaskExecStatus.SUCCESS, PropagationTaskExecStatus.valueOf(execution.getStatus()));
        // 5. verify that pulled user has
        PagedResult<UserTO> users = userService.search(new AnyQuery.Builder().realm("/").fiql(SyncopeClient.getUserSearchConditionBuilder().is("username").equalTo(user.getUsername()).query()).build());
        assertEquals(1, users.getTotalCount());
        assertEquals(1, users.getResult().get(0).getMemberships().size());
        assertEquals("5432", users.getResult().get(0).getMemberships().get(0).getPlainAttr("aLong").get().getValues().get(0));
    } catch (Exception e) {
        LOG.error("Unexpected error", e);
        fail(e.getMessage());
    } finally {
        if (newTask != null && !"83f7e85d-9774-43fe-adba-ccd856312994".equals(newTask.getKey())) {
            taskService.delete(TaskType.PULL, newTask.getKey());
        }
        resourceService.delete(newResource.getKey());
    }
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) TaskService(org.apache.syncope.common.rest.api.service.TaskService) PropagationTaskExecStatus(org.apache.syncope.common.lib.types.PropagationTaskExecStatus) AttrTO(org.apache.syncope.common.lib.to.AttrTO) Autowired(org.springframework.beans.factory.annotation.Autowired) UserPatch(org.apache.syncope.common.lib.patch.UserPatch) ResourceDeassociationAction(org.apache.syncope.common.lib.types.ResourceDeassociationAction) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) SpringJUnitConfig(org.springframework.test.context.junit.jupiter.SpringJUnitConfig) MembershipPatch(org.apache.syncope.common.lib.patch.MembershipPatch) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) DataSource(javax.sql.DataSource) ItemTO(org.apache.syncope.common.lib.to.ItemTO) ClientExceptionType(org.apache.syncope.common.lib.types.ClientExceptionType) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) AbstractITCase(org.apache.syncope.fit.AbstractITCase) AnyQuery(org.apache.syncope.common.rest.api.beans.AnyQuery) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) PagedResult(org.apache.syncope.common.lib.to.PagedResult) ExecTO(org.apache.syncope.common.lib.to.ExecTO) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) BulkActionResult(org.apache.syncope.common.lib.to.BulkActionResult) GroupTO(org.apache.syncope.common.lib.to.GroupTO) Test(org.junit.jupiter.api.Test) AttrPatch(org.apache.syncope.common.lib.patch.AttrPatch) TypeExtensionTO(org.apache.syncope.common.lib.to.TypeExtensionTO) Response(javax.ws.rs.core.Response) MappingPurpose(org.apache.syncope.common.lib.types.MappingPurpose) DeassociationPatch(org.apache.syncope.common.lib.patch.DeassociationPatch) PatchOperation(org.apache.syncope.common.lib.types.PatchOperation) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) PullTaskTO(org.apache.syncope.common.lib.to.PullTaskTO) SyncopeClient(org.apache.syncope.client.lib.SyncopeClient) UserTO(org.apache.syncope.common.lib.to.UserTO) TaskType(org.apache.syncope.common.lib.types.TaskType) ExecTO(org.apache.syncope.common.lib.to.ExecTO) TaskService(org.apache.syncope.common.rest.api.service.TaskService) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) ItemTO(org.apache.syncope.common.lib.to.ItemTO) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) Response(javax.ws.rs.core.Response) DeassociationPatch(org.apache.syncope.common.lib.patch.DeassociationPatch) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) UserTO(org.apache.syncope.common.lib.to.UserTO) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) PullTaskTO(org.apache.syncope.common.lib.to.PullTaskTO) BulkActionResult(org.apache.syncope.common.lib.to.BulkActionResult) Test(org.junit.jupiter.api.Test)

Example 33 with ResourceTO

use of org.apache.syncope.common.lib.to.ResourceTO in project syncope by apache.

the class MultitenancyITCase method createResourceAndPull.

@Test
public void createResourceAndPull() {
    // read connector
    ConnInstanceTO conn = adminClient.getService(ConnectorService.class).read("b7ea96c3-c633-488b-98a0-b52ac35850f7", Locale.ENGLISH.getLanguage());
    assertNotNull(conn);
    assertEquals("LDAP", conn.getDisplayName());
    // prepare resource
    ResourceTO resource = new ResourceTO();
    resource.setKey("new-ldap-resource");
    resource.setConnector(conn.getKey());
    try {
        ProvisionTO provisionTO = new ProvisionTO();
        provisionTO.setAnyType(AnyTypeKind.USER.name());
        provisionTO.setObjectClass(ObjectClass.ACCOUNT_NAME);
        resource.getProvisions().add(provisionTO);
        MappingTO mapping = new MappingTO();
        mapping.setConnObjectLink("'uid=' + username + ',ou=people,o=isp'");
        provisionTO.setMapping(mapping);
        ItemTO item = new ItemTO();
        item.setIntAttrName("username");
        item.setExtAttrName("cn");
        item.setPurpose(MappingPurpose.BOTH);
        mapping.setConnObjectKeyItem(item);
        item = new ItemTO();
        item.setPassword(true);
        item.setIntAttrName("password");
        item.setExtAttrName("userPassword");
        item.setPurpose(MappingPurpose.BOTH);
        item.setMandatoryCondition("true");
        mapping.add(item);
        item = new ItemTO();
        item.setIntAttrName("key");
        item.setPurpose(MappingPurpose.BOTH);
        item.setExtAttrName("sn");
        item.setMandatoryCondition("true");
        mapping.add(item);
        item = new ItemTO();
        item.setIntAttrName("email");
        item.setPurpose(MappingPurpose.BOTH);
        item.setExtAttrName("mail");
        mapping.add(item);
        // create resource
        Response response = adminClient.getService(ResourceService.class).create(resource);
        assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
        resource = adminClient.getService(ResourceService.class).read(resource.getKey());
        assertNotNull(resource);
        // create pull task
        PullTaskTO task = new PullTaskTO();
        task.setName("LDAP Pull Task");
        task.setActive(true);
        task.setDestinationRealm(SyncopeConstants.ROOT_REALM);
        task.setResource(resource.getKey());
        task.setPullMode(PullMode.FULL_RECONCILIATION);
        task.setPerformCreate(true);
        response = adminClient.getService(TaskService.class).create(TaskType.PULL, task);
        assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
        task = adminClient.getService(TaskService.class).read(TaskType.PULL, StringUtils.substringAfterLast(response.getLocation().toASCIIString(), "/"), true);
        assertNotNull(resource);
        // pull
        ExecTO execution = AbstractTaskITCase.execProvisioningTask(adminClient.getService(TaskService.class), TaskType.PULL, task.getKey(), 50, false);
        // verify execution status
        String status = execution.getStatus();
        assertNotNull(status);
        assertEquals(PropagationTaskExecStatus.SUCCESS, PropagationTaskExecStatus.valueOf(status));
        // verify that pulled user is found
        PagedResult<UserTO> matchingUsers = adminClient.getService(UserService.class).search(new AnyQuery.Builder().realm(SyncopeConstants.ROOT_REALM).fiql(SyncopeClient.getUserSearchConditionBuilder().is("username").equalTo("pullFromLDAP").query()).build());
        assertNotNull(matchingUsers);
        assertEquals(1, matchingUsers.getResult().size());
    } finally {
        adminClient.getService(ResourceService.class).delete(resource.getKey());
    }
}
Also used : ExecTO(org.apache.syncope.common.lib.to.ExecTO) UserService(org.apache.syncope.common.rest.api.service.UserService) TaskService(org.apache.syncope.common.rest.api.service.TaskService) ResourceService(org.apache.syncope.common.rest.api.service.ResourceService) ItemTO(org.apache.syncope.common.lib.to.ItemTO) ConnectorService(org.apache.syncope.common.rest.api.service.ConnectorService) Response(javax.ws.rs.core.Response) MappingTO(org.apache.syncope.common.lib.to.MappingTO) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) UserTO(org.apache.syncope.common.lib.to.UserTO) ConnInstanceTO(org.apache.syncope.common.lib.to.ConnInstanceTO) PullTaskTO(org.apache.syncope.common.lib.to.PullTaskTO) ProvisionTO(org.apache.syncope.common.lib.to.ProvisionTO) Test(org.junit.jupiter.api.Test)

Example 34 with ResourceTO

use of org.apache.syncope.common.lib.to.ResourceTO in project syncope by apache.

the class PropagationTaskITCase method propagationJEXLTransformer.

@Test
public void propagationJEXLTransformer() {
    // 0. Set propagation JEXL MappingItemTransformer
    ResourceTO resource = resourceService.read(RESOURCE_NAME_DBSCRIPTED);
    ResourceTO originalResource = SerializationUtils.clone(resource);
    ProvisionTO provision = resource.getProvision("PRINTER").get();
    assertNotNull(provision);
    Optional<ItemTO> mappingItem = provision.getMapping().getItems().stream().filter(item -> "location".equals(item.getIntAttrName())).findFirst();
    assertTrue(mappingItem.isPresent());
    assertTrue(mappingItem.get().getTransformers().isEmpty());
    String suffix = getUUIDString();
    mappingItem.get().setPropagationJEXLTransformer("value + '" + suffix + "'");
    try {
        resourceService.update(resource);
        // 1. create printer on external resource
        AnyObjectTO anyObjectTO = AnyObjectITCase.getSampleTO("propagationJEXLTransformer");
        String originalLocation = anyObjectTO.getPlainAttr("location").get().getValues().get(0);
        assertFalse(originalLocation.endsWith(suffix));
        anyObjectTO = createAnyObject(anyObjectTO).getEntity();
        assertNotNull(anyObjectTO);
        // 2. verify that JEXL MappingItemTransformer was applied during propagation
        // (location ends with given suffix on external resource)
        ConnObjectTO connObjectTO = resourceService.readConnObject(RESOURCE_NAME_DBSCRIPTED, anyObjectTO.getType(), anyObjectTO.getKey());
        assertFalse(anyObjectTO.getPlainAttr("location").get().getValues().get(0).endsWith(suffix));
        assertTrue(connObjectTO.getAttr("LOCATION").get().getValues().get(0).endsWith(suffix));
    } finally {
        resourceService.update(originalResource);
    }
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) ExecuteQuery(org.apache.syncope.common.rest.api.beans.ExecuteQuery) ProvisionTO(org.apache.syncope.common.lib.to.ProvisionTO) TaskTO(org.apache.syncope.common.lib.to.TaskTO) AttrTO(org.apache.syncope.common.lib.to.AttrTO) SerializationUtils(org.apache.commons.lang3.SerializationUtils) ProvisioningResult(org.apache.syncope.common.lib.to.ProvisioningResult) ConnObjectTO(org.apache.syncope.common.lib.to.ConnObjectTO) ArrayList(java.util.ArrayList) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) PropagationTaskTO(org.apache.syncope.common.lib.to.PropagationTaskTO) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) ItemTO(org.apache.syncope.common.lib.to.ItemTO) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) PagedResult(org.apache.syncope.common.lib.to.PagedResult) ExecTO(org.apache.syncope.common.lib.to.ExecTO) TaskQuery(org.apache.syncope.common.rest.api.beans.TaskQuery) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) ExecQuery(org.apache.syncope.common.rest.api.beans.ExecQuery) Test(org.junit.jupiter.api.Test) List(java.util.List) MappingPurpose(org.apache.syncope.common.lib.types.MappingPurpose) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Optional(java.util.Optional) BulkAction(org.apache.syncope.common.lib.to.BulkAction) UserTO(org.apache.syncope.common.lib.to.UserTO) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) TaskType(org.apache.syncope.common.lib.types.TaskType) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) ProvisionTO(org.apache.syncope.common.lib.to.ProvisionTO) ConnObjectTO(org.apache.syncope.common.lib.to.ConnObjectTO) ItemTO(org.apache.syncope.common.lib.to.ItemTO) Test(org.junit.jupiter.api.Test)

Example 35 with ResourceTO

use of org.apache.syncope.common.lib.to.ResourceTO in project syncope by apache.

the class PullTaskITCase method reconcileFromScriptedSQL.

@Test
public void reconcileFromScriptedSQL() throws IOException {
    // 0. reset sync token and set MappingItemTransformer
    ResourceTO resource = resourceService.read(RESOURCE_NAME_DBSCRIPTED);
    ResourceTO originalResource = SerializationUtils.clone(resource);
    ProvisionTO provision = resource.getProvision("PRINTER").get();
    assertNotNull(provision);
    ItemTO mappingItem = provision.getMapping().getItems().stream().filter(object -> "location".equals(object.getIntAttrName())).findFirst().get();
    assertNotNull(mappingItem);
    final String prefix = "PREFIX_";
    ImplementationTO transformer = new ImplementationTO();
    transformer.setKey("PrefixItemTransformer");
    transformer.setEngine(ImplementationEngine.GROOVY);
    transformer.setType(ImplementationType.ITEM_TRANSFORMER);
    transformer.setBody(IOUtils.toString(getClass().getResourceAsStream("/PrefixItemTransformer.groovy"), StandardCharsets.UTF_8));
    Response response = implementationService.create(transformer);
    transformer = implementationService.read(transformer.getType(), response.getHeaderString(RESTHeaders.RESOURCE_KEY));
    assertNotNull(transformer);
    mappingItem.getTransformers().clear();
    mappingItem.getTransformers().add(transformer.getKey());
    try {
        resourceService.update(resource);
        resourceService.removeSyncToken(resource.getKey(), provision.getAnyType());
        // insert a deleted record in the external resource (SYNCOPE-923), which will be returned
        // as sync event prior to the CREATE_OR_UPDATE events generated by the actions below (before pull)
        JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
        jdbcTemplate.update("INSERT INTO TESTPRINTER (id, printername, location, deleted, lastmodification) VALUES (?,?,?,?,?)", UUID.randomUUID().toString(), "Mysterious Printer", "Nowhere", true, new Date());
        // 1. create printer on external resource
        AnyObjectTO anyObjectTO = AnyObjectITCase.getSampleTO("pull");
        String originalLocation = anyObjectTO.getPlainAttr("location").get().getValues().get(0);
        assertFalse(originalLocation.startsWith(prefix));
        anyObjectTO = createAnyObject(anyObjectTO).getEntity();
        assertNotNull(anyObjectTO);
        // 2. verify that PrefixMappingItemTransformer was applied during propagation
        // (location starts with given prefix on external resource)
        ConnObjectTO connObjectTO = resourceService.readConnObject(RESOURCE_NAME_DBSCRIPTED, anyObjectTO.getType(), anyObjectTO.getKey());
        assertFalse(anyObjectTO.getPlainAttr("location").get().getValues().get(0).startsWith(prefix));
        assertTrue(connObjectTO.getAttr("LOCATION").get().getValues().get(0).startsWith(prefix));
        // 3. unlink any existing printer and delete from Syncope (printer is now only on external resource)
        PagedResult<AnyObjectTO> matchingPrinters = anyObjectService.search(new AnyQuery.Builder().realm(SyncopeConstants.ROOT_REALM).fiql(SyncopeClient.getAnyObjectSearchConditionBuilder("PRINTER").is("location").equalTo("pull*").query()).build());
        assertTrue(matchingPrinters.getSize() > 0);
        for (AnyObjectTO printer : matchingPrinters.getResult()) {
            anyObjectService.deassociate(new DeassociationPatch.Builder().key(printer.getKey()).action(ResourceDeassociationAction.UNLINK).resource(RESOURCE_NAME_DBSCRIPTED).build());
            anyObjectService.delete(printer.getKey());
        }
        // ensure that the pull task does not have the DELETE capability (SYNCOPE-923)
        PullTaskTO pullTask = taskService.read(TaskType.PULL, "30cfd653-257b-495f-8665-281281dbcb3d", false);
        assertNotNull(pullTask);
        assertFalse(pullTask.isPerformDelete());
        // 4. pull
        execProvisioningTask(taskService, TaskType.PULL, pullTask.getKey(), 50, false);
        // 5. verify that printer was re-created in Syncope (implies that location does not start with given prefix,
        // hence PrefixItemTransformer was applied during pull)
        matchingPrinters = anyObjectService.search(new AnyQuery.Builder().realm(SyncopeConstants.ROOT_REALM).fiql(SyncopeClient.getAnyObjectSearchConditionBuilder("PRINTER").is("location").equalTo("pull*").query()).build());
        assertTrue(matchingPrinters.getSize() > 0);
        // 6. verify that synctoken was updated
        assertNotNull(resourceService.read(RESOURCE_NAME_DBSCRIPTED).getProvision(anyObjectTO.getType()).get().getSyncToken());
    } finally {
        resourceService.update(originalResource);
    }
}
Also used : JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) ItemTO(org.apache.syncope.common.lib.to.ItemTO) Date(java.util.Date) ImplementationTO(org.apache.syncope.common.lib.to.ImplementationTO) Response(javax.ws.rs.core.Response) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) DeassociationPatch(org.apache.syncope.common.lib.patch.DeassociationPatch) ResourceTO(org.apache.syncope.common.lib.to.ResourceTO) PullTaskTO(org.apache.syncope.common.lib.to.PullTaskTO) ProvisionTO(org.apache.syncope.common.lib.to.ProvisionTO) ConnObjectTO(org.apache.syncope.common.lib.to.ConnObjectTO) AnyQuery(org.apache.syncope.common.rest.api.beans.AnyQuery) Test(org.junit.jupiter.api.Test)

Aggregations

ResourceTO (org.apache.syncope.common.lib.to.ResourceTO)61 Test (org.junit.jupiter.api.Test)49 ItemTO (org.apache.syncope.common.lib.to.ItemTO)32 ProvisionTO (org.apache.syncope.common.lib.to.ProvisionTO)29 SyncopeClientException (org.apache.syncope.common.lib.SyncopeClientException)27 Response (javax.ws.rs.core.Response)23 MappingTO (org.apache.syncope.common.lib.to.MappingTO)23 UserTO (org.apache.syncope.common.lib.to.UserTO)17 ConnInstanceTO (org.apache.syncope.common.lib.to.ConnInstanceTO)14 ConnObjectTO (org.apache.syncope.common.lib.to.ConnObjectTO)12 ResourceService (org.apache.syncope.common.rest.api.service.ResourceService)11 UserPatch (org.apache.syncope.common.lib.patch.UserPatch)10 GroupTO (org.apache.syncope.common.lib.to.GroupTO)10 ConnConfProperty (org.apache.syncope.common.lib.types.ConnConfProperty)9 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)9 AnyTypeKind (org.apache.syncope.common.lib.types.AnyTypeKind)8 Assertions.assertEquals (org.junit.jupiter.api.Assertions.assertEquals)8 Assertions.assertFalse (org.junit.jupiter.api.Assertions.assertFalse)8 Assertions.assertNotNull (org.junit.jupiter.api.Assertions.assertNotNull)8 Assertions.assertTrue (org.junit.jupiter.api.Assertions.assertTrue)8