Search in sources :

Example 16 with ObjectAlreadyExistsException

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

the class ObjectUpdater method modifyObjectAttempt.

public <T extends ObjectType> void modifyObjectAttempt(Class<T> type, String oid, Collection<? extends ItemDelta> modifications, RepoModifyOptions modifyOptions, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, SerializationRelatedException {
    // clone - because some certification and lookup table related methods manipulate this collection and even their constituent deltas
    // TODO clone elements only if necessary
    modifications = CloneUtil.cloneCollectionMembers(modifications);
    //modifications = new ArrayList<>(modifications);
    LOGGER.debug("Modifying object '{}' with oid '{}'.", new Object[] { type.getSimpleName(), oid });
    LOGGER_PERFORMANCE.debug("> modify object {}, oid={}, modifications={}", type.getSimpleName(), oid, modifications);
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Modifications:\n{}", DebugUtil.debugDump(modifications));
    }
    Session session = null;
    OrgClosureManager.Context closureContext = null;
    try {
        session = baseHelper.beginTransaction();
        closureContext = closureManager.onBeginTransactionModify(session, type, oid, modifications);
        Collection<? extends ItemDelta> lookupTableModifications = lookupTableHelper.filterLookupTableModifications(type, modifications);
        Collection<? extends ItemDelta> campaignCaseModifications = caseHelper.filterCampaignCaseModifications(type, modifications);
        if (!modifications.isEmpty() || RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) {
            // JpegPhoto (RFocusPhoto) is a special kind of entity. First of all, it is lazily loaded, because photos are really big.
            // Each RFocusPhoto naturally belongs to one RFocus, so it would be appropriate to set orphanRemoval=true for focus-photo
            // association. However, this leads to a strange problem when merging in-memory RFocus object with the database state:
            // If in-memory RFocus object has no photo associated (because of lazy loading), then the associated RFocusPhoto is deleted.
            //
            // To prevent this behavior, we've set orphanRemoval to false. Fortunately, the remove operation on RFocus
            // seems to be still cascaded to RFocusPhoto. What we have to implement ourselves, however, is removal of RFocusPhoto
            // _without_ removing of RFocus. In order to know whether the photo has to be removed, we have to retrieve
            // its value, apply the delta (e.g. if the delta is a DELETE VALUE X, we have to know whether X matches current
            // value of the photo), and if the resulting value is empty, we have to manually delete the RFocusPhoto instance.
            //
            // So the first step is to retrieve the current value of photo - we obviously do this only if the modifications
            // deal with the jpegPhoto property.
            Collection<SelectorOptions<GetOperationOptions>> options;
            boolean containsFocusPhotoModification = FocusType.class.isAssignableFrom(type) && containsPhotoModification(modifications);
            if (containsFocusPhotoModification) {
                options = Collections.singletonList(SelectorOptions.create(FocusType.F_JPEG_PHOTO, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)));
            } else {
                options = null;
            }
            // get object
            PrismObject<T> prismObject = objectRetriever.getObjectInternal(session, type, oid, options, true, result);
            // apply diff
            LOGGER.trace("OBJECT before:\n{}", prismObject.debugDumpLazily());
            PrismObject<T> originalObject = null;
            if (closureManager.isEnabled()) {
                originalObject = prismObject.clone();
            }
            ItemDelta.applyTo(modifications, prismObject);
            LOGGER.trace("OBJECT after:\n{}", prismObject.debugDumpLazily());
            // Continuing the photo treatment: should we remove the (now obsolete) focus photo?
            // We have to test prismObject at this place, because updateFullObject (below) removes photo property from the prismObject.
            boolean shouldPhotoBeRemoved = containsFocusPhotoModification && ((FocusType) prismObject.asObjectable()).getJpegPhoto() == null;
            // merge and update object
            LOGGER.trace("Translating JAXB to data type.");
            ObjectTypeUtil.normalizeAllRelations(prismObject);
            RObject rObject = createDataObjectFromJAXB(prismObject, PrismIdentifierGenerator.Operation.MODIFY);
            rObject.setVersion(rObject.getVersion() + 1);
            updateFullObject(rObject, prismObject);
            LOGGER.trace("Starting merge.");
            session.merge(rObject);
            if (closureManager.isEnabled()) {
                closureManager.updateOrgClosure(originalObject, modifications, session, oid, type, OrgClosureManager.Operation.MODIFY, closureContext);
            }
            // we have to remove the photo manually.
            if (shouldPhotoBeRemoved) {
                Query query = session.createQuery("delete RFocusPhoto where ownerOid = :oid");
                query.setParameter("oid", prismObject.getOid());
                query.executeUpdate();
                LOGGER.trace("Focus photo for {} was deleted", prismObject.getOid());
            }
        }
        if (LookupTableType.class.isAssignableFrom(type)) {
            lookupTableHelper.updateLookupTableData(session, oid, lookupTableModifications);
        }
        if (AccessCertificationCampaignType.class.isAssignableFrom(type)) {
            caseHelper.updateCampaignCases(session, oid, campaignCaseModifications, modifyOptions);
        }
        LOGGER.trace("Before commit...");
        session.getTransaction().commit();
        LOGGER.trace("Committed!");
    } catch (ObjectNotFoundException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (ConstraintViolationException ex) {
        handleConstraintViolationException(session, ex, result);
        baseHelper.rollbackTransaction(session, ex, result, true);
        LOGGER.debug("Constraint violation occurred (will be rethrown as ObjectAlreadyExistsException).", ex);
        //todo improve (we support only 5 DB, so we should probably do some hacking in here)
        throw new ObjectAlreadyExistsException(ex);
    } catch (SchemaException ex) {
        baseHelper.rollbackTransaction(session, ex, result, true);
        throw ex;
    } catch (DtoTranslationException | RuntimeException ex) {
        baseHelper.handleGeneralException(ex, session, result);
    } finally {
        cleanupClosureAndSessionAndResult(closureContext, session, result);
        LOGGER.trace("Session cleaned up.");
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) SQLQuery(org.hibernate.SQLQuery) Query(org.hibernate.Query) DtoTranslationException(com.evolveum.midpoint.repo.sql.util.DtoTranslationException) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) RObject(com.evolveum.midpoint.repo.sql.data.common.RObject) FocusType(com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ConstraintViolationException(org.hibernate.exception.ConstraintViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) Session(org.hibernate.Session)

Example 17 with ObjectAlreadyExistsException

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

the class AddGetObjectTest method addSameName.

@Test
public void addSameName() throws Exception {
    final File user = new File(FOLDER_BASIC, "objects-user.xml");
    addGetCompare(user);
    try {
        // WHEN
        addGetCompare(user);
        assert false : "Unexpected success";
    } catch (ObjectAlreadyExistsException e) {
        TestUtil.assertExceptionSanity(e);
    }
}
Also used : File(java.io.File) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException) Test(org.testng.annotations.Test)

Example 18 with ObjectAlreadyExistsException

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

the class AbstractIntegrationTest method repoAddObject.

protected <T extends ObjectType> void repoAddObject(PrismObject<T> object, String contextDesc, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, EncryptionException {
    if (object.canRepresent(TaskType.class)) {
        Assert.assertNotNull(taskManager, "Task manager is not initialized");
        try {
            taskManager.addTask((PrismObject<TaskType>) object, result);
        } catch (ObjectAlreadyExistsException ex) {
            result.recordFatalError(ex.getMessage(), ex);
            throw ex;
        } catch (SchemaException ex) {
            result.recordFatalError(ex.getMessage(), ex);
            throw ex;
        }
    } else {
        Assert.assertNotNull(repositoryService, "Repository service is not initialized");
        try {
            CryptoUtil.encryptValues(protector, object);
            String oid = repositoryService.addObject(object, null, result);
            object.setOid(oid);
        } catch (ObjectAlreadyExistsException ex) {
            result.recordFatalError(ex.getMessage() + " while adding " + object + (contextDesc == null ? "" : " " + contextDesc), ex);
            throw ex;
        } catch (SchemaException ex) {
            result.recordFatalError(ex.getMessage() + " while adding " + object + (contextDesc == null ? "" : " " + contextDesc), ex);
            throw ex;
        } catch (EncryptionException ex) {
            result.recordFatalError(ex.getMessage() + " while adding " + object + (contextDesc == null ? "" : " " + contextDesc), ex);
            throw ex;
        }
    }
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)

Example 19 with ObjectAlreadyExistsException

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

the class AbstractLdapHierarchyTest method reconcileAllOrgs.

protected void reconcileAllOrgs() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    final Task task = createTask("reconcileAllOrgs");
    OperationResult result = task.getResult();
    ResultHandler<OrgType> handler = new ResultHandler<OrgType>() {

        @Override
        public boolean handle(PrismObject<OrgType> object, OperationResult parentResult) {
            try {
                display("reconciling " + object);
                reconcileOrg(object.getOid(), task, parentResult);
            } catch (SchemaException | PolicyViolationException | ExpressionEvaluationException | ObjectNotFoundException | ObjectAlreadyExistsException | CommunicationException | ConfigurationException | SecurityViolationException e) {
                throw new SystemException(e.getMessage(), e);
            }
            return true;
        }
    };
    display("Reconciling all orgs");
    modelService.searchObjectsIterative(OrgType.class, null, handler, null, task, result);
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) Task(com.evolveum.midpoint.task.api.Task) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResultHandler(com.evolveum.midpoint.schema.ResultHandler) PrismObject(com.evolveum.midpoint.prism.PrismObject) SystemException(com.evolveum.midpoint.util.exception.SystemException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) OrgType(com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) PolicyViolationException(com.evolveum.midpoint.util.exception.PolicyViolationException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)

Example 20 with ObjectAlreadyExistsException

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

the class ProvisioningServiceImpl method synchronize.

@SuppressWarnings("rawtypes")
@Override
public int synchronize(ResourceShadowDiscriminator shadowCoordinates, Task task, OperationResult parentResult) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
    Validate.notNull(shadowCoordinates, "Coordinates oid must not be null.");
    String resourceOid = shadowCoordinates.getResourceOid();
    Validate.notNull(resourceOid, "Resource oid must not be null.");
    Validate.notNull(task, "Task must not be null.");
    Validate.notNull(parentResult, "Operation result must not be null.");
    OperationResult result = parentResult.createSubresult(ProvisioningService.class.getName() + ".synchronize");
    result.addParam(OperationResult.PARAM_OID, resourceOid);
    result.addParam(OperationResult.PARAM_TASK, task.toString());
    int processedChanges = 0;
    try {
        // Resolve resource
        PrismObject<ResourceType> resource = getObject(ResourceType.class, resourceOid, null, task, result);
        ResourceType resourceType = resource.asObjectable();
        LOGGER.trace("**PROVISIONING: Start synchronization of resource {} ", resourceType);
        // getting token form task
        PrismProperty tokenProperty = getTokenProperty(shadowCoordinates, task, result);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("**PROVISIONING: Got token property: {} from the task extension.", SchemaDebugUtil.prettyPrint(tokenProperty));
        }
        processedChanges = getShadowCache(Mode.STANDARD).synchronize(shadowCoordinates, tokenProperty, task, result);
        LOGGER.debug("Synchronization of {} done, token {}, {} changes", resource, tokenProperty, processedChanges);
    } catch (ObjectNotFoundException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: object not found: " + e.getMessage(), e);
        throw e;
    } catch (CommunicationException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: communication problem: " + e.getMessage(), e);
        throw e;
    } catch (ObjectAlreadyExistsException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: object already exists problem: " + e.getMessage(), e);
        throw new SystemException(e);
    } catch (GenericFrameworkException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: generic connector framework error: " + e.getMessage(), e);
        throw new GenericConnectorException(e.getMessage(), e);
    } catch (SchemaException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: schema problem: " + e.getMessage(), e);
        throw e;
    } catch (SecurityViolationException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: security violation: " + e.getMessage(), e);
        throw e;
    } catch (ConfigurationException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: configuration problem: " + e.getMessage(), e);
        throw e;
    } catch (RuntimeException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: unexpected problem: " + e.getMessage(), e);
        throw e;
    } catch (ExpressionEvaluationException e) {
        ProvisioningUtil.recordFatalError(LOGGER, result, "Synchronization error: expression error: " + e.getMessage(), e);
        throw e;
    }
    result.recordSuccess();
    result.cleanupResult();
    return processedChanges;
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) GenericFrameworkException(com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) ResourceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType) LabeledString(com.evolveum.midpoint.schema.LabeledString) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) SystemException(com.evolveum.midpoint.util.exception.SystemException) GenericConnectorException(com.evolveum.midpoint.provisioning.api.GenericConnectorException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) ObjectAlreadyExistsException(com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)

Aggregations

ObjectAlreadyExistsException (com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException)142 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)84 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)76 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)69 SystemException (com.evolveum.midpoint.util.exception.SystemException)50 PrismObject (com.evolveum.midpoint.prism.PrismObject)39 Test (org.testng.annotations.Test)36 CommunicationException (com.evolveum.midpoint.util.exception.CommunicationException)31 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)29 ConfigurationException (com.evolveum.midpoint.util.exception.ConfigurationException)28 ItemDelta (com.evolveum.midpoint.prism.delta.ItemDelta)27 SqaleRepoBaseTest (com.evolveum.midpoint.repo.sqale.SqaleRepoBaseTest)24 SecurityViolationException (com.evolveum.midpoint.util.exception.SecurityViolationException)24 RepositoryService (com.evolveum.midpoint.repo.api.RepositoryService)22 PolyStringType (com.evolveum.prism.xml.ns._public.types_3.PolyStringType)22 QName (javax.xml.namespace.QName)22 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)20 ObjectDelta (com.evolveum.midpoint.prism.delta.ObjectDelta)17 SchemaConstants (com.evolveum.midpoint.schema.constants.SchemaConstants)17 com.evolveum.midpoint.xml.ns._public.common.common_3 (com.evolveum.midpoint.xml.ns._public.common.common_3)17