use of org.apache.syncope.core.persistence.api.entity.resource.OrgUnit in project syncope by apache.
the class PropagationManagerImpl method createTasks.
@Override
public List<PropagationTaskTO> createTasks(final Realm realm, final PropagationByResource propByRes, final Collection<String> noPropResourceKeys) {
if (noPropResourceKeys != null) {
propByRes.removeAll(noPropResourceKeys);
}
LOG.debug("Provisioning {}:\n{}", realm, propByRes);
// Avoid duplicates - see javadoc
propByRes.purge();
LOG.debug("After purge {}:\n{}", realm, propByRes);
List<PropagationTaskTO> tasks = new ArrayList<>();
propByRes.asMap().forEach((resourceKey, operation) -> {
ExternalResource resource = resourceDAO.find(resourceKey);
OrgUnit orgUnit = resource == null ? null : resource.getOrgUnit();
if (resource == null) {
LOG.error("Invalid resource name specified: {}, ignoring...", resourceKey);
} else if (orgUnit == null) {
LOG.error("No orgUnit specified on resource {}, ignoring...", resource);
} else if (StringUtils.isBlank(orgUnit.getConnObjectLink())) {
LOG.warn("Requesting propagation for {} but no ConnObjectLink provided for {}", realm.getFullPath(), resource);
} else {
PropagationTaskTO task = new PropagationTaskTO();
task.setResource(resource.getKey());
task.setObjectClassName(orgUnit.getObjectClass().getObjectClassValue());
task.setEntityKey(realm.getKey());
task.setOperation(operation);
task.setOldConnObjectKey(propByRes.getOldConnObjectKey(resource.getKey()));
Pair<String, Set<Attribute>> preparedAttrs = mappingManager.prepareAttrs(realm, orgUnit);
task.setConnObjectKey(preparedAttrs.getKey());
task.setAttributes(POJOHelper.serialize(preparedAttrs.getValue()));
tasks.add(task);
LOG.debug("PropagationTask created: {}", task);
}
});
return tasks;
}
use of org.apache.syncope.core.persistence.api.entity.resource.OrgUnit in project syncope by apache.
the class DefaultRealmPushResultHandler method doHandle.
private void doHandle(final Realm realm) throws JobExecutionException {
ProvisioningReport result = new ProvisioningReport();
profile.getResults().add(result);
result.setKey(realm.getKey());
result.setAnyType(REALM_TYPE);
result.setName(realm.getFullPath());
LOG.debug("Propagating Realm with key {} towards {}", realm.getKey(), profile.getTask().getResource());
Object output = null;
Result resultStatus = null;
// Try to read remote object BEFORE any actual operation
OrgUnit orgUnit = profile.getTask().getResource().getOrgUnit();
Optional<? extends OrgUnitItem> connObjectKey = orgUnit.getConnObjectKeyItem();
Optional<String> connObjecKeyValue = mappingManager.getConnObjectKeyValue(realm, orgUnit);
ConnectorObject beforeObj = null;
if (connObjectKey.isPresent() && connObjecKeyValue.isPresent()) {
beforeObj = getRemoteObject(orgUnit.getObjectClass(), connObjectKey.get().getExtAttrName(), connObjecKeyValue.get(), orgUnit.getItems().iterator());
} else {
LOG.debug("OrgUnitItem {} or its value {} are null", connObjectKey, connObjecKeyValue);
}
if (profile.isDryRun()) {
if (beforeObj == null) {
result.setOperation(toResourceOperation(profile.getTask().getUnmatchingRule()));
} else {
result.setOperation(toResourceOperation(profile.getTask().getMatchingRule()));
}
result.setStatus(ProvisioningReport.Status.SUCCESS);
} else {
String operation = beforeObj == null ? UnmatchingRule.toEventName(profile.getTask().getUnmatchingRule()) : MatchingRule.toEventName(profile.getTask().getMatchingRule());
boolean notificationsAvailable = notificationManager.notificationsAvailable(AuditElements.EventCategoryType.PUSH, REALM_TYPE.toLowerCase(), profile.getTask().getResource().getKey(), operation);
boolean auditRequested = auditManager.auditRequested(AuditElements.EventCategoryType.PUSH, REALM_TYPE.toLowerCase(), profile.getTask().getResource().getKey(), operation);
try {
if (beforeObj == null) {
result.setOperation(toResourceOperation(profile.getTask().getUnmatchingRule()));
switch(profile.getTask().getUnmatchingRule()) {
case ASSIGN:
for (PushActions action : profile.getActions()) {
action.beforeAssign(profile, realm);
}
if (!profile.getTask().isPerformCreate()) {
LOG.debug("PushTask not configured for create");
result.setStatus(ProvisioningReport.Status.IGNORE);
} else {
assign(realm, result);
}
break;
case PROVISION:
for (PushActions action : profile.getActions()) {
action.beforeProvision(profile, realm);
}
if (!profile.getTask().isPerformCreate()) {
LOG.debug("PushTask not configured for create");
result.setStatus(ProvisioningReport.Status.IGNORE);
} else {
provision(realm, result);
}
break;
case UNLINK:
for (PushActions action : profile.getActions()) {
action.beforeUnlink(profile, realm);
}
if (!profile.getTask().isPerformUpdate()) {
LOG.debug("PushTask not configured for update");
result.setStatus(ProvisioningReport.Status.IGNORE);
} else {
link(realm, true, result);
}
break;
case IGNORE:
LOG.debug("Ignored any: {}", realm);
result.setStatus(ProvisioningReport.Status.IGNORE);
break;
default:
}
} else {
result.setOperation(toResourceOperation(profile.getTask().getMatchingRule()));
switch(profile.getTask().getMatchingRule()) {
case UPDATE:
for (PushActions action : profile.getActions()) {
action.beforeUpdate(profile, realm);
}
if (!profile.getTask().isPerformUpdate()) {
LOG.debug("PushTask not configured for update");
result.setStatus(ProvisioningReport.Status.IGNORE);
} else {
update(binder.getRealmTO(realm, true), result);
}
break;
case DEPROVISION:
for (PushActions action : profile.getActions()) {
action.beforeDeprovision(profile, realm);
}
if (!profile.getTask().isPerformDelete()) {
LOG.debug("PushTask not configured for delete");
result.setStatus(ProvisioningReport.Status.IGNORE);
} else {
deprovision(realm, result);
}
break;
case UNASSIGN:
for (PushActions action : profile.getActions()) {
action.beforeUnassign(profile, realm);
}
if (!profile.getTask().isPerformDelete()) {
LOG.debug("PushTask not configured for delete");
result.setStatus(ProvisioningReport.Status.IGNORE);
} else {
unassign(realm, result);
}
break;
case LINK:
for (PushActions action : profile.getActions()) {
action.beforeLink(profile, realm);
}
if (!profile.getTask().isPerformUpdate()) {
LOG.debug("PushTask not configured for update");
result.setStatus(ProvisioningReport.Status.IGNORE);
} else {
link(realm, false, result);
}
break;
case UNLINK:
for (PushActions action : profile.getActions()) {
action.beforeUnlink(profile, realm);
}
if (!profile.getTask().isPerformUpdate()) {
LOG.debug("PushTask not configured for update");
result.setStatus(ProvisioningReport.Status.IGNORE);
} else {
link(realm, true, result);
}
break;
case IGNORE:
LOG.debug("Ignored any: {}", realm);
result.setStatus(ProvisioningReport.Status.IGNORE);
break;
default:
}
}
for (PushActions action : profile.getActions()) {
action.after(profile, realm, result);
}
if (result.getStatus() == null) {
result.setStatus(ProvisioningReport.Status.SUCCESS);
}
resultStatus = AuditElements.Result.SUCCESS;
if (connObjectKey.isPresent() && connObjecKeyValue.isPresent()) {
output = getRemoteObject(orgUnit.getObjectClass(), connObjectKey.get().getExtAttrName(), connObjecKeyValue.get(), orgUnit.getItems().iterator());
}
} catch (IgnoreProvisionException e) {
throw e;
} catch (Exception e) {
result.setStatus(ProvisioningReport.Status.FAILURE);
result.setMessage(ExceptionUtils.getRootCauseMessage(e));
resultStatus = AuditElements.Result.FAILURE;
output = e;
LOG.warn("Error pushing {} towards {}", realm, profile.getTask().getResource(), e);
for (PushActions action : profile.getActions()) {
action.onError(profile, realm, result, e);
}
throw new JobExecutionException(e);
} finally {
if (notificationsAvailable || auditRequested) {
Map<String, Object> jobMap = new HashMap<>();
jobMap.put(AfterHandlingEvent.JOBMAP_KEY, new AfterHandlingEvent(AuditElements.EventCategoryType.PUSH, REALM_TYPE.toLowerCase(), profile.getTask().getResource().getKey(), operation, resultStatus, beforeObj, output, realm));
AfterHandlingJob.schedule(scheduler, jobMap);
}
}
}
}
use of org.apache.syncope.core.persistence.api.entity.resource.OrgUnit in project syncope by apache.
the class PullJobDelegate method doExecuteProvisioning.
@Override
protected String doExecuteProvisioning(final PullTask pullTask, final Connector connector, final boolean dryRun) throws JobExecutionException {
LOG.debug("Executing pull on {}", pullTask.getResource());
List<PullActions> actions = new ArrayList<>();
pullTask.getActions().forEach(impl -> {
try {
actions.add(ImplementationManager.build(impl));
} catch (Exception e) {
LOG.warn("While building {}", impl, e);
}
});
profile = new ProvisioningProfile<>(connector, pullTask);
profile.getActions().addAll(actions);
profile.setDryRun(dryRun);
profile.setResAct(pullTask.getResource().getPullPolicy() == null ? ConflictResolutionAction.IGNORE : pullTask.getResource().getPullPolicy().getConflictResolutionAction());
latestSyncTokens.clear();
if (!profile.isDryRun()) {
for (PullActions action : actions) {
action.beforeAll(profile);
}
}
status.set("Initialization completed");
// First realms...
if (pullTask.getResource().getOrgUnit() != null) {
status.set("Pulling " + pullTask.getResource().getOrgUnit().getObjectClass().getObjectClassValue());
OrgUnit orgUnit = pullTask.getResource().getOrgUnit();
OperationOptions options = MappingUtils.buildOperationOptions(MappingUtils.getPullItems(orgUnit.getItems()).iterator());
rhandler = buildRealmHandler();
try {
switch(pullTask.getPullMode()) {
case INCREMENTAL:
if (!dryRun) {
latestSyncTokens.put(orgUnit.getObjectClass(), orgUnit.getSyncToken());
}
connector.sync(orgUnit.getObjectClass(), orgUnit.getSyncToken(), rhandler, options);
if (!dryRun) {
orgUnit.setSyncToken(latestSyncTokens.get(orgUnit.getObjectClass()));
resourceDAO.save(orgUnit.getResource());
}
break;
case FILTERED_RECONCILIATION:
ReconFilterBuilder filterBuilder = ImplementationManager.build(pullTask.getReconFilterBuilder());
connector.filteredReconciliation(orgUnit.getObjectClass(), filterBuilder, rhandler, options);
break;
case FULL_RECONCILIATION:
default:
connector.fullReconciliation(orgUnit.getObjectClass(), rhandler, options);
break;
}
} catch (Throwable t) {
throw new JobExecutionException("While pulling from connector", t);
}
}
// ...then provisions for any types
ahandler = buildAnyObjectHandler();
uhandler = buildUserHandler();
ghandler = buildGroupHandler();
for (Provision provision : pullTask.getResource().getProvisions()) {
if (provision.getMapping() != null) {
status.set("Pulling " + provision.getObjectClass().getObjectClassValue());
SyncopePullResultHandler handler;
switch(provision.getAnyType().getKind()) {
case USER:
handler = uhandler;
break;
case GROUP:
handler = ghandler;
break;
case ANY_OBJECT:
default:
handler = ahandler;
}
try {
Set<MappingItem> linkingMappingItems = virSchemaDAO.findByProvision(provision).stream().map(schema -> schema.asLinkingMappingItem()).collect(Collectors.toSet());
Iterator<MappingItem> mapItems = new IteratorChain<>(provision.getMapping().getItems().iterator(), linkingMappingItems.iterator());
OperationOptions options = MappingUtils.buildOperationOptions(mapItems);
switch(pullTask.getPullMode()) {
case INCREMENTAL:
if (!dryRun) {
latestSyncTokens.put(provision.getObjectClass(), provision.getSyncToken());
}
connector.sync(provision.getObjectClass(), provision.getSyncToken(), handler, options);
if (!dryRun) {
provision.setSyncToken(latestSyncTokens.get(provision.getObjectClass()));
resourceDAO.save(provision.getResource());
}
break;
case FILTERED_RECONCILIATION:
ReconFilterBuilder filterBuilder = ImplementationManager.build(pullTask.getReconFilterBuilder());
connector.filteredReconciliation(provision.getObjectClass(), filterBuilder, handler, options);
break;
case FULL_RECONCILIATION:
default:
connector.fullReconciliation(provision.getObjectClass(), handler, options);
break;
}
} catch (Throwable t) {
throw new JobExecutionException("While pulling from connector", t);
}
}
}
try {
setGroupOwners(ghandler);
} catch (Exception e) {
LOG.error("While setting group owners", e);
}
if (!profile.isDryRun()) {
for (PullActions action : actions) {
action.afterAll(profile);
}
}
status.set("Pull done");
String result = createReport(profile.getResults(), pullTask.getResource(), dryRun);
LOG.debug("Pull result: {}", result);
return result;
}
use of org.apache.syncope.core.persistence.api.entity.resource.OrgUnit in project syncope by apache.
the class AbstractPropagationTaskExecutor method execute.
protected TaskExec execute(final PropagationTaskTO taskTO, final PropagationReporter reporter) {
PropagationTask task = entityFactory.newEntity(PropagationTask.class);
task.setResource(resourceDAO.find(taskTO.getResource()));
task.setObjectClassName(taskTO.getObjectClassName());
task.setAnyTypeKind(taskTO.getAnyTypeKind());
task.setAnyType(taskTO.getAnyType());
task.setEntityKey(taskTO.getEntityKey());
task.setOperation(taskTO.getOperation());
task.setConnObjectKey(taskTO.getConnObjectKey());
task.setOldConnObjectKey(taskTO.getOldConnObjectKey());
Set<Attribute> attributes = new HashSet<>();
if (StringUtils.isNotBlank(taskTO.getAttributes())) {
attributes.addAll(Arrays.asList(POJOHelper.deserialize(taskTO.getAttributes(), Attribute[].class)));
}
task.setAttributes(attributes);
List<PropagationActions> actions = getPropagationActions(task.getResource());
String resource = task.getResource().getKey();
Date start = new Date();
TaskExec execution = entityFactory.newEntity(TaskExec.class);
execution.setStatus(PropagationTaskExecStatus.CREATED.name());
String taskExecutionMessage = null;
String failureReason = null;
// Flag to state whether any propagation has been attempted
AtomicReference<Boolean> propagationAttempted = new AtomicReference<>(false);
ConnectorObject beforeObj = null;
ConnectorObject afterObj = null;
Provision provision = null;
OrgUnit orgUnit = null;
Uid uid = null;
Connector connector = null;
Result result;
try {
provision = task.getResource().getProvision(new ObjectClass(task.getObjectClassName())).orElse(null);
orgUnit = task.getResource().getOrgUnit();
connector = connFactory.getConnector(task.getResource());
// Try to read remote object BEFORE any actual operation
beforeObj = provision == null && orgUnit == null ? null : orgUnit == null ? getRemoteObject(task, connector, provision, false) : getRemoteObject(task, connector, orgUnit, false);
for (PropagationActions action : actions) {
action.before(task, beforeObj);
}
switch(task.getOperation()) {
case CREATE:
case UPDATE:
uid = createOrUpdate(task, beforeObj, connector, propagationAttempted);
break;
case DELETE:
uid = delete(task, beforeObj, connector, propagationAttempted);
break;
default:
}
execution.setStatus(propagationAttempted.get() ? PropagationTaskExecStatus.SUCCESS.name() : PropagationTaskExecStatus.NOT_ATTEMPTED.name());
LOG.debug("Successfully propagated to {}", task.getResource());
result = Result.SUCCESS;
} catch (Exception e) {
result = Result.FAILURE;
LOG.error("Exception during provision on resource " + resource, e);
if (e instanceof ConnectorException && e.getCause() != null) {
taskExecutionMessage = e.getCause().getMessage();
if (e.getCause().getMessage() == null) {
failureReason = e.getMessage();
} else {
failureReason = e.getMessage() + "\n\n Cause: " + e.getCause().getMessage().split("\n")[0];
}
} else {
taskExecutionMessage = ExceptionUtils2.getFullStackTrace(e);
if (e.getCause() == null) {
failureReason = e.getMessage();
} else {
failureReason = e.getMessage() + "\n\n Cause: " + e.getCause().getMessage().split("\n")[0];
}
}
try {
execution.setStatus(PropagationTaskExecStatus.FAILURE.name());
} catch (Exception wft) {
LOG.error("While executing KO action on {}", execution, wft);
}
propagationAttempted.set(true);
actions.forEach(action -> {
action.onError(task, execution, e);
});
} finally {
// Try to read remote object AFTER any actual operation
if (connector != null) {
if (uid != null) {
task.setConnObjectKey(uid.getUidValue());
}
try {
afterObj = provision == null && orgUnit == null ? null : orgUnit == null ? getRemoteObject(task, connector, provision, true) : getRemoteObject(task, connector, orgUnit, true);
} catch (Exception ignore) {
// ignore exception
LOG.error("Error retrieving after object", ignore);
}
}
if (task.getOperation() != ResourceOperation.DELETE && afterObj == null && uid != null) {
afterObj = new ConnectorObjectBuilder().setObjectClass(new ObjectClass(task.getObjectClassName())).setUid(uid).setName(AttributeUtil.getNameFromAttributes(task.getAttributes())).build();
}
execution.setStart(start);
execution.setMessage(taskExecutionMessage);
execution.setEnd(new Date());
LOG.debug("Execution finished: {}", execution);
if (hasToBeregistered(task, execution)) {
LOG.debug("Execution to be stored: {}", execution);
execution.setTask(task);
task.add(execution);
taskDAO.save(task);
// needed to generate a value for the execution key
taskDAO.flush();
}
if (reporter != null) {
reporter.onSuccessOrNonPriorityResourceFailures(taskTO, PropagationTaskExecStatus.valueOf(execution.getStatus()), failureReason, beforeObj, afterObj);
}
}
for (PropagationActions action : actions) {
action.after(task, execution, afterObj);
}
// SYNCOPE-1136
String anyTypeKind = task.getAnyTypeKind() == null ? "realm" : task.getAnyTypeKind().name().toLowerCase();
String operation = task.getOperation().name().toLowerCase();
boolean notificationsAvailable = notificationManager.notificationsAvailable(AuditElements.EventCategoryType.PROPAGATION, anyTypeKind, resource, operation);
boolean auditRequested = auditManager.auditRequested(AuditElements.EventCategoryType.PROPAGATION, anyTypeKind, resource, operation);
if (notificationsAvailable || auditRequested) {
ExecTO execTO = taskDataBinder.getExecTO(execution);
notificationManager.createTasks(AuditElements.EventCategoryType.PROPAGATION, anyTypeKind, resource, operation, result, beforeObj, new Object[] { execTO, afterObj }, taskTO);
auditManager.audit(AuditElements.EventCategoryType.PROPAGATION, anyTypeKind, resource, operation, result, beforeObj, new Object[] { execTO, afterObj }, taskTO);
}
return execution;
}
use of org.apache.syncope.core.persistence.api.entity.resource.OrgUnit in project syncope by apache.
the class ResourceDataBinderImpl method getResourceTO.
@Override
public ResourceTO getResourceTO(final ExternalResource resource) {
ResourceTO resourceTO = new ResourceTO();
// set the resource name
resourceTO.setKey(resource.getKey());
// set the connector instance
ConnInstance connector = resource.getConnector();
resourceTO.setConnector(connector == null ? null : connector.getKey());
resourceTO.setConnectorDisplayName(connector == null ? null : connector.getDisplayName());
// set the provision information
resource.getProvisions().stream().map(provision -> {
ProvisionTO provisionTO = new ProvisionTO();
provisionTO.setKey(provision.getKey());
provisionTO.setAnyType(provision.getAnyType().getKey());
provisionTO.setObjectClass(provision.getObjectClass().getObjectClassValue());
provisionTO.getAuxClasses().addAll(provision.getAuxClasses().stream().map(cls -> cls.getKey()).collect(Collectors.toList()));
provisionTO.setSyncToken(provision.getSerializedSyncToken());
if (provision.getMapping() != null) {
MappingTO mappingTO = new MappingTO();
provisionTO.setMapping(mappingTO);
mappingTO.setConnObjectLink(provision.getMapping().getConnObjectLink());
populateItems(provision.getMapping().getItems(), mappingTO);
}
virSchemaDAO.findByProvision(provision).forEach(virSchema -> {
provisionTO.getVirSchemas().add(virSchema.getKey());
MappingItem linkingMappingItem = virSchema.asLinkingMappingItem();
ItemTO itemTO = new ItemTO();
itemTO.setKey(linkingMappingItem.getKey());
BeanUtils.copyProperties(linkingMappingItem, itemTO, ITEM_IGNORE_PROPERTIES);
provisionTO.getMapping().getLinkingItems().add(itemTO);
});
return provisionTO;
}).forEachOrdered(provisionTO -> {
resourceTO.getProvisions().add(provisionTO);
});
if (resource.getOrgUnit() != null) {
OrgUnit orgUnit = resource.getOrgUnit();
OrgUnitTO orgUnitTO = new OrgUnitTO();
orgUnitTO.setKey(orgUnit.getKey());
orgUnitTO.setObjectClass(orgUnit.getObjectClass().getObjectClassValue());
orgUnitTO.setSyncToken(orgUnit.getSerializedSyncToken());
orgUnitTO.setConnObjectLink(orgUnit.getConnObjectLink());
populateItems(orgUnit.getItems(), orgUnitTO);
resourceTO.setOrgUnit(orgUnitTO);
}
resourceTO.setEnforceMandatoryCondition(resource.isEnforceMandatoryCondition());
resourceTO.setPropagationPriority(resource.getPropagationPriority());
resourceTO.setRandomPwdIfNotProvided(resource.isRandomPwdIfNotProvided());
resourceTO.setCreateTraceLevel(resource.getCreateTraceLevel());
resourceTO.setUpdateTraceLevel(resource.getUpdateTraceLevel());
resourceTO.setDeleteTraceLevel(resource.getDeleteTraceLevel());
resourceTO.setProvisioningTraceLevel(resource.getProvisioningTraceLevel());
resourceTO.setPasswordPolicy(resource.getPasswordPolicy() == null ? null : resource.getPasswordPolicy().getKey());
resourceTO.setAccountPolicy(resource.getAccountPolicy() == null ? null : resource.getAccountPolicy().getKey());
resourceTO.setPullPolicy(resource.getPullPolicy() == null ? null : resource.getPullPolicy().getKey());
resourceTO.getConfOverride().addAll(resource.getConfOverride());
Collections.sort(resourceTO.getConfOverride());
resourceTO.setOverrideCapabilities(resource.isOverrideCapabilities());
resourceTO.getCapabilitiesOverride().addAll(resource.getCapabilitiesOverride());
resourceTO.getPropagationActions().addAll(resource.getPropagationActions().stream().map(Entity::getKey).collect(Collectors.toList()));
return resourceTO;
}
Aggregations