Search in sources :

Example 66 with ObjectAlreadyExistsException

use of com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException in project midpoint by Evolveum.

the class AuditReindexTaskHandler method run.

@Override
public TaskRunResult run(Task coordinatorTask) {
    OperationResult opResult = new OperationResult(OperationConstants.AUDIT_REINDEX + ".run");
    opResult.setStatus(OperationResultStatus.IN_PROGRESS);
    TaskRunResult runResult = new TaskRunResult();
    runResult.setOperationResult(opResult);
    final Long expectedTotal = auditService.countObjects("select count(*) from RAuditEventRecord as aer where 1=1", null);
    AuditResultHandler resultHandler = new AuditResultHandler() {

        private AtomicInteger processedObjects = new AtomicInteger();

        @Override
        public boolean handle(AuditEventRecord auditRecord) {
            auditService.reindexEntry(auditRecord);
            processedObjects.incrementAndGet();
            return true;
        }

        @Override
        public int getProgress() {
            return processedObjects.get();
        }
    };
    if (resultHandler == null) {
        // the error should already be in the runResult
        return runResult;
    }
    try {
        LOGGER.trace("{}: expecting {} objects to be processed", taskName, expectedTotal);
        runResult.setProgress(0);
        coordinatorTask.setProgress(0);
        if (expectedTotal != null) {
            coordinatorTask.setExpectedTotal(expectedTotal);
        }
        try {
            coordinatorTask.savePendingModifications(opResult);
        } catch (ObjectAlreadyExistsException e) {
            // try block
            throw new IllegalStateException("Unexpected ObjectAlreadyExistsException when updating task progress/expectedTotal", e);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        while (true) {
            params.put("setFirstResult", firstResult);
            params.put("setMaxResults", maxResults);
            List<AuditEventRecord> records = auditService.listRecords(null, params);
            if (CollectionUtils.isNotEmpty(records)) {
                for (AuditEventRecord record : records) {
                    resultHandler.handle(record);
                    runResult.setProgress(resultHandler.getProgress());
                }
                firstResult += maxResults;
                maxResults = ((expectedTotal.intValue() - firstResult) > maxResults ? maxResults : (expectedTotal.intValue() - firstResult));
            } else {
                break;
            }
        }
        opResult.recordSuccess();
    } catch (ObjectNotFoundException e) {
        // This is bad. The resource does not exist. Permanent problem.
        logErrorAndSetResult(runResult, resultHandler, "Object not found", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    } catch (SchemaException e) {
        // Not sure about this. But most likely it is a misconfigured
        // resource or connector
        // It may be worth to retry. Error is fatal, but may not be
        // permanent.
        logErrorAndSetResult(runResult, resultHandler, "Error dealing with schema", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.TEMPORARY_ERROR);
        return runResult;
    } catch (RuntimeException e) {
        // Can be anything ... but we can't recover from that.
        // It is most likely a programming error. Does not make much sense
        // to retry.
        logErrorAndSetResult(runResult, resultHandler, "Internal error", e, OperationResultStatus.FATAL_ERROR, TaskRunResultStatus.PERMANENT_ERROR);
        return runResult;
    }
    // TODO: check last handler status
    runResult.setProgress(resultHandler.getProgress());
    runResult.setRunResultStatus(TaskRunResultStatus.FINISHED);
    String finishMessage = "Finished " + taskName + " (" + coordinatorTask + "). ";
    String statistics = "Processed " + resultHandler.getProgress() + " objects";
    opResult.createSubresult(OperationConstants.AUDIT_REINDEX + ".statistics").recordStatus(OperationResultStatus.SUCCESS, statistics);
    LOGGER.info(finishMessage + statistics);
    LOGGER.trace("{} run finished (task {}, run result {})", taskName, coordinatorTask, runResult);
    return runResult;
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) HashMap(java.util.HashMap) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) TaskRunResult(com.evolveum.midpoint.task.api.TaskRunResult) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) AuditResultHandler(com.evolveum.midpoint.audit.api.AuditResultHandler) AuditEventRecord(com.evolveum.midpoint.audit.api.AuditEventRecord) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)

Example 67 with ObjectAlreadyExistsException

use of com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException in project midpoint by Evolveum.

the class AbstractConfiguredModelIntegrationTest method initSystem.

@Override
public void initSystem(Task initTask, OperationResult initResult) throws Exception {
    LOGGER.trace("initSystem");
    // We want logging config from logback-test.xml and not from system config object
    InternalsConfig.avoidLoggingChange = true;
    super.initSystem(initTask, initResult);
    modelService.postInit(initResult);
    // System Configuration
    try {
        repoAddObjectFromFile(getSystemConfigurationFile(), initResult);
    } catch (ObjectAlreadyExistsException e) {
        throw new ObjectAlreadyExistsException("System configuration already exists in repository;" + "looks like the previous test haven't cleaned it up", e);
    }
    // Users
    userAdministrator = repoAddObjectFromFile(USER_ADMINISTRATOR_FILE, UserType.class, initResult);
    repoAddObjectFromFile(ROLE_SUPERUSER_FILE, initResult);
    login(userAdministrator);
}
Also used : ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)

Example 68 with ObjectAlreadyExistsException

use of com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException in project midpoint by Evolveum.

the class WfProcessInstanceShadowTaskHandler method queryProcessInstance.

private void queryProcessInstance(String id, Task task, OperationResult parentResult) {
    String taskOid = task.getOid();
    Validate.notEmpty(taskOid, "Task oid must not be null or empty (task must be persistent).");
    OperationResult result = parentResult.createSubresult(DOT_CLASS + "queryProcessInstance");
    QueryProcessCommand qpc = new QueryProcessCommand();
    qpc.setTaskOid(taskOid);
    qpc.setPid(id);
    try {
        activitiInterface.queryActivitiProcessInstance(qpc, task, result);
    } catch (RuntimeException | ObjectNotFoundException | ObjectAlreadyExistsException | SchemaException e) {
        LoggingUtils.logUnexpectedException(LOGGER, "Couldn't send a request to query a process instance to workflow management system", e);
        result.recordPartialError("Couldn't send a request to query a process instance to workflow management system", e);
    } finally {
        result.computeStatusIfUnknown();
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) QueryProcessCommand(com.evolveum.midpoint.wf.impl.messages.QueryProcessCommand) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)

Example 69 with ObjectAlreadyExistsException

use of com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException in project midpoint by Evolveum.

the class ShadowManager method modifyShadowAttributes.

/**
	 * Really modifies shadow attributes. It applies the changes. It is used for synchronous operations and also for
	 * applying the results of completed asynchronous operations. 
	 */
public void modifyShadowAttributes(ProvisioningContext ctx, PrismObject<ShadowType> shadow, Collection<? extends ItemDelta> modifications, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ConfigurationException, CommunicationException, ExpressionEvaluationException {
    Collection<? extends ItemDelta> shadowChanges = extractRepoShadowChanges(ctx, shadow, modifications);
    if (shadowChanges != null && !shadowChanges.isEmpty()) {
        LOGGER.trace("Detected shadow changes. Start to modify shadow in the repository, applying modifications {}", DebugUtil.debugDump(shadowChanges));
        try {
            ConstraintsChecker.onShadowModifyOperation(shadowChanges);
            repositoryService.modifyObject(ShadowType.class, shadow.getOid(), shadowChanges, parentResult);
            LOGGER.trace("Shadow changes processed successfully.");
        } catch (ObjectAlreadyExistsException ex) {
            throw new SystemException(ex);
        }
    }
}
Also used : SystemException(com.evolveum.midpoint.util.exception.SystemException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)

Example 70 with ObjectAlreadyExistsException

use of com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException in project midpoint by Evolveum.

the class ShadowManager method updateShadow.

/**
	 * Updates repository shadow based on shadow from resource. Handles rename cases,
	 * change of auxiliary object classes, etc.
	 * @returns repository shadow as it should look like after the update
	 */
@SuppressWarnings("unchecked")
public PrismObject<ShadowType> updateShadow(ProvisioningContext ctx, PrismObject<ShadowType> currentResourceShadow, PrismObject<ShadowType> oldRepoShadow, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException, ConfigurationException, CommunicationException, ExpressionEvaluationException {
    RefinedObjectClassDefinition ocDef = ctx.computeCompositeObjectClassDefinition(currentResourceShadow);
    ObjectDelta<ShadowType> shadowDelta = oldRepoShadow.createModifyDelta();
    PrismContainer<Containerable> currentResourceAttributesContainer = currentResourceShadow.findContainer(ShadowType.F_ATTRIBUTES);
    PrismContainer<Containerable> oldRepoAttributesContainer = oldRepoShadow.findContainer(ShadowType.F_ATTRIBUTES);
    ShadowType oldRepoShadowType = oldRepoShadow.asObjectable();
    ShadowType currentResourceShadowType = currentResourceShadow.asObjectable();
    if (oldRepoShadowType.isExists() != currentResourceShadowType.isExists()) {
        // Resource object obviously exists when we have got here
        shadowDelta.addModificationReplaceProperty(ShadowType.F_EXISTS, currentResourceShadowType.isExists());
    }
    CachingStategyType cachingStrategy = ProvisioningUtil.getCachingStrategy(ctx);
    for (Item<?, ?> currentResourceItem : currentResourceAttributesContainer.getValue().getItems()) {
        if (currentResourceItem instanceof PrismProperty<?>) {
            PrismProperty<?> currentResourceAttrProperty = (PrismProperty<?>) currentResourceItem;
            RefinedAttributeDefinition<Object> attrDef = ocDef.findAttributeDefinition(currentResourceAttrProperty.getElementName());
            if (ProvisioningUtil.shouldStoreAtributeInShadow(ocDef, attrDef.getName(), cachingStrategy)) {
                MatchingRule matchingRule = matchingRuleRegistry.getMatchingRule(attrDef.getMatchingRuleQName(), attrDef.getTypeName());
                PrismProperty<Object> oldRepoAttributeProperty = oldRepoAttributesContainer.findProperty(currentResourceAttrProperty.getElementName());
                if (oldRepoAttributeProperty == null) {
                    PropertyDelta<?> attrAddDelta = currentResourceAttrProperty.createDelta();
                    for (PrismPropertyValue pval : currentResourceAttrProperty.getValues()) {
                        Object normalizedRealValue;
                        if (matchingRule == null) {
                            normalizedRealValue = pval.getValue();
                        } else {
                            normalizedRealValue = matchingRule.normalize(pval.getValue());
                        }
                        attrAddDelta.addValueToAdd(new PrismPropertyValue(normalizedRealValue));
                        LOGGER.trace("CURRENT ATTR:\n{}\nATTR DELTA:\n{}", currentResourceAttrProperty.debugDump(1), attrAddDelta.debugDump(1));
                    }
                    shadowDelta.addModification(attrAddDelta);
                } else {
                    if (attrDef.isSingleValue()) {
                        Object currentResourceRealValue = currentResourceAttrProperty.getRealValue();
                        Object currentResourceNormalizedRealValue;
                        if (matchingRule == null) {
                            currentResourceNormalizedRealValue = currentResourceRealValue;
                        } else {
                            currentResourceNormalizedRealValue = matchingRule.normalize(currentResourceRealValue);
                        }
                        if (!currentResourceNormalizedRealValue.equals(oldRepoAttributeProperty.getRealValue())) {
                            LOGGER.trace("CURRENT ATTR:\n{}\ncurrentResourceNormalizedRealValue: {}", currentResourceAttrProperty.debugDump(1), currentResourceNormalizedRealValue);
                            shadowDelta.addModificationReplaceProperty(currentResourceAttrProperty.getPath(), currentResourceNormalizedRealValue);
                        }
                    } else {
                        PrismProperty<Object> normalizedCurrentResourceAttrProperty = (PrismProperty<Object>) currentResourceAttrProperty.clone();
                        if (matchingRule != null) {
                            for (PrismPropertyValue pval : normalizedCurrentResourceAttrProperty.getValues()) {
                                Object normalizedRealValue = matchingRule.normalize(pval.getValue());
                                pval.setValue(normalizedRealValue);
                            }
                        }
                        PropertyDelta<Object> attrDiff = oldRepoAttributeProperty.diff(normalizedCurrentResourceAttrProperty);
                        LOGGER.trace("DIFF:\n{}\n-\n{}\n=:\n{}", oldRepoAttributeProperty == null ? null : oldRepoAttributeProperty.debugDump(1), normalizedCurrentResourceAttrProperty == null ? null : normalizedCurrentResourceAttrProperty.debugDump(1), attrDiff == null ? null : attrDiff.debugDump(1));
                        if (attrDiff != null && !attrDiff.isEmpty()) {
                            attrDiff.setParentPath(new ItemPath(ShadowType.F_ATTRIBUTES));
                            shadowDelta.addModification(attrDiff);
                        }
                    }
                }
            }
        }
    }
    for (Item<?, ?> oldRepoItem : oldRepoAttributesContainer.getValue().getItems()) {
        if (oldRepoItem instanceof PrismProperty<?>) {
            PrismProperty<?> oldRepoAttrProperty = (PrismProperty<?>) oldRepoItem;
            RefinedAttributeDefinition<Object> attrDef = ocDef.findAttributeDefinition(oldRepoAttrProperty.getElementName());
            PrismProperty<Object> currentAttribute = currentResourceAttributesContainer.findProperty(oldRepoAttrProperty.getElementName());
            if (attrDef == null || !ProvisioningUtil.shouldStoreAtributeInShadow(ocDef, attrDef.getName(), cachingStrategy) || currentAttribute == null) {
                // No definition for this property it should not be there or no current value: remove it from the shadow
                PropertyDelta<?> oldRepoAttrPropDelta = oldRepoAttrProperty.createDelta();
                oldRepoAttrPropDelta.addValuesToDelete((Collection) PrismPropertyValue.cloneCollection(oldRepoAttrProperty.getValues()));
                shadowDelta.addModification(oldRepoAttrPropDelta);
            }
        }
    }
    PolyString currentShadowName = ShadowUtil.determineShadowName(currentResourceShadow);
    PolyString oldRepoShadowName = oldRepoShadow.getName();
    if (!currentShadowName.equalsOriginalValue(oldRepoShadowName)) {
        PropertyDelta<?> shadowNameDelta = PropertyDelta.createModificationReplaceProperty(ShadowType.F_NAME, oldRepoShadow.getDefinition(), currentShadowName);
        shadowDelta.addModification(shadowNameDelta);
    }
    PropertyDelta<QName> auxOcDelta = (PropertyDelta) PrismProperty.diff(oldRepoShadow.findProperty(ShadowType.F_AUXILIARY_OBJECT_CLASS), currentResourceShadow.findProperty(ShadowType.F_AUXILIARY_OBJECT_CLASS));
    if (auxOcDelta != null) {
        shadowDelta.addModification(auxOcDelta);
    }
    if (cachingStrategy == CachingStategyType.NONE) {
        if (oldRepoShadowType.getCachingMetadata() != null) {
            shadowDelta.addModificationReplaceProperty(ShadowType.F_CACHING_METADATA);
        }
    } else if (cachingStrategy == CachingStategyType.PASSIVE) {
        compareUpdateProperty(shadowDelta, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, currentResourceShadow, oldRepoShadow);
        compareUpdateProperty(shadowDelta, SchemaConstants.PATH_ACTIVATION_VALID_FROM, currentResourceShadow, oldRepoShadow);
        compareUpdateProperty(shadowDelta, SchemaConstants.PATH_ACTIVATION_VALID_TO, currentResourceShadow, oldRepoShadow);
        compareUpdateProperty(shadowDelta, SchemaConstants.PATH_ACTIVATION_LOCKOUT_STATUS, currentResourceShadow, oldRepoShadow);
        CachingMetadataType cachingMetadata = new CachingMetadataType();
        cachingMetadata.setRetrievalTimestamp(clock.currentTimeXMLGregorianCalendar());
        shadowDelta.addModificationReplaceProperty(ShadowType.F_CACHING_METADATA, cachingMetadata);
    } else {
        throw new ConfigurationException("Unknown caching strategy " + cachingStrategy);
    }
    if (!shadowDelta.isEmpty()) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Updating repo shadow {} with delta:\n{}", oldRepoShadow, shadowDelta.debugDump(1));
        }
        ConstraintsChecker.onShadowModifyOperation(shadowDelta.getModifications());
        try {
            repositoryService.modifyObject(ShadowType.class, oldRepoShadow.getOid(), shadowDelta.getModifications(), parentResult);
        } catch (ObjectAlreadyExistsException e) {
            // This should not happen for shadows
            throw new SystemException(e.getMessage(), e);
        }
        PrismObject<ShadowType> newRepoShadow = oldRepoShadow.clone();
        shadowDelta.applyTo(newRepoShadow);
        return newRepoShadow;
    } else {
        LOGGER.trace("No need to update repo shadow {} (empty delta)", oldRepoShadow);
        return oldRepoShadow;
    }
}
Also used : RefinedObjectClassDefinition(com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition) SystemException(com.evolveum.midpoint.util.exception.SystemException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) Containerable(com.evolveum.midpoint.prism.Containerable) PropertyDelta(com.evolveum.midpoint.prism.delta.PropertyDelta) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue) QName(javax.xml.namespace.QName) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) PrismObject(com.evolveum.midpoint.prism.PrismObject) MatchingRule(com.evolveum.midpoint.prism.match.MatchingRule) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Aggregations

ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)93 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)57 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)50 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)45 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)35 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)33 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)32 SystemException (com.evolveum.midpoint.util.exception.SystemException)31 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)25 PrismObject (com.evolveum.midpoint.prism.PrismObject)21 PolicyViolationException (com.evolveum.midpoint.util.exception.PolicyViolationException)18 Task (com.evolveum.midpoint.task.api.Task)17 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)14 GenericFrameworkException (com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException)14 ShadowType (com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType)13 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)12 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)12 ArrayList (java.util.ArrayList)11 ItemDelta (com.evolveum.midpoint.prism.delta.ItemDelta)10 PropertyDelta (com.evolveum.midpoint.prism.delta.PropertyDelta)9