Skip to content

Commit

Permalink
MID-7580: fix for creating task with activity for custom action in table
Browse files Browse the repository at this point in the history
  • Loading branch information
skublik committed Jan 27, 2022
1 parent 0a7cf74 commit f837dbb
Showing 1 changed file with 63 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@

import static com.evolveum.midpoint.gui.api.page.PageBase.createStringResourceStatic;
import static com.evolveum.midpoint.model.api.ModelExecuteOptions.toModelExecutionOptionsBean;
import static com.evolveum.midpoint.schema.GetOperationOptions.createExecutionPhase;
import static com.evolveum.midpoint.schema.SelectorOptions.createCollection;
import static com.evolveum.midpoint.schema.util.ObjectTypeUtil.createObjectRef;
import static com.evolveum.midpoint.xml.ns._public.common.common_3.TaskExecutionStateType.RUNNABLE;
import static com.evolveum.midpoint.xml.ns._public.common.common_3.TaskSchedulingStateType.READY;

import java.io.PrintWriter;
import java.io.StringWriter;
Expand All @@ -24,6 +29,7 @@
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;

import com.evolveum.midpoint.prism.delta.DeltaFactory;
import com.evolveum.midpoint.schema.util.task.work.ObjectSetUtil;

import org.apache.commons.collections4.CollectionUtils;
Expand Down Expand Up @@ -225,7 +231,6 @@ public final class WebComponentUtil {
private static final Map<Class<? extends ObjectType>, Class<? extends PageBase>> OBJECT_DETAILS_PAGE_MAP;
private static final Map<Class<? extends ObjectType>, Class<? extends PageBase>> CREATE_NEW_OBJECT_PAGE_MAP;


private static final Map<Class<? extends ObjectType>, Class<? extends PageBase>> OBJECT_DETAILS_PAGE_MAP_NEW;

static {
Expand Down Expand Up @@ -705,8 +710,8 @@ public static TaskType createIterativeChangeExecutionTask(String taskName, QName
IterativeChangeExecutionWorkDefinitionType workDef =
new IterativeChangeExecutionWorkDefinitionType(PrismContext.get())
.beginObjects()
.type(applicableType)
.query(pageBase.getQueryConverter().createQueryType(query))
.type(applicableType)
.query(pageBase.getQueryConverter().createQueryType(query))
.<IterativeChangeExecutionWorkDefinitionType>end()
.delta(DeltaConvertor.toObjectDeltaType(delta))
.executionOptions(toModelExecutionOptionsBean(options));
Expand Down Expand Up @@ -2412,7 +2417,7 @@ public static List<QName> getMatchingRuleList() {

public static String createHumanReadableByteCount(long bytes) {
int unit = 1024;
if (bytes < unit) { return bytes + "B"; }
if (bytes < unit) {return bytes + "B";}
int exp = (int) (Math.log(bytes) / Math.log(unit));
char pre = "KMGTPE".charAt(exp - 1);
return String.format("%.1f%sB", bytes / Math.pow(unit, exp), pre);
Expand All @@ -2428,7 +2433,6 @@ public static void setCurrentPage(Table table, ObjectPaging paging) {
return;
}


long itemsPerPage = table.getDataTable().getItemsPerPage();
long page = ((paging.getOffset() + itemsPerPage) / itemsPerPage) - 1;
if (page < 0) {
Expand Down Expand Up @@ -3319,7 +3323,7 @@ public void onClick(AjaxRequestTarget target) {
OperationResult result = new OperationResult(operation);
try {
Collection<String> oids;
if (getRowModel() != null){
if (getRowModel() != null) {
oids = Collections.singletonList(getRowModel().getObject().getValue().getOid());
} else {
oids = CollectionUtils.emptyIfNull(selectedObjectsSupplier.get())
Expand All @@ -3329,24 +3333,37 @@ public void onClick(AjaxRequestTarget target) {
.collect(Collectors.toSet());
}
if (!oids.isEmpty()) {
Map<QName, Object> extensionValues = prepareExtensionValues(oids);
TaskType executorTask = pageBase.getModelInteractionService().submitTaskFromTemplate(
templateOid, extensionValues, pageBase.createSimpleTask(operation), result);
ObjectSetBasedWorkDefinitionType workDef = ObjectSetUtil.getObjectSetDefinitionFromTask(executorTask);
QueryType query = (QueryType) extensionValues.get(SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY);
@NotNull Item<PrismValue, ItemDefinition> extensionQuery = prepareExtensionValues(oids);

MidPointPrincipal principal = pageBase.getPrincipal();
if (principal == null) {
throw new SecurityViolationException("No current user");
}
TaskType newTask = pageBase.getModelService().getObject(TaskType.class, templateOid,
createCollection(createExecutionPhase()), pageBase.createSimpleTask(operation), result).asObjectable();
newTask.setName(PolyStringType.fromOrig(newTask.getName().getOrig() + " " + (int) (Math.random() * 10000)));
newTask.setOid(null);
newTask.setTaskIdentifier(null);
newTask.setOwnerRef(createObjectRef(principal.getFocus()));
newTask.setExecutionState(RUNNABLE);
newTask.setSchedulingState(READY);
newTask.asPrismObject().getOrCreateExtension().add(extensionQuery);
ObjectSetBasedWorkDefinitionType workDef = ObjectSetUtil.getObjectSetDefinitionFromTask(newTask);
QueryType query = (QueryType) extensionQuery.getRealValue();
ObjectSetType objectSet = workDef.getObjects();
if (objectSet == null){
if (objectSet == null) {
objectSet = new ObjectSetType();
objectSet.setType(ObjectType.COMPLEX_TYPE);
}
objectSet.setQuery(query);
workDef.setObjects(objectSet);
ObjectDelta<TaskType> delta = pageBase.getPrismContext().deltaFactory().object().createModifyDelta(executorTask.getOid(),
pageBase.getPrismContext().deltaFactory().container()
.createModificationReplace(workDef.asPrismContainerValue().getPath(), TaskType.class, workDef.clone()), TaskType.class);
saveTask(delta, result, pageBase);
result.setInProgress(); // this should be probably have been done in submitTaskFromTemplate
result.setBackgroundTaskOid(executorTask.getOid());
ObjectDelta<TaskType> delta = DeltaFactory.Object.createAddDelta(newTask.asPrismObject());
Collection<ObjectDeltaOperation<? extends ObjectType>> executedChanges = saveTask(delta, result, pageBase);
String newTaskOid = ObjectDeltaOperation.findAddDeltaOid(executedChanges, newTask.asPrismObject());
newTask.setOid(newTaskOid);
newTask.setTaskIdentifier(newTaskOid);
result.setInProgress();
result.setBackgroundTaskOid(newTask.getOid());
} else {
result.recordWarning(pageBase.createStringResource("WebComponentUtil.message.createMenuItemsFromActions.warning").getString());
}
Expand All @@ -3370,15 +3387,23 @@ public void onClick(AjaxRequestTarget target) {
*/

@NotNull
private Map<QName, Object> prepareExtensionValues(Collection<String> oids) throws SchemaException {
Map<QName, Object> extensionValues = new HashMap<>();
private Item<PrismValue, ItemDefinition> prepareExtensionValues(Collection<String> oids) throws SchemaException {
PrismContext prismContext = pageBase.getPrismContext();
ObjectQuery objectQuery = prismContext.queryFor(ObjectType.class)
.id(oids.toArray(new String[0]))
.build();
QueryType queryBean = pageBase.getQueryConverter().createQueryType(objectQuery);
extensionValues.put(SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY, queryBean);
return extensionValues;
PrismContainerDefinition<?> extDef = PrismContext.get().getSchemaRegistry()
.findObjectDefinitionByCompileTimeClass(TaskType.class).findContainerDefinition(TaskType.F_EXTENSION);
ItemDefinition<Item<PrismValue, ItemDefinition>> def = extDef != null
? extDef.findItemDefinition(SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY)
: null;
if (def == null) {
throw new SchemaException("No definition of " + SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY + " in the extension");
}
Item<PrismValue, ItemDefinition> extensionItem = def.instantiate();
extensionItem.add(prismContext.itemFactory().createValue(queryBean));
return extensionItem;
}
});
});
Expand Down Expand Up @@ -3793,7 +3818,7 @@ public static <O extends ObjectType> CompositedIcon createCompositeIconForObject
String iconColor = getIconColor(basicIconDisplayType);

CompositedIconBuilder builder = iconBuilder.setBasicIcon(
getIconCssClass(basicIconDisplayType), IconCssStyle.IN_ROW_STYLE)
getIconCssClass(basicIconDisplayType), IconCssStyle.IN_ROW_STYLE)
.appendColorHtmlValue(StringUtils.isNotEmpty(iconColor) ? iconColor : "");

StringBuilder title = new StringBuilder(getOrigStringFromPolyOrEmpty(basicIconDisplayType.getTooltip()));
Expand Down Expand Up @@ -3864,7 +3889,7 @@ public static CompositedIcon createAccountIcon(ShadowType shadow, PageBase pageB
} else {
builder.appendLayerIcon(icon, IconCssStyle.BOTTOM_LEFT_STYLE);
}
if (StringUtils.isNotBlank(title)){
if (StringUtils.isNotBlank(title)) {
title = title + "\n " + pageBase.createStringResource("ChangePasswordPanel.legendMessage.maintenance").getString();
} else {
title = pageBase.createStringResource("ChangePasswordPanel.legendMessage.maintenance").getString();
Expand Down Expand Up @@ -4065,7 +4090,7 @@ public static <O extends ObjectType> IconType getIconForActivationStatus(O obj)
IconType icon = new IconType();
if (LockoutStatusType.LOCKED == activation.getLockoutStatus()) {
icon.setCssClass(GuiStyleConstants.CLASS_LOCK_STATUS);
} else if (ActivationStatusType.ENABLED == status) {
} else if (ActivationStatusType.ENABLED == status) {
return null;
} else if (ActivationStatusType.DISABLED == status) {
icon.setCssClass(GuiStyleConstants.CLASS_BAN);
Expand Down Expand Up @@ -4171,7 +4196,7 @@ public static void deleteSyncTokenPerformed(AjaxRequestTarget target, ResourceTy
String handlerUri = "http://midpoint.evolveum.com/xml/ns/public/model/synchronization/task/live-sync/handler-3";
ObjectReferenceType resourceRef = new ObjectReferenceType();
resourceRef.setOid(resourceOid);
PrismObject<TaskType> oldTask;
PrismObject<TaskType> task;

OperationResult result = new OperationResult(pageBase.getClass().getName() + "." + "deleteSyncToken");
ObjectQuery query = pageBase.getPrismContext().queryFor(TaskType.class)
Expand All @@ -4184,13 +4209,13 @@ public static void deleteSyncTokenPerformed(AjaxRequestTarget target, ResourceTy
if (taskList.size() != 1) {
pageBase.error(pageBase.createStringResource("pageResource.message.invalidTaskSearch"));
} else {
oldTask = taskList.get(0);
PrismProperty<?> property = oldTask.findProperty(ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN));
task = taskList.get(0);
PrismProperty<?> property = task.findProperty(ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN));

if (property != null) {
Object value = property.getRealValue();

ObjectDelta<TaskType> delta = pageBase.getPrismContext().deltaFactory().object().createModifyDelta(oldTask.getOid(),
ObjectDelta<TaskType> delta = pageBase.getPrismContext().deltaFactory().object().createModifyDelta(task.getOid(),
pageBase.getPrismContext().deltaFactory().property()
.createModificationDeleteProperty(ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN), property.getDefinition(), value),
TaskType.class);
Expand Down Expand Up @@ -4301,6 +4326,7 @@ public static List<AssignmentObjectRelation> divideAssignmentRelationsByAllValue
* it's expected that the list of AssignmentObjectRelation will be pre-prepared in such manner that each AssignmentObjectRelation
* in the list will contain only one object type, one relation and one archetypeRef. This methods compares only the first
* items in these lists
*
* @param list
* @param relation
* @return
Expand Down Expand Up @@ -4342,20 +4368,22 @@ public static boolean assignmentObjectRelationAlreadyExists(List<AssignmentObjec
return true;
}

private static void saveTask(ObjectDelta<TaskType> delta, OperationResult result, PageBase pageBase) {
private static Collection<ObjectDeltaOperation<? extends ObjectType>> saveTask(ObjectDelta<TaskType> delta, OperationResult result, PageBase pageBase) {
Task opTask = pageBase.createSimpleTask(pageBase.getClass().getName() + "." + "saveTask");

if (LOGGER.isTraceEnabled()) {
LOGGER.trace(delta.debugDump());
}

Collection<ObjectDeltaOperation<? extends ObjectType>> ret = null;
try {
pageBase.getModelService().executeChanges(MiscUtil.createCollection(delta), null, opTask, result);
ret = pageBase.getModelService().executeChanges(MiscUtil.createCollection(delta), null, opTask, result);
} catch (Exception e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't save task.", e);
result.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntSaveTask").getString(), e);
}
result.recomputeStatus();
return ret;
}

// TODO: use LocalizationService.translate(polyString) instead
Expand Down Expand Up @@ -4951,8 +4979,8 @@ public static <F extends FocusType> Locale getLocale() {

Locale locale = null;
if (principal instanceof GuiProfiledPrincipal
&& ((GuiProfiledPrincipal)principal).getCompiledGuiProfile().getLocale() != null) {
locale = ((GuiProfiledPrincipal)principal).getCompiledGuiProfile().getLocale();
&& ((GuiProfiledPrincipal) principal).getCompiledGuiProfile().getLocale() != null) {
locale = ((GuiProfiledPrincipal) principal).getCompiledGuiProfile().getLocale();
} else {
F focus = (F) principal.getFocus();
if (focus == null) {
Expand Down Expand Up @@ -5135,7 +5163,7 @@ public static List<DisplayableValue<?>> getAllowedValues(SearchFilterParameterTy

if (!((Set<?>) value).isEmpty()) {
if (!(((Set<?>) value).iterator().next() instanceof PrismPropertyValue)
|| !(((PrismPropertyValue)(((Set<?>) value).iterator().next())).getValue() instanceof DisplayableValue)) {
|| !(((PrismPropertyValue) (((Set<?>) value).iterator().next())).getValue() instanceof DisplayableValue)) {
LOGGER.error("Exception return unexpected type, expected Set<PPV<DisplayableValue>>, but was " + (value == null ? null : value.getClass()));
pageBase.error(pageBase.createStringResource("FilterSearchItem.message.error.wrongType", expression).getString());
return allowedValues;
Expand Down Expand Up @@ -5182,7 +5210,7 @@ public static Map<IconCssStyle, IconType> createMainButtonLayerIcon(DisplayType
return layerIconMap;
}

public static <T extends AssignmentHolderType> void addNewArchetype(PrismObjectWrapper<T> object, String archetypeOid, AjaxRequestTarget target, PageBase pageBase){
public static <T extends AssignmentHolderType> void addNewArchetype(PrismObjectWrapper<T> object, String archetypeOid, AjaxRequestTarget target, PageBase pageBase) {
try {
PrismContainerWrapper<AssignmentType> archetypeAssignment = object.findContainer(TaskType.F_ASSIGNMENT);
PrismContainerValue<AssignmentType> archetypeAssignmentValue = archetypeAssignment.getItem().createNewValue();
Expand Down

0 comments on commit f837dbb

Please sign in to comment.