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.");
}
}
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);
}
}
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;
}
}
}
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);
}
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;
}
Aggregations