com.evolveum.midpoint.task.api.Task类的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(14.4k)|赞(0)|评价(0)|浏览(145)

本文整理了Java中com.evolveum.midpoint.task.api.Task类的一些代码示例,展示了Task类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Task类的具体详情如下:
包路径:com.evolveum.midpoint.task.api.Task
类名称:Task

Task介绍

[英]Task instance - a logical unit of work that is either done synchronously, asynchronously, it is deferred, scheduled, etc. The classes that implement this interface hold a "java" task state. They represent the in-memory task data structure. The instances must be able to serialize the state to the repository object (TaskType) when needed. The task implementation should be simple Java objects (POJOs). They are created also for a synchronous tasks, which means they are created frequently. We want a low overhead for task management until the task is made persistent. API for modifying task properties works like this: - A getter (get) reads data from the in-memory representation of a task. - A setter (set) writes data to the in-memory representation, and prepares a PropertyDelta to be written into repository later (of course, only for persistent tasks). PropertyDeltas should be then written by calling savePendingModifications method. In case you want to write property change into the repository immediately, you have to use setImmediate method. In that case, the property change does not go into the list of pending modifications, but it is instantly written into the repository (so the method uses OperationResult as parameter, and can throw relevant exceptions as well).
[中]Task instance(任务实例)-一个逻辑工作单元,可以同步、异步完成,也可以延迟、计划等。实现此接口的类保持“java”任务状态。它们代表内存中的任务数据结构。这些实例必须能够在需要时将状态序列化到存储库对象(TaskType)。任务实现应该是简单Java对象(POJO)。它们也是为同步任务创建的,这意味着它们经常被创建。在任务持久化之前,我们希望任务管理的开销较低。用于修改任务属性的API的工作原理如下:-getter(get)从任务的内存表示中读取数据。-setter(set)将数据写入内存中的表示,并准备一个PropertyDelta,以便稍后写入存储库(当然,仅用于持久性任务)。然后,应该通过调用savePendingModifications方法来编写PropertyDelta。如果要立即将属性更改写入存储库,必须使用setImmediate方法。在这种情况下,属性更改不会进入挂起的修改列表,但会立即写入存储库(因此该方法使用OperationResult作为参数,并可以引发相关异常)。

代码示例

代码示例来源:origin: Evolveum/midpoint

protected void assertAllowRequestAssignmentItems(String userOid, String targetRoleOid, ItemPath... expectedAllowedItemPaths)
    throws SchemaException, SecurityViolationException, CommunicationException, ObjectNotFoundException, ConfigurationException, ExpressionEvaluationException {
  Task task = createTask(AbstractModelIntegrationTest.class.getName() + ".assertAllowRequestItems");
  OperationResult result = task.getResult();
  assertAllowRequestAssignmentItems(userOid, targetRoleOid, task, result, expectedAllowedItemPaths);
  assertSuccess(result);
}

代码示例来源:origin: Evolveum/midpoint

private <F extends ObjectType> void applyCreateMetadata(LensContext<F> context, MetadataType metaData, XMLGregorianCalendar now, Task task) {
  String channel = LensUtil.getChannel(context, task);
  metaData.setCreateChannel(channel);
  metaData.setCreateTimestamp(now);
  if (task.getOwner() != null) {
    metaData.setCreatorRef(createObjectRef(task.getOwner(), prismContext));
  }
  metaData.setCreateTaskRef(task.getOid() != null ? createObjectRef(task.getTaskPrismObject(), prismContext) : null);
}

代码示例来源:origin: Evolveum/midpoint

private static void dumpTaskTree(StringBuilder sb, int indent, Task task, OperationResult result) throws SchemaException {
    DebugUtil.indentDebugDump(sb, indent);
    sb.append(task)
        .append(" [").append(task.getExecutionStatus())
        .append(", ").append(task.getProgress())
        .append(", ").append(task.getNode())
        .append("]").append("\n");
    List<Task> subtasks = task.listSubtasks(result);
    for (Task subtask : subtasks) {
      dumpTaskTree(sb, indent + 1, subtask, result);
    }
  }
}

代码示例来源:origin: Evolveum/midpoint

private void scheduleSubtasksNow(List<Task> subtasks, Task masterTask, OperationResult opResult) throws SchemaException,
    ObjectAlreadyExistsException, ObjectNotFoundException {
  masterTask.makeWaiting(TaskWaitingReason.OTHER_TASKS, TaskUnpauseActionType.RESCHEDULE);  // i.e. close for single-run tasks
  masterTask.savePendingModifications(opResult);
  Set<String> dependents = getDependentTasksIdentifiers(subtasks);
  // first set dependents to waiting, and only after that start runnables
  for (Task subtask : subtasks) {
    if (dependents.contains(subtask.getTaskIdentifier())) {
      subtask.makeWaiting(TaskWaitingReason.OTHER_TASKS, TaskUnpauseActionType.EXECUTE_IMMEDIATELY);
      subtask.savePendingModifications(opResult);
    }
  }
  for (Task subtask : subtasks) {
    if (!dependents.contains(subtask.getTaskIdentifier())) {
      taskManager.scheduleTaskNow(subtask, opResult);
    }
  }
}

代码示例来源:origin: Evolveum/midpoint

protected Task createTask(String operationName) {
  Task task = super.createTask(operationName);
  PrismObject<UserType> defaultActor = getDefaultActor();
  if (defaultActor != null) {
    task.setOwner(defaultActor);
  }
  task.setChannel(DEFAULT_CHANNEL);
  return task;
}

代码示例来源:origin: Evolveum/midpoint

protected <O extends ObjectType> void assertAllow(String opname, Attempt attempt) throws Exception {
  Task task = taskManager.createTaskInstance(AbstractModelIntegrationTest.class.getName() + ".assertAllow."+opname);
  task.setOwner(getSecurityContextPrincipalUser());
  task.setChannel(SchemaConstants.CHANNEL_GUI_USER_URI);
  OperationResult result = task.getResult();
  try {
    logAttempt(opname);
    attempt.run(task, result);
  } catch (SecurityViolationException e) {
    failAllow(opname, e);
  }
  result.computeStatus();
  TestUtil.assertSuccess(result);
  logAllow(opname);
}

代码示例来源:origin: Evolveum/midpoint

@Override
public boolean check() throws CommonException {
  task.refresh(waitResult);
  OperationResult result = task.getResult();
  if (verbose) display("Check result", result);
  return task.getExecutionStatus() == TaskExecutionStatus.CLOSED;
}
@Override

代码示例来源:origin: Evolveum/midpoint

@Test
public void test200StartRemediationDeny() throws Exception {
  final String TEST_NAME = "test200StartRemediationDeny";
  TestUtil.displayTestTitle(this, TEST_NAME);
  login(getUserFromRepo(USER_ELAINE_OID));
  // GIVEN
  Task task = taskManager.createTaskInstance(TestCertificationBasic.class.getName() + "." + TEST_NAME);
  task.setOwner(userAdministrator.asPrismObject());
  OperationResult result = task.getResult();
  // WHEN+THEN
  TestUtil.displayWhen(TEST_NAME);
  try {
    certificationService.startRemediation(campaignOid, task, result);
  } catch (SecurityViolationException e) {
    System.out.println("Got expected deny exception: " + e.getMessage());
  }
}

代码示例来源:origin: Evolveum/midpoint

public void launch(AccessCertificationCampaignType campaign, OperationResult parentResult) throws SchemaException, ObjectNotFoundException {
  LOGGER.debug("Launching closing task handler for campaign {} as asynchronous task", toShortString(campaign));
  OperationResult result = parentResult.createSubresult(CLASS_DOT + "launch");
  result.addParam("campaignOid", campaign.getOid());
  Task task = taskManager.createTaskInstance();
  task.setHandlerUri(HANDLER_URI);
  task.setName(new PolyStringType("Closing " + campaign.getName()));
  task.setObjectRef(ObjectTypeUtil.createObjectRef(campaign, prismContext));
  task.setOwner(repositoryService.getObject(UserType.class, SystemObjectsType.USER_ADMINISTRATOR.value(), null, result));
  taskManager.switchToBackground(task, result);
  result.setBackgroundTaskOid(task.getOid());
  if (result.isInProgress()) {
    result.recordStatus(OperationResultStatus.IN_PROGRESS, "Closing task "+task+" was successfully started, please use Server Tasks to see its status.");
  }
  LOGGER.trace("Closing task for {} switched to background, control thread returning with task {}", toShortString(campaign), task);
}

代码示例来源:origin: Evolveum/midpoint

private void createAndProcessEvent(Task task, TaskRunResult runResult, EventOperationType operationType) {
  TaskEvent event = new TaskEvent(lightweightIdentifierGenerator, task, runResult, operationType, task.getChannel());
  if (task.getOwner() != null) {
    event.setRequester(new SimpleObjectRefImpl(notificationsUtil, task.getOwner().asObjectable()));
    event.setRequestee(new SimpleObjectRefImpl(notificationsUtil, task.getOwner().asObjectable()));
  } else {
    LOGGER.debug("No owner for task " + task + ", therefore no requester and requestee will be set for event " + event.getId());
  }
  Task opTask = taskManager.createTaskInstance(OPERATION_PROCESS_EVENT);
  notificationManager.processEvent(event, opTask, opTask.getResult());
}

代码示例来源:origin: Evolveum/midpoint

subtask.addDependent(dependent.getTaskIdentifier());
  if (dependent.getExecutionStatus() == TaskExecutionStatus.SUSPENDED) {
    dependent.makeWaiting(TaskWaitingReason.OTHER_TASKS, TaskUnpauseActionType.EXECUTE_IMMEDIATELY);
    dependent.savePendingModifications(opResult);
subtask.savePendingModifications(opResult);

代码示例来源:origin: Evolveum/midpoint

public static void finishRequest(Task task, SecurityHelper securityHelper) {
  task.getResult().computeStatus();
  ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_REST_URI);
  connEnv.setSessionIdOverride(task.getTaskIdentifier());
  securityHelper.auditLogout(connEnv, task);
}

代码示例来源:origin: Evolveum/midpoint

public CounterSepcification getCounterSpec(Task task) {
    if (task.getOid() == null) {
      return null;
    }
    return countersMap.get(task.getOid());
  }
}

代码示例来源:origin: Evolveum/midpoint

if (coordinatorTask.getExecutionStatus() == null) {
  throw new IllegalStateException("Null executionStatus of " + coordinatorTask);
switch (coordinatorTask.getExecutionStatus()) {
  case WAITING: workerExecutionStatus = TaskExecutionStatusType.RUNNABLE; break;
  case SUSPENDED: workerExecutionStatus = TaskExecutionStatusType.SUSPENDED; break;
  case CLOSED: workerExecutionStatus = TaskExecutionStatusType.CLOSED; break;             // not very useful
  case RUNNABLE: workerExecutionStatus = TaskExecutionStatusType.SUSPENDED; break;
  default: throw new IllegalStateException("Unsupported executionStatus of " + coordinatorTask + ": " + coordinatorTask.getExecutionStatus());
TaskType coordinatorTaskBean = coordinatorTask.getTaskType();
TaskWorkManagementType wsCfg = coordinatorTask.getWorkManagement();
WorkersManagementType workersCfg = wsCfg.getWorkers();
  worker.setCategory(coordinatorTask.getCategory());
  worker.setObjectRef(CloneUtil.clone(coordinatorTaskBean.getObjectRef()));
  worker.setRecurrence(TaskRecurrenceType.SINGLE);
  worker.setParent(coordinatorTask.getTaskIdentifier());
  worker.beginWorkManagement().taskKind(TaskKindType.WORKER);
  PrismContainer<Containerable> coordinatorExtension = coordinatorTaskBean.asPrismObject().findContainer(TaskType.F_EXTENSION);

代码示例来源:origin: Evolveum/midpoint

ApprovalStageDefinitionType stageDef = ActivitiUtil.getAndVerifyCurrentStage(execution, wfTask, false, prismContext);
int stageNumber = stageDef.getNumber();
opTask.setChannel(wfTask.getChannel());         // TODO !!!!!!!!!!
  recordAutoCompletionDecision(wfTask.getOid(), predeterminedOutcome, automatedCompletionReason, stageNumber, opResult);

代码示例来源:origin: Evolveum/midpoint

@Test
public void test010CycleCronLoose() throws Exception {
  final String TEST_NAME = "test010CycleCronLoose";
  final OperationResult result = createResult(TEST_NAME, LOGGER);
  addObjectFromFile(taskFilename(TEST_NAME));
  waitForTaskProgress(taskOid(TEST_NAME), result, 15000, 2000, 2);
  // Check task status
  Task task = getTask(taskOid(TEST_NAME), result);
  AssertJUnit.assertNotNull(task);
  System.out.println(task.debugDump());
  TaskType t = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result).getValue().getValue();
  System.out.println(ObjectTypeUtil.dump(t));
  AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus());
  // .. and last run should not be zero
  AssertJUnit.assertNotNull(task.getLastRunStartTimestamp());
  assertFalse(task.getLastRunStartTimestamp() == 0);
  AssertJUnit.assertNotNull(task.getLastRunFinishTimestamp());
  assertFalse(task.getLastRunFinishTimestamp() == 0);
  // The progress should be at least 2 as the task has run at least twice
  AssertJUnit.assertTrue("Task has not been executed at least twice", task.getProgress() >= 2);
  // Test for presence of a result. It should be there and it should
  // indicate success
  assertSuccessOrInProgress(task);
  // Suspend the task (in order to keep logs clean), without much waiting
  taskManager.suspendTaskQuietly(task, 100, result);
}

代码示例来源:origin: Evolveum/midpoint

@BeforeMethod
public void initSystemConditional() throws Exception {
  // Check whether we are already initialized
  assertNotNull("Repository is not wired properly", repositoryService);
  assertNotNull("Task manager is not wired properly", taskManager);
  LOGGER.trace("initSystemConditional: {} systemInitialized={}", this.getClass(), isSystemInitialized());
  if (!isSystemInitialized()) {
    PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
    PrismTestUtil.setPrismContext(prismContext);
    LOGGER.trace("initSystemConditional: invoking initSystem");
    Task initTask = taskManager.createTaskInstance(this.getClass().getName() + ".initSystem");
    initTask.setChannel(SchemaConstants.CHANNEL_GUI_INIT_URI);
    OperationResult result = initTask.getResult();
    InternalMonitor.reset();
    InternalsConfig.setPrismMonitoring(true);
    prismContext.setMonitor(new InternalMonitor());
    
    initSystem(initTask, result);
    postInitSystem(initTask, result);
    result.computeStatus();
    IntegrationTestTools.display("initSystem result", result);
    TestUtil.assertSuccessOrWarning("initSystem failed (result)", result, 1);
    setSystemInitialized();
  }
}

代码示例来源:origin: Evolveum/midpoint

private <T> T get(Task task, QName propertyName, T defaultValue) {
  PrismProperty<T> property = task.getExtensionProperty(propertyName);
  if (property == null) {
    return defaultValue;
  } else {
    return property.getRealValue();
  }
}

代码示例来源:origin: Evolveum/midpoint

private void setOperationContext(OperationExecutionType operation,
    OperationResultStatusType overallStatus, XMLGregorianCalendar now, String channel, Task task) {
  if (task.getParentForLightweightAsynchronousTask() != null) {
    task = task.getParentForLightweightAsynchronousTask();
  }
  if (task.isPersistent()) {
    operation.setTaskRef(ObjectTypeUtil.createObjectRef(task.getTaskPrismObject(), prismContext));
  }
  operation.setStatus(overallStatus);
  operation.setInitiatorRef(ObjectTypeUtil.createObjectRef(task.getOwner(), prismContext));		// TODO what if the real initiator is different? (e.g. when executing approved changes)
  operation.setChannel(channel);
  operation.setTimestamp(now);
}

代码示例来源:origin: Evolveum/midpoint

/**
 * Creates a root job, based on provided job start instruction.
 * Puts a reference to the workflow root task to the model task.
 *
 * @param rootInstruction instruction to use
 * @param taskFromModel (potential) parent task
 * @param wfConfigurationType
 * @param result
 * @return reference to a newly created job
 * @throws SchemaException
 * @throws ObjectNotFoundException
 */
public WfTask submitRootTask(WfTaskCreationInstruction rootInstruction, Task taskFromModel, WfConfigurationType wfConfigurationType,
    OperationResult result)
    throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException {
  WfTask rootWfTask = wfTaskController.submitWfTask(rootInstruction, determineParentTaskForRoot(taskFromModel), wfConfigurationType, taskFromModel.getChannel(), result);
  result.setBackgroundTaskOid(rootWfTask.getTask().getOid());
  wfTaskUtil.setRootTaskOidImmediate(taskFromModel, rootWfTask.getTask().getOid(), result);
  return rootWfTask;
}

相关文章

微信公众号

最新文章

更多