Search in sources :

Example 91 with ItemDelta

use of com.evolveum.midpoint.prism.delta.ItemDelta in project midpoint by Evolveum.

the class ModifyTest method test130ExtensionModify.

@Test
public void test130ExtensionModify() throws Exception {
    final String TEST_NAME = "test130ExtensionModify";
    TestUtil.displayTestTile(TEST_NAME);
    final QName QNAME_LOOT = new QName("http://example.com/p", "loot");
    File userFile = new File(TEST_DIR, "user-with-extension.xml");
    //add first user
    PrismObject<UserType> user = prismContext.parseObject(userFile);
    OperationResult result = new OperationResult("test extension modify");
    final String oid = repositoryService.addObject(user, null, result);
    user = prismContext.parseObject(userFile);
    PrismObject<UserType> readUser = repositoryService.getObject(UserType.class, oid, null, result);
    AssertJUnit.assertTrue("User was not saved correctly", user.diff(readUser).isEmpty());
    String lastVersion = readUser.getVersion();
    Collection<ItemDelta> modifications = new ArrayList<ItemDelta>();
    ItemPath path = new ItemPath(UserType.F_EXTENSION, QNAME_LOOT);
    PrismProperty loot = user.findProperty(path);
    PropertyDelta lootDelta = new PropertyDelta(path, loot.getDefinition(), prismContext);
    lootDelta.setValueToReplace(new PrismPropertyValue(456));
    modifications.add(lootDelta);
    repositoryService.modifyObject(UserType.class, oid, modifications, getModifyOptions(), result);
    //check read after modify operation
    user = prismContext.parseObject(userFile);
    loot = user.findProperty(new ItemPath(UserType.F_EXTENSION, QNAME_LOOT));
    loot.setValue(new PrismPropertyValue(456));
    readUser = repositoryService.getObject(UserType.class, oid, null, result);
    AssertJUnit.assertTrue("User was not modified correctly", user.diff(readUser).isEmpty());
    SqlRepoTestUtil.assertVersionProgress(lastVersion, readUser.getVersion());
}
Also used : QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) File(java.io.File) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) Test(org.testng.annotations.Test)

Example 92 with ItemDelta

use of com.evolveum.midpoint.prism.delta.ItemDelta in project midpoint by Evolveum.

the class CertificationCaseHelper method updateCasesContent.

private void updateCasesContent(Session session, String campaignOid, Collection<? extends ItemDelta> modifications, List<Long> casesAddedOrDeleted, RepoModifyOptions modifyOptions) throws SchemaException, ObjectNotFoundException, DtoTranslationException {
    Set<Long> casesModified = new HashSet<>();
    for (ItemDelta delta : modifications) {
        ItemPath deltaPath = delta.getPath();
        if (deltaPath.size() > 1) {
            LOGGER.trace("Updating campaign " + campaignOid + " with delta " + delta);
            // should start with "case[id]"
            long id = checkPathSanity(deltaPath, casesAddedOrDeleted);
            Query query = session.getNamedQuery("get.campaignCase");
            query.setString("ownerOid", campaignOid);
            query.setInteger("id", (int) id);
            byte[] fullObject = (byte[]) query.uniqueResult();
            if (fullObject == null) {
                throw new ObjectNotFoundException("Couldn't update cert campaign " + campaignOid + " + by delta with path " + deltaPath + " - specified case does not exist");
            }
            AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext, false);
            // to avoid changing original modifications
            delta = delta.clone();
            // remove "case[id]" from the delta path
            delta.setParentPath(delta.getParentPath().tail(2));
            delta.applyTo(aCase.asPrismContainerValue());
            // we need to generate IDs but we (currently) do not use that for setting "isTransient" flag
            PrismIdentifierGenerator generator = new PrismIdentifierGenerator();
            generator.generate(aCase, PrismIdentifierGenerator.Operation.MODIFY);
            RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase, createRepositoryContext());
            session.merge(rCase);
            LOGGER.trace("Access certification case {} merged", rCase);
            casesModified.add(aCase.getId());
        }
    }
    // refresh campaign cases, if requested
    if (RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) {
        Query query = session.getNamedQuery("get.campaignCases");
        query.setString("ownerOid", campaignOid);
        List<Object> cases = query.list();
        for (Object o : cases) {
            if (!(o instanceof byte[])) {
                throw new IllegalStateException("Certification case: expected byte[], got " + o.getClass());
            }
            byte[] fullObject = (byte[]) o;
            AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext, false);
            Long id = aCase.getId();
            if (id != null && casesAddedOrDeleted != null && !casesAddedOrDeleted.contains(id) && !casesModified.contains(id)) {
                RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase, createRepositoryContext());
                session.merge(rCase);
                LOGGER.trace("Access certification case {} refreshed", rCase);
            }
        }
    }
}
Also used : AccessCertificationCaseType(com.evolveum.midpoint.xml.ns._public.common.common_3.AccessCertificationCaseType) Query(org.hibernate.Query) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) RQuery(com.evolveum.midpoint.repo.sql.query.RQuery) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) RAccessCertificationCase(com.evolveum.midpoint.repo.sql.data.common.container.RAccessCertificationCase) PrismObject(com.evolveum.midpoint.prism.PrismObject) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 93 with ItemDelta

use of com.evolveum.midpoint.prism.delta.ItemDelta in project midpoint by Evolveum.

the class LookupTableHelper method updateLookupTableData.

public void updateLookupTableData(Session session, String tableOid, Collection<? extends ItemDelta> modifications) throws SchemaException {
    if (modifications.isEmpty()) {
        return;
    }
    for (ItemDelta delta : modifications) {
        if (delta.getPath().size() == 1) {
            // whole row add/delete/replace
            if (!(delta instanceof ContainerDelta)) {
                throw new IllegalStateException("Wrong table delta sneaked into updateLookupTableData: class=" + delta.getClass() + ", path=" + delta.getPath());
            }
            // one "table" container modification
            ContainerDelta containerDelta = (ContainerDelta) delta;
            if (containerDelta.getValuesToDelete() != null) {
                // todo do 'bulk' delete like delete from ... where oid=? and id in (...)
                for (PrismContainerValue<LookupTableRowType> value : (Collection<PrismContainerValue>) containerDelta.getValuesToDelete()) {
                    if (value.getId() != null) {
                        deleteRowById(session, tableOid, value.getId());
                    } else if (value.asContainerable().getKey() != null) {
                        deleteRowByKey(session, tableOid, value.asContainerable().getKey());
                    } else {
                    // ignore (or throw an exception?)
                    }
                }
            }
            if (containerDelta.getValuesToAdd() != null) {
                int currentId = generalHelper.findLastIdInRepo(session, tableOid, "get.lookupTableLastId") + 1;
                addLookupTableRows(session, tableOid, containerDelta.getValuesToAdd(), currentId, true);
            }
            if (containerDelta.getValuesToReplace() != null) {
                deleteLookupTableRows(session, tableOid);
                addLookupTableRows(session, tableOid, containerDelta.getValuesToReplace(), 1, false);
            }
        } else if (delta.getPath().size() == 3) {
            // row segment modification (structure is already checked)
            List<ItemPathSegment> segments = delta.getPath().getSegments();
            Long rowId = ((IdItemPathSegment) segments.get(1)).getId();
            QName name = ((NameItemPathSegment) segments.get(2)).getName();
            RLookupTableRow row = (RLookupTableRow) session.get(RLookupTableRow.class, new RContainerId(RUtil.toInteger(rowId), tableOid));
            LookupTableRowType rowType = row.toJAXB();
            delta.setParentPath(ItemPath.EMPTY_PATH);
            delta.applyTo(rowType.asPrismContainerValue());
            if (!QNameUtil.match(name, LookupTableRowType.F_LAST_CHANGE_TIMESTAMP)) {
                // in order to get filled in via toRepo call below
                rowType.setLastChangeTimestamp(null);
            }
            RLookupTableRow rowUpdated = RLookupTableRow.toRepo(tableOid, rowType);
            session.merge(rowUpdated);
        }
    }
}
Also used : RLookupTableRow(com.evolveum.midpoint.repo.sql.data.common.other.RLookupTableRow) ContainerDelta(com.evolveum.midpoint.prism.delta.ContainerDelta) QName(javax.xml.namespace.QName) Collection(java.util.Collection) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ArrayList(java.util.ArrayList) List(java.util.List) RContainerId(com.evolveum.midpoint.repo.sql.data.common.id.RContainerId) LookupTableRowType(com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableRowType)

Example 94 with ItemDelta

use of com.evolveum.midpoint.prism.delta.ItemDelta in project midpoint by Evolveum.

the class AbstractIntegrationTest method deleteResourceAssigmentPolicy.

protected void deleteResourceAssigmentPolicy(String oid, AssignmentPolicyEnforcementType policy, boolean legalize) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
    PrismObjectDefinition<ResourceType> objectDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ResourceType.class);
    ProjectionPolicyType syncSettings = new ProjectionPolicyType();
    syncSettings.setAssignmentPolicyEnforcement(policy);
    syncSettings.setLegalize(Boolean.valueOf(legalize));
    ItemDelta deleteAssigmentEnforcement = PropertyDelta.createModificationDeleteProperty(new ItemPath(ResourceType.F_PROJECTION), objectDefinition.findPropertyDefinition(ResourceType.F_PROJECTION), syncSettings);
    Collection<ItemDelta> modifications = new ArrayList<ItemDelta>();
    modifications.add(deleteAssigmentEnforcement);
    OperationResult result = new OperationResult("Aplying sync settings");
    repositoryService.modifyObject(ResourceType.class, oid, modifications, result);
    display("Aplying sync settings result", result);
    result.computeStatus();
    TestUtil.assertSuccess("Aplying sync settings failed (result)", result);
}
Also used : ArrayList(java.util.ArrayList) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 95 with ItemDelta

use of com.evolveum.midpoint.prism.delta.ItemDelta in project midpoint by Evolveum.

the class TaskQuartzImpl method finishHandler.

//    @Override
//    public void replaceCurrentHandlerUri(String newUri, ScheduleType schedule) {
//
//        checkHandlerUriConsistency();
//        setHandlerUri(newUri);
//        setSchedule(schedule);
//    }
@Override
public void finishHandler(OperationResult parentResult) throws ObjectNotFoundException, SchemaException {
    // let us drop the current handler URI and nominate the top of the other
    // handlers stack as the current one
    LOGGER.trace("finishHandler called for handler URI {}, task {}", this.getHandlerUri(), this);
    UriStack otherHandlersUriStack = getOtherHandlersUriStack();
    if (otherHandlersUriStack != null && !otherHandlersUriStack.getUriStackEntry().isEmpty()) {
        UriStackEntry use = popFromOtherHandlersUriStack();
        setHandlerUri(use.getHandlerUri());
        setRecurrenceStatus(use.getRecurrence() != null ? TaskRecurrence.fromTaskType(use.getRecurrence()) : recurrenceFromSchedule(use.getSchedule()));
        setSchedule(use.getSchedule());
        if (use.getBinding() != null) {
            setBinding(TaskBinding.fromTaskType(use.getBinding()));
        } else {
            setBinding(bindingFromSchedule(use.getSchedule()));
        }
        for (ItemDeltaType itemDeltaType : use.getExtensionDelta()) {
            ItemDelta itemDelta = DeltaConvertor.createItemDelta(itemDeltaType, TaskType.class, taskManager.getPrismContext());
            LOGGER.trace("Applying ItemDelta to task extension; task = {}; itemDelta = {}", this, itemDelta.debugDump());
            this.modifyExtension(itemDelta);
        }
        this.setRecreateQuartzTrigger(true);
    } else {
        //setHandlerUri(null);                                                  // we want the last handler to remain set so the task can be revived
        // as there are no more handlers, let us close this task
        taskManager.closeTaskWithoutSavingState(this, parentResult);
    }
    try {
        savePendingModifications(parentResult);
        checkDependentTasksOnClose(parentResult);
    } catch (ObjectAlreadyExistsException ex) {
        throw new SystemException(ex);
    }
    LOGGER.trace("finishHandler: new current handler uri = {}, new number of handlers = {}", getHandlerUri(), getHandlersCount());
}
Also used : SystemException(com.evolveum.midpoint.util.exception.SystemException) ItemDelta(com.evolveum.midpoint.prism.delta.ItemDelta) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) ItemDeltaType(com.evolveum.prism.xml.ns._public.types_3.ItemDeltaType)

Aggregations

ItemDelta (com.evolveum.midpoint.prism.delta.ItemDelta)185 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)87 Test (org.testng.annotations.Test)66 ArrayList (java.util.ArrayList)64 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)56 Task (com.evolveum.midpoint.task.api.Task)40 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)33 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)30 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)26 PropertyDelta (com.evolveum.midpoint.prism.delta.PropertyDelta)21 QName (javax.xml.namespace.QName)21 AbstractInitializedModelIntegrationTest (com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest)20 ObjectType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType)19 LookupTableType (com.evolveum.midpoint.xml.ns._public.common.common_3.LookupTableType)15 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)15 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)14 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)14 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)14 PrismObject (com.evolveum.midpoint.prism.PrismObject)13 ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)12