예제 #1
0
  private CallableResult<List<AssignmentItemDto>> loadAssignments() throws Exception {
    LOGGER.debug("Loading assignments.");
    CallableResult callableResult = new CallableResult();
    List<AssignmentItemDto> list = new ArrayList<AssignmentItemDto>();
    callableResult.setValue(list);

    PrismObject<UserType> user = principalModel.getObject();
    if (user == null || user.findContainer(UserType.F_ASSIGNMENT) == null) {
      return callableResult;
    }

    Task task = createSimpleTask(OPERATION_LOAD_ASSIGNMENTS);
    OperationResult result = task.getResult();
    callableResult.setResult(result);

    PrismContainer assignments = user.findContainer(UserType.F_ASSIGNMENT);
    List<PrismContainerValue> values = assignments.getValues();
    for (PrismContainerValue assignment : values) {
      AssignmentItemDto item = createAssignmentItem(user, assignment, task, result);
      if (item != null) {
        list.add(item);
      }
    }
    result.recordSuccessIfUnknown();
    result.recomputeStatus();

    Collections.sort(list);

    LOGGER.debug("Finished assignments loading.");

    return callableResult;
  }
예제 #2
0
  @Override
  protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd)
      throws ObjectNotFoundException, SchemaException {
    OperationResult result =
        new OperationResult(AbstractIntegrationTest.class.getName() + ".assertSyncToken");
    Task task = taskManager.getTask(syncTaskOid, result);
    result.computeStatus();
    TestUtil.assertSuccess(result);

    PrismProperty<String> syncTokenProperty = task.getExtensionProperty(SchemaConstants.SYNC_TOKEN);
    assertNotNull("No sync token in " + task, syncTokenProperty);
    String syncToken = syncTokenProperty.getRealValue();
    assertNotNull("No sync token in " + task, syncToken);
    IntegrationTestTools.display("Sync token", syncToken);

    GeneralizedTime syncTokenGt;
    try {
      syncTokenGt = new GeneralizedTime(syncToken);
    } catch (ParseException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    TestUtil.assertBetween(
        "Wrong time in sync token: " + syncToken,
        roundTsDown(tsStart),
        roundTsUp(tsEnd),
        syncTokenGt.getCalendar().getTimeInMillis());
  }
예제 #3
0
  public <O extends ObjectType> List<PrismObject<O>> resolveLinkRefs(
      Collection<ObjectReferenceType> refs, Class type) {

    List<PrismObject<O>> objects = new ArrayList<>();

    for (ObjectReferenceType ref : refs) {
      Class clazz = getClassForType(ref.getType());
      if (!clazz.equals(type)) {
        continue;
      }
      Task task = taskManager.createTaskInstance();
      OperationResult parentResult = task.getResult();
      try {
        PrismObject<O> obj =
            model.getObject(
                type,
                ref.getOid(),
                SelectorOptions.createCollection(GetOperationOptions.createResolveNames()),
                task,
                parentResult);
        objects.add(obj);
      } catch (ObjectNotFoundException
          | SchemaException
          | SecurityViolationException
          | CommunicationException
          | ConfigurationException e) {
        // TODO Auto-generated catch block
        LOGGER.error(
            "Could not get object with oid " + ref.getOid() + ". Reason: " + e.getMessage());
      }
    }
    return objects;
  }
예제 #4
0
  @Test
  public void test320GetResourceNoJars() throws Exception {
    TestUtil.displayTestTile(this, "test320GetResourceNoJars");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test320GetResourceNoJars");
    OperationResult result = task.getResult();

    // WHEN
    PrismObject<ResourceType> resource =
        modelService.getObject(ResourceType.class, RESOURCE_DUMMY_NOJARS_OID, null, task, result);

    // THEN
    display("getObject resource", resource);
    result.computeStatus();
    display("getObject result", result);
    assertEquals(
        "Expected partial errror in result",
        OperationResultStatus.PARTIAL_ERROR,
        result.getStatus());

    OperationResultType fetchResult = resource.asObjectable().getFetchResult();
    display("resource.fetchResult", fetchResult);
    assertEquals(
        "Expected partial errror in fetchResult",
        OperationResultStatusType.PARTIAL_ERROR,
        fetchResult.getStatus());

    // TODO: better asserts
    assertNotNull("Null resource", resource);
  }
  @Override
  public TaskRunResult run(Task task) {

    OperationResult result =
        task.getResult().createSubresult(WaitForTasksTaskHandler.class.getName() + ".run");
    result.recordInProgress();

    LOGGER.info("WaitForTasksTaskHandler run starting; in task " + task.getName());
    try {
      // todo resolve this brutal hack
      taskManagerImpl.pauseTask(task, TaskWaitingReason.OTHER, result);
      task.startWaitingForTasksImmediate(result);
    } catch (SchemaException e) {
      throw new SystemException(
          "Couldn't mark task as waiting for prerequisite tasks",
          e); // should not occur; will be handled by task runner
    } catch (ObjectNotFoundException e) {
      throw new SystemException(
          "Couldn't mark task as waiting for prerequisite tasks",
          e); // should not occur; will be handled by task runner
    }
    LOGGER.info("WaitForTasksTaskHandler run finishing; in task " + task.getName());

    result.computeStatus();

    TaskRunResult runResult = new TaskRunResult();
    runResult.setOperationResult(result);
    runResult.setProgress(task.getProgress()); // not to overwrite task's progress
    runResult.setRunResultStatus(TaskRunResultStatus.FINISHED);
    return runResult;
  }
예제 #6
0
  @Test(enabled = true)
  public void test010SetGetWfApprovedBy() throws Exception {

    Task task = taskManager.createTaskInstance();
    OperationResult result = new OperationResult("test010SetGetWfApprovedBy");

    task.setOwner(
        repositoryService.getObject(
            UserType.class, SystemObjectsType.USER_ADMINISTRATOR.value(), null, result));
    taskManager.switchToBackground(task, result);

    wfTaskUtil.addApprovedBy(task, SystemObjectsType.USER_ADMINISTRATOR.value());
    wfTaskUtil.addApprovedBy(task, SystemObjectsType.USER_ADMINISTRATOR.value());
    wfTaskUtil.addApprovedBy(task, AbstractWfTestLegacy.R1BOSS_OID);
    wfTaskUtil.addApprovedBy(task, AbstractWfTestLegacy.R2BOSS_OID);
    task.savePendingModifications(result);

    Task task2 = taskManager.getTask(task.getOid(), result);
    PrismReference approvers = wfTaskUtil.getApprovedBy(task2);

    assertEquals("Incorrect number of approvers", 3, approvers.getValues().size());
    assertEquals(
        "Incorrect approvers",
        new HashSet(
            Arrays.asList(
                SystemObjectsType.USER_ADMINISTRATOR.value(),
                AbstractWfTestLegacy.R1BOSS_OID,
                AbstractWfTestLegacy.R2BOSS_OID)),
        new HashSet(
            Arrays.asList(
                approvers.getValue(0).getOid(),
                approvers.getValue(1).getOid(),
                approvers.getValue(2).getOid())));
  }
예제 #7
0
  /**
   * Assign two resources to a user. One of them is looney, the other is not. The result should be
   * that the account on the good resource is created.
   */
  private void testAssignTwoResoures(final String TEST_NAME, String badResourceOid)
      throws Exception {
    TestUtil.displayTestTile(this, TEST_NAME);

    // GIVEN
    Task task =
        taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME);
    OperationResult result = task.getResult();
    assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE);

    ObjectDelta<UserType> userDelta =
        createAccountAssignmentUserDelta(USER_JACK_OID, badResourceOid, null, true);
    userDelta.addModification(createAccountAssignmentModification(RESOURCE_DUMMY_OID, null, true));
    display("input delta", userDelta);
    Collection<ObjectDelta<? extends ObjectType>> deltas =
        MiscSchemaUtil.createCollection(userDelta);

    // WHEN
    modelService.executeChanges(deltas, null, task, result);

    // THEN
    result.computeStatus();
    display("executeChanges result", result);

    // TODO: ugly hack, see MID-1248
    if ("test401AssignTwoResouresBroken".equals(TEST_NAME)) {
      assertEquals(
          "Expected partial error in result",
          OperationResultStatus.PARTIAL_ERROR,
          result.getStatus());
    }

    DummyAccount jackDummyAccount = dummyResource.getAccountByUsername(USER_JACK_USERNAME);
    assertNotNull("No jack dummy account", jackDummyAccount);
  }
예제 #8
0
  public List<PrismObject<AccessCertificationCampaignType>> getCertificationCampaigns(
      Boolean alsoClosedCampaigns)
      throws SchemaException, ConfigurationException, ObjectNotFoundException,
          CommunicationException, SecurityViolationException {
    Task task = taskManager.createTaskInstance();

    ObjectQuery query =
        QueryBuilder.queryFor(AccessCertificationCampaignType.class, prismContext)
            .asc(F_NAME)
            .build();
    if (!Boolean.TRUE.equals(alsoClosedCampaigns)) {
      query.addFilter(
          QueryBuilder.queryFor(AccessCertificationCampaignType.class, prismContext)
              .not()
              .item(F_STATE)
              .eq(CLOSED)
              .buildFilter());
    }

    Collection<SelectorOptions<GetOperationOptions>> options =
        SelectorOptions.createCollection(GetOperationOptions.createResolveNames());
    options.add(
        SelectorOptions.create(
            AccessCertificationCampaignType.F_CASE,
            GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE)));

    return model.searchObjects(
        AccessCertificationCampaignType.class, query, options, task, task.getResult());
  }
예제 #9
0
 private List<AccessCertificationCaseType> getCertificationCampaignCasesAsBeans(
     String campaignName)
     throws SchemaException, SecurityViolationException, ConfigurationException,
         ObjectNotFoundException {
   Task task = taskManager.createTaskInstance();
   ObjectQuery query;
   if (StringUtils.isEmpty(campaignName)) {
     // query = null;
     return new ArrayList<>();
   } else {
     query =
         QueryBuilder.queryFor(AccessCertificationCaseType.class, prismContext)
             .item(PrismConstants.T_PARENT, F_NAME)
             .eqPoly(campaignName, "")
             .matchingOrig()
             .asc(
                 CertCampaignTypeUtil.getOrderBy(
                     F_OBJECT_REF)) // TODO first by type then by name (not supported by the
             // repository as of now)
             .asc(CertCampaignTypeUtil.getOrderBy(F_TARGET_REF)) // the same
             .build();
   }
   Collection<SelectorOptions<GetOperationOptions>> options =
       SelectorOptions.createCollection(GetOperationOptions.createResolveNames());
   return model.searchContainers(
       AccessCertificationCaseType.class, query, options, task, task.getResult());
 }
예제 #10
0
  @Test
  public void test120SearchAccountByUsernameJack() throws Exception {
    TestUtil.displayTestTile(this, "test120SearchAccountByUsernameJack");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test120SearchAccountByUsernameJack");
    OperationResult result = task.getResult();

    PrismObject<ResourceType> resource =
        modelService.getObject(ResourceType.class, RESOURCE_CSVFILE_BROKEN_OID, null, task, result);

    try {

      // WHEN
      PrismObject<ShadowType> account = findAccountByUsername("jack", resource, task, result);

      AssertJUnit.fail("Expected SystemException but the operation was successful");
    } catch (SystemException e) {
      // This is expected
      result.computeStatus();
      display("findAccountByUsername result", result);
      TestUtil.assertFailure("findAccountByUsername result", result);
    }
  }
예제 #11
0
  @Test
  public void test102GetAccountMurrayRaw() throws Exception {
    TestUtil.displayTestTile(this, "test102GetAccountMurrayRaw");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test102GetAccountMurrayRaw");
    OperationResult result = task.getResult();

    Collection<SelectorOptions<GetOperationOptions>> options =
        SelectorOptions.createCollection(GetOperationOptions.createRaw());

    // WHEN
    PrismObject<ShadowType> account =
        modelService.getObject(
            ShadowType.class, ACCOUNT_SHADOW_MURRAY_CSVFILE_OID, options, task, result);

    display("getObject account", account);
    result.computeStatus();
    display("getObject result", result);
    TestUtil.assertSuccess("getObject result", result);
    // TODO: better asserts
    assertNotNull("Null resource", account);
  }
예제 #12
0
  @Test
  public void test100GetAccountMurray() throws Exception {
    TestUtil.displayTestTile(this, "test100GetAccountMurray");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test100GetAccountMurray");
    OperationResult result = task.getResult();

    try {

      // WHEN
      PrismObject<ShadowType> account =
          modelService.getObject(
              ShadowType.class, ACCOUNT_SHADOW_MURRAY_CSVFILE_OID, null, task, result);

      AssertJUnit.fail("Expected SystemException but the operation was successful");
    } catch (SystemException e) {
      // This is expected
      display("Expected exception", e);
      result.computeStatus();
      display("getObject result", result);
      TestUtil.assertFailure("getObject result", result);
    }
  }
예제 #13
0
  @Test
  public void test020GetResourceBroken() throws Exception {
    TestUtil.displayTestTile(this, "test020GetResourceBroken");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test020GetResourceBroken");
    OperationResult result = task.getResult();

    // WHEN
    PrismObject<ResourceType> resource =
        modelService.getObject(ResourceType.class, RESOURCE_CSVFILE_BROKEN_OID, null, task, result);

    // THEN
    display("getObject resource", resource);
    result.computeStatus();
    display("getObject result", result);
    TestUtil.assertSuccess("getObject result", result);

    OperationResultType fetchResult = resource.asObjectable().getFetchResult();
    TestUtil.assertSuccess("resource.fetchResult", fetchResult);

    // TODO: better asserts
    assertNotNull("Null resource", resource);
  }
  protected void assertMonkeyIslandOrgSanity(int expectedFictional)
      throws ObjectNotFoundException, SchemaException, SecurityViolationException,
          CommunicationException, ConfigurationException {
    Task task =
        taskManager.createTaskInstance(
            AbstractInitializedModelIntegrationTest.class.getName()
                + ".assertMonkeyIslandOrgSanity");
    OperationResult result = task.getResult();

    PrismObject<OrgType> orgGovernorOffice =
        modelService.getObject(OrgType.class, ORG_GOVERNOR_OFFICE_OID, null, task, result);
    result.computeStatus();
    TestUtil.assertSuccess(result);
    OrgType orgGovernorOfficeType = orgGovernorOffice.asObjectable();
    assertEquals(
        "Wrong governor office name",
        PrismTestUtil.createPolyStringType("F0001"),
        orgGovernorOfficeType.getName());

    List<PrismObject<OrgType>> governorSubOrgs =
        searchOrg(ORG_GOVERNOR_OFFICE_OID, OrgFilter.Scope.ONE_LEVEL, task, result);
    if (verbose) display("governor suborgs", governorSubOrgs);
    assertEquals("Unexpected number of governor suborgs", 3, governorSubOrgs.size());

    List<PrismObject<OrgType>> functionalOrgs =
        searchOrg(ORG_GOVERNOR_OFFICE_OID, OrgFilter.Scope.SUBTREE, task, result);
    if (verbose) display("functional orgs (null)", functionalOrgs);
    assertEquals(
        "Unexpected number of functional orgs (null)",
        NUM_FUNCTIONAL_ORGS - 1 + expectedFictional,
        functionalOrgs.size());

    List<PrismObject<OrgType>> prootSubOrgs =
        searchOrg(ORG_PROJECT_ROOT_OID, OrgFilter.Scope.ONE_LEVEL, task, result);
    if (verbose) display("project root suborgs", prootSubOrgs);
    assertEquals("Unexpected number of governor suborgs", 2, prootSubOrgs.size());

    List<PrismObject<OrgType>> projectOrgs =
        searchOrg(ORG_PROJECT_ROOT_OID, OrgFilter.Scope.SUBTREE, task, result);
    if (verbose) display("project orgs (null)", projectOrgs);
    assertEquals(
        "Unexpected number of functional orgs (null)", NUM_PROJECT_ORGS - 1, projectOrgs.size());

    PrismObject<OrgType> orgScummBar =
        modelService.getObject(OrgType.class, ORG_SCUMM_BAR_OID, null, task, result);
    List<AssignmentType> scummBarInducements = orgScummBar.asObjectable().getInducement();
    assertEquals(
        "Unexpected number of scumm bar inducements: " + scummBarInducements,
        1,
        scummBarInducements.size());

    ResultHandler<OrgType> handler = getOrgSanityCheckHandler();
    if (handler != null) {
      modelService.searchObjectsIterative(OrgType.class, null, handler, null, task, result);
    }
  }
예제 #15
0
  private void savePerformed(AjaxRequestTarget target) {
    ObjectViewDto dto = model.getObject();
    if (StringUtils.isEmpty(dto.getXml())) {
      error(getString("pageResourceEdit.message.emptyXml"));
      target.add(getFeedbackPanel());
      return;
    }

    Task task = createSimpleTask(OPERATION_SAVE_RESOURCE);
    OperationResult result = task.getResult();
    try {
      Holder<PrismObject<ResourceType>> objectHolder = new Holder<PrismObject<ResourceType>>(null);
      validateObject(dto.getXml(), objectHolder, false, result);

      if (result.isAcceptable()) {
        PrismObject<ResourceType> newResource = objectHolder.getValue();
        updateConnectorRef(newResource, task, result);

        if (!isEditing()) {
          // we're adding new resource
          ObjectDelta delta = ObjectDelta.createAddDelta(newResource);
          getModelService()
              .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
        } else {
          // we're editing existing resource
          PrismObject<ResourceType> oldResource = dto.getObject();
          ObjectDelta<ResourceType> delta = oldResource.diff(newResource);

          getModelService()
              .executeChanges(
                  WebMiscUtil.createDeltaCollection(delta),
                  ModelExecuteOptions.createRaw(),
                  task,
                  result);
        }

        result.computeStatus();
      }
    } catch (Exception ex) {
      LoggingUtils.logException(LOGGER, "Couldn't save resource", ex);
      result.recordFatalError("Couldn't save resource.", ex);
    }

    if (WebMiscUtil.isSuccessOrHandledError(result)) {
      showResultInSession(result);
      setResponsePage(PageResources.class);
    } else {
      showResult(result);
      target.add(getFeedbackPanel());
    }
  }
예제 #16
0
  public <O extends ObjectType> List<PrismObject<O>> resolveAssignments(
      Collection<AssignmentType> assignments, Class<O> type) {
    List<PrismObject<O>> resolvedAssignments = new ArrayList<>();
    if (assignments == null) {
      return resolvedAssignments;
    }
    for (AssignmentType assignment : assignments) {
      Class clazz = null;
      String oid = null;
      if (assignment.getTargetRef() != null) {
        clazz = getClassForType(assignment.getTargetRef().getType());
        oid = assignment.getTargetRef().getOid();
      } else if (assignment.getTarget() != null) {
        clazz = assignment.getTarget().getClass();
      } else if (assignment.getTenantRef() != null) {
        clazz = getClassForType(assignment.getTenantRef().getType());
        oid = assignment.getTenantRef().getOid();
      }

      if (clazz == null && assignment.getConstruction() != null) {
        continue;
      } else {
        LOGGER.debug("Could not resolve assignment for type {}. No target type defined.", type);
      }

      if (!clazz.equals(type)) {
        continue;
      }

      if (assignment.getTarget() != null) {
        resolvedAssignments.add(assignment.getTarget().asPrismObject());
        continue;
      }

      Task task = taskManager.createTaskInstance();
      try {
        PrismObject<O> obj = model.getObject(type, oid, null, task, task.getResult());
        resolvedAssignments.add(obj);
      } catch (ObjectNotFoundException
          | SchemaException
          | SecurityViolationException
          | CommunicationException
          | ConfigurationException e) {
        LOGGER.error("Could not get object with oid " + oid + ". Reason: " + e.getMessage());
      }
    }

    return resolvedAssignments;
  }
예제 #17
0
  private AccountCallableResult<List<SimpleAccountDto>> loadAccounts() throws Exception {
    LOGGER.debug("Loading accounts.");

    AccountCallableResult callableResult = new AccountCallableResult();
    List<SimpleAccountDto> list = new ArrayList<SimpleAccountDto>();
    callableResult.setValue(list);
    PrismObject<UserType> user = principalModel.getObject();
    if (user == null) {
      return callableResult;
    }

    Task task = createSimpleTask(OPERATION_LOAD_ACCOUNTS);
    OperationResult result = task.getResult();
    callableResult.setResult(result);
    Collection<SelectorOptions<GetOperationOptions>> options =
        SelectorOptions.createCollection(
            ShadowType.F_RESOURCE, GetOperationOptions.createResolve());

    List<ObjectReferenceType> references = user.asObjectable().getLinkRef();
    for (ObjectReferenceType reference : references) {
      PrismObject<ShadowType> account =
          WebModelUtils.loadObject(
              ShadowType.class, reference.getOid(), options, this, task, result);
      if (account == null) {
        continue;
      }

      ShadowType accountType = account.asObjectable();

      OperationResultType fetchResult = accountType.getFetchResult();

      if (fetchResult != null) {
        callableResult.getFetchResults().add(OperationResult.createOperationResult(fetchResult));
      }

      ResourceType resource = accountType.getResource();
      String resourceName = WebMiscUtil.getName(resource);
      list.add(
          new SimpleAccountDto(
              WebMiscUtil.getOrigStringFromPoly(accountType.getName()), resourceName));
    }
    result.recordSuccessIfUnknown();
    result.recomputeStatus();

    LOGGER.debug("Finished accounts loading.");

    return callableResult;
  }
예제 #18
0
  public UserType getShadowOwner(String shadowOid) {
    Task task = taskManager.createTaskInstance();
    try {
      PrismObject<UserType> owner = model.findShadowOwner(shadowOid, task, task.getResult());
      return owner.asObjectable();
    } catch (ObjectNotFoundException
        | SecurityViolationException
        | SchemaException
        | ConfigurationException e) {
      // TODO Auto-generated catch block
      LOGGER.error(
          "Could not find owner for shadow with oid " + shadowOid + ". Reason: " + e.getMessage());
    }

    return null;
  }
예제 #19
0
  @Test
  public void test010TestResourceBroken() throws Exception {
    TestUtil.displayTestTile(this, "test010TestResourceBroken");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test010TestResourceBroken");
    OperationResult result = task.getResult();

    // WHEN
    OperationResult testResult = modelService.testResource(RESOURCE_CSVFILE_BROKEN_OID, task);

    // THEN
    display("testResource result", testResult);
    TestUtil.assertSuccess("testResource result", testResult);
  }
예제 #20
0
  @Test
  public void test210TestResourceNotFound() throws Exception {
    TestUtil.displayTestTile(this, "test210TestResourceNotFound");

    // GIVEN
    Task task =
        taskManager.createTaskInstance(
            TestModelServiceContract.class.getName() + ".test210TestResourceNotFound");
    OperationResult result = task.getResult();

    // WHEN
    OperationResult testResult = modelService.testResource(RESOURCE_CSVFILE_NOTFOUND_OID, task);

    // THEN
    display("testResource result", testResult);
    TestUtil.assertFailure("testResource result", testResult);
  }
예제 #21
0
  @Test
  public void test380DisableJackInBackgroundSimple() throws Exception {
    final String TEST_NAME = "test380DisableJackInBackgroundSimple";
    TestUtil.displayTestTile(this, TEST_NAME);

    // GIVEN
    OperationResult result = new OperationResult(DOT_CLASS + TEST_NAME);

    // WHEN
    Task task = taskManager.createTaskInstance();
    task.setOwner(getUser(USER_ADMINISTRATOR_OID));
    scriptingExpressionEvaluator.evaluateExpressionInBackground(
        UserType.COMPLEX_TYPE,
        ObjectQueryUtil.createOrigNameQuery("jack", prismContext).getFilter(),
        "disable",
        task,
        result);

    waitForTaskFinish(task.getOid(), false);
    task.refresh(result);

    // THEN
    IntegrationTestTools.display(task.getResult());
    TestUtil.assertSuccess(task.getResult());
    PrismObject<UserType> jack = getUser(USER_JACK_OID);
    IntegrationTestTools.display("jack after disable script", jack);
    assertAdministrativeStatusDisabled(jack);
  }
예제 #22
0
  @Test
  public void test221GetResourceNotFoundResolveConnector() throws Exception {
    final String TEST_NAME = "test221GetResourceNotFoundResolveConnector";
    TestUtil.displayTestTile(this, TEST_NAME);

    // GIVEN
    Task task =
        taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME);
    OperationResult result = task.getResult();

    Collection<SelectorOptions<GetOperationOptions>> options =
        SelectorOptions.createCollection(
            ResourceType.F_CONNECTOR_REF, GetOperationOptions.createResolve());

    // WHEN
    PrismObject<ResourceType> resource =
        modelService.getObject(
            ResourceType.class, RESOURCE_CSVFILE_NOTFOUND_OID, options, task, result);

    // THEN
    display("getObject resource", resource);
    result.computeStatus();
    display("getObject result", result);
    assertEquals(
        "Expected partial errror in result",
        OperationResultStatus.PARTIAL_ERROR,
        result.getStatus());

    OperationResultType fetchResult = resource.asObjectable().getFetchResult();
    display("resource.fetchResult", fetchResult);
    assertEquals(
        "Expected partial errror in fetchResult",
        OperationResultStatusType.PARTIAL_ERROR,
        fetchResult.getStatus());

    // TODO: better asserts
    assertNotNull("Null resource", resource);

    assertNotNull("Connector was not resolved", resource.asObjectable().getConnector());
  }
  // region Finalizing the processing
  @Override
  public void onProcessEnd(ProcessEvent event, Job job, OperationResult result)
      throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException {

    Task task = job.getTask();
    // we simply put model context back into parent task
    // (or if it is null, we set the task to skip model context processing)

    // it is safe to directly access the parent, because (1) it is in waiting state, (2) we are its
    // only child

    Task rootTask = task.getParentTask(result);

    SerializationSafeContainer<LensContextType> contextContainer =
        (SerializationSafeContainer<LensContextType>)
            event.getVariable(GcpProcessVariableNames.VARIABLE_MODEL_CONTEXT);
    LensContextType lensContextType = null;
    if (contextContainer != null) {
      contextContainer.setPrismContext(prismContext);
      lensContextType = contextContainer.getValue();
    }

    if (lensContextType == null) {
      LOGGER.debug(
          GcpProcessVariableNames.VARIABLE_MODEL_CONTEXT
              + " not present in process, this means we should stop processing. Task = {}",
          rootTask);
      wfTaskUtil.setSkipModelContextProcessingProperty(rootTask, true, result);
    } else {
      LOGGER.debug(
          "Putting (changed or unchanged) value of {} into the task {}",
          GcpProcessVariableNames.VARIABLE_MODEL_CONTEXT,
          rootTask);
      wfTaskUtil.storeModelContext(
          rootTask, lensContextType.asPrismContainerValue().getContainer());
    }

    rootTask.savePendingModifications(result);
    LOGGER.trace("onProcessEnd ending for task {}", task);
  }
예제 #24
0
 public <O extends ObjectType> O resolveObject(Class type, String oid) {
   Task task = taskManager.createTaskInstance();
   OperationResult parentResult = task.getResult();
   PrismObject<O> obj;
   try {
     obj =
         model.getObject(
             type,
             oid,
             SelectorOptions.createCollection(GetOperationOptions.createResolveNames()),
             task,
             parentResult);
     return obj.asObjectable();
   } catch (ObjectNotFoundException
       | SchemaException
       | SecurityViolationException
       | CommunicationException
       | ConfigurationException e) {
     // TODO Auto-generated catch block
     LOGGER.error("Could not get object with oid " + oid + ". Reason: " + e.getMessage());
   }
   return null;
 }
예제 #25
0
 <T extends ObjectType> List<T> searchObjects(Class<T> type, ObjectQuery query) {
   List<T> ret = new ArrayList();
   Task task = taskManager.createTaskInstance();
   try {
     List<PrismObject<T>> list =
         model.searchObjects(type, query, null, task, task.getResult()).getList();
     for (PrismObject<T> po : list) {
       ret.add(po.asObjectable());
     }
   } catch (SchemaException
       | ObjectNotFoundException
       | SecurityViolationException
       | CommunicationException
       | ConfigurationException e) {
     LOGGER.error(
         "Could not search objects of type: "
             + type
             + " with query "
             + query
             + ". Reason: "
             + e.getMessage());
   }
   return ret;
 }
예제 #26
0
  @Test
  public void test370AssignToJackInBackground() throws Exception {
    final String TEST_NAME = "test370AssignToJackInBackground";
    TestUtil.displayTestTile(this, TEST_NAME);

    // GIVEN
    OperationResult result = new OperationResult(DOT_CLASS + TEST_NAME);
    PrismProperty<ScriptingExpressionType> expression = parseAnyData(ASSIGN_TO_JACK_2_FILE);

    // WHEN
    Task task = taskManager.createTaskInstance();
    task.setOwner(getUser(USER_ADMINISTRATOR_OID));
    scriptingExpressionEvaluator.evaluateExpressionInBackground(
        expression.getAnyValue().getValue(), task, result);
    waitForTaskFinish(task.getOid(), false);
    task.refresh(result);

    // THEN
    IntegrationTestTools.display(task.getResult());
    TestUtil.assertSuccess(task.getResult());
    PrismObject<UserType> jack = getUser(USER_JACK_OID);
    IntegrationTestTools.display("jack after assignment creation", jack);
    assertAssignedRole(jack, "12345678-d34d-b33f-f00d-555555556677");
  }
  @Override
  public String getCaseInfoButtonTitle(
      IModel<? extends CertCaseOrDecisionDto> rowModel, PageBase page) {
    CertCaseOrDecisionDto dto = rowModel.getObject();
    AccessCertificationCaseType _case = dto.getCertCase();
    if (!(_case instanceof AccessCertificationAssignmentCaseType)) {
      return null; // should not occur, TODO treat gracefully
    }
    AccessCertificationAssignmentCaseType assignmentCase =
        (AccessCertificationAssignmentCaseType) _case;
    AssignmentType assignment = assignmentCase.getAssignment();

    List<String> infoList = new ArrayList<>();

    String assignmentOrInducement;
    if (Boolean.TRUE.equals(assignmentCase.isIsInducement())) {
      assignmentOrInducement =
          page.createStringResource("PageCert.message.textInducement").getString();
    } else {
      assignmentOrInducement =
          page.createStringResource("PageCert.message.textAssignment").getString();
    }
    String targetType = getLocalizedTypeName(_case.getTargetRef().getType(), page);
    String targetName = dto.getTargetName();
    String objectType = getLocalizedTypeName(_case.getObjectRef().getType(), page);
    String objectName = dto.getObjectName();

    infoList.add(
        page.createStringResource(
                "PageCert.message.assignment",
                assignmentOrInducement,
                emptyToDash(targetType),
                emptyToDash(targetName),
                emptyToDash(objectType),
                emptyToDash(objectName))
            .getString());

    if (StringUtils.isNotEmpty(assignment.getDescription())) {
      infoList.add(
          page.createStringResource("PageCert.message.textDescription", assignment.getDescription())
              .getString());
    }
    if (assignment.getOrder() != null) {
      infoList.add(
          page.createStringResource("PageCert.message.textOrder", assignment.getOrder())
              .getString());
    }
    if (assignment.getConstruction() != null) {
      if (assignment.getConstruction().getKind() != null) {
        infoList.add(
            page.createStringResource(
                    "PageCert.message.textKind",
                    page.createStringResource(assignment.getConstruction().getKind()).getString())
                .getString());
      }
      if (assignment.getConstruction().getIntent() != null) {
        infoList.add(
            page.createStringResource(
                    "PageCert.message.textIntent", assignment.getConstruction().getIntent())
                .getString());
      }
    }
    if (_case.getTargetRef().getRelation() != null) {
      infoList.add(
          page.createStringResource(
                  "PageCert.message.textRelation",
                  _case.getTargetRef().getRelation().getLocalPart())
              .getString());
    }
    Task task = page.createSimpleTask("dummy");
    if (assignment.getOrgRef() != null) {
      String orgName =
          WebModelServiceUtils.resolveReferenceName(
              assignment.getOrgRef(), page, task, task.getResult());
      infoList.add(page.createStringResource("PageCert.message.textOrg", orgName).getString());
    }
    if (assignment.getTenantRef() != null) {
      String tenantName =
          WebModelServiceUtils.resolveReferenceName(
              assignment.getTenantRef(), page, task, task.getResult());
      infoList.add(
          page.createStringResource("PageCert.message.textTenant", tenantName).getString());
    }

    PrismContainer<? extends Containerable> extensionContainer =
        assignment.asPrismContainerValue().findContainer(AssignmentType.F_EXTENSION);
    if (extensionContainer != null && !extensionContainer.isEmpty()) {
      List<String> extensionItemNameList = new ArrayList<>();
      for (Item extensionItem : extensionContainer.getValue().getItems()) {
        extensionItemNameList.add(extensionItem.getElementName().getLocalPart());
      }
      infoList.add(
          page.createStringResource(
                  "PageCert.message.textExtensions", StringUtils.join(extensionItemNameList, ", "))
              .getString());
    }

    if (assignment.getActivation() != null) {
      String validFrom = WebComponentUtil.formatDate(assignment.getActivation().getValidFrom());
      if (validFrom != null) {
        infoList.add(
            page.createStringResource("PageCert.message.textValidFrom", validFrom).getString());
      }
      String validTo = WebComponentUtil.formatDate(assignment.getActivation().getValidTo());
      if (validTo != null) {
        infoList.add(
            page.createStringResource("PageCert.message.textValidTo", validTo).getString());
      }
      if (assignment.getActivation().getAdministrativeStatus() != null) {
        infoList.add(
            page.createStringResource(
                    "PageCert.message.textAdministrativeState",
                    page.createStringResource(assignment.getActivation().getAdministrativeStatus())
                        .getString())
                .getString());
      }
    }

    String rv = StringUtils.join(infoList, "<br/>");
    return rv;
  }
예제 #28
0
  /**
   * Retrieves all definitions. Augments them by count of campaigns (all + open ones).
   *
   * <p>TODO query parameters, customizable sorting definitions and campaigns counts are expected to
   * be low, so we can afford to go through all of them here
   */
  public Collection<PrismObject<AccessCertificationDefinitionForReportType>>
      searchCertificationDefinitions()
          throws ConfigurationException, SchemaException, ObjectNotFoundException,
              CommunicationException, SecurityViolationException {

    Task task = taskManager.createTaskInstance();
    OperationResult result = task.getResult();
    Collection<SelectorOptions<GetOperationOptions>> options =
        SelectorOptions.createCollection(GetOperationOptions.createResolveNames());
    List<PrismObject<AccessCertificationDefinitionType>> definitions =
        model.searchObjects(AccessCertificationDefinitionType.class, null, options, task, result);
    final Map<String, PrismObject<AccessCertificationDefinitionForReportType>>
        definitionsForReportMap = new HashMap<>();
    for (PrismObject<AccessCertificationDefinitionType> definition : definitions) {
      // create subclass with the values copied from the superclass
      PrismObject<AccessCertificationDefinitionForReportType> definitionForReport =
          prismContext
              .createObjectable(AccessCertificationDefinitionForReportType.class)
              .asPrismObject();
      for (Item<?, ?> item : definition.getValue().getItems()) {
        definitionForReport.getValue().add(item.clone());
      }
      definitionsForReportMap.put(definition.getOid(), definitionForReport);
    }

    ResultHandler<AccessCertificationCampaignType> handler =
        new ResultHandler<AccessCertificationCampaignType>() {
          @Override
          public boolean handle(
              PrismObject<AccessCertificationCampaignType> campaignObject,
              OperationResult parentResult) {
            AccessCertificationCampaignType campaign = campaignObject.asObjectable();
            if (campaign.getDefinitionRef() != null) {
              String definitionOid = campaign.getDefinitionRef().getOid();
              PrismObject<AccessCertificationDefinitionForReportType> definitionObject =
                  definitionsForReportMap.get(definitionOid);
              if (definitionObject != null) {
                AccessCertificationDefinitionForReportType definition =
                    definitionObject.asObjectable();
                int campaigns = definition.getCampaigns() != null ? definition.getCampaigns() : 0;
                definition.setCampaigns(campaigns + 1);
                AccessCertificationCampaignStateType state = campaign.getState();
                if (state != AccessCertificationCampaignStateType.CREATED && state != CLOSED) {
                  int openCampaigns =
                      definition.getOpenCampaigns() != null ? definition.getOpenCampaigns() : 0;
                  definition.setOpenCampaigns(openCampaigns + 1);
                }
              }
            }
            return true;
          }
        };
    model.searchObjectsIterative(
        AccessCertificationCampaignType.class, null, handler, null, task, result);

    List<PrismObject<AccessCertificationDefinitionForReportType>> rv =
        new ArrayList<>(definitionsForReportMap.values());
    Collections.sort(
        rv,
        new Comparator<PrismObject<AccessCertificationDefinitionForReportType>>() {
          @Override
          public int compare(
              PrismObject<AccessCertificationDefinitionForReportType> o1,
              PrismObject<AccessCertificationDefinitionForReportType> o2) {
            String n1 = o1.asObjectable().getName().getOrig();
            String n2 = o2.asObjectable().getName().getOrig();
            if (n1 == null) {
              n1 = "";
            }
            return n1.compareTo(n2);
          }
        });
    for (PrismObject<AccessCertificationDefinitionForReportType> defObject : rv) {
      AccessCertificationDefinitionForReportType def = defObject.asObjectable();
      if (def.getCampaigns() == null) {
        def.setCampaigns(0);
      }
      if (def.getOpenCampaigns() == null) {
        def.setOpenCampaigns(0);
      }
    }
    return rv;
  }
예제 #29
0
  // normally this method returns an InputPanel;
  // however, for some special readonly types (like ObjectDeltaType) it will return a Panel
  private Panel createTypedInputComponent(String id) {
    final Item item = model.getObject().getItem().getItem();

    Panel panel = null;
    if (item instanceof PrismProperty) {
      final PrismProperty property = (PrismProperty) item;
      PrismPropertyDefinition definition = property.getDefinition();
      QName valueType = definition.getTypeName();

      final String baseExpression = "value.value"; // pointing to prism property real value

      ContainerWrapper containerWrapper = model.getObject().getItem().getContainer();
      if (containerWrapper != null && containerWrapper.getPath() != null) {
        if (ShadowType.F_ASSOCIATION.getLocalPart().equals(containerWrapper.getPath().toString())) {
          return new TextDetailsPanel(id, new PropertyModel<String>(model, baseExpression)) {

            @Override
            public String createAssociationTooltip() {
              return createAssociationTooltipText(property);
            }
          };
        }
      }

      // fixing MID-1230, will be improved with some kind of annotation or something like that
      // now it works only in description
      if (ObjectType.F_DESCRIPTION.equals(definition.getName())) {
        return new TextAreaPanel(id, new PropertyModel(model, baseExpression));
      }

      // the same for requester and approver comments in workflows [mederly] - this is really ugly,
      // as it is specific to each approval form
      if (AssignmentCreationApprovalFormType.F_REQUESTER_COMMENT.equals(definition.getName())
          || AssignmentCreationApprovalFormType.F_COMMENT.equals(definition.getName())) {
        return new TextAreaPanel(id, new PropertyModel(model, baseExpression));
      }

      if (ActivationType.F_ADMINISTRATIVE_STATUS.equals(definition.getName())) {
        return WebMiscUtil.createEnumPanel(
            ActivationStatusType.class,
            id,
            new PropertyModel<ActivationStatusType>(model, baseExpression),
            this);
      } else if (ActivationType.F_LOCKOUT_STATUS.equals(definition.getName())) {
        return WebMiscUtil.createEnumPanel(
            LockoutStatusType.class,
            id,
            new PropertyModel<LockoutStatusType>(model, baseExpression),
            this);
      } else {
        // nothing to do
      }

      if (DOMUtil.XSD_DATETIME.equals(valueType)) {
        panel = new DatePanel(id, new PropertyModel<XMLGregorianCalendar>(model, baseExpression));

      } else if (ProtectedStringType.COMPLEX_TYPE.equals(valueType)) {
        panel =
            new PasswordPanel(
                id,
                new PropertyModel<ProtectedStringType>(model, baseExpression),
                model.getObject().isReadonly());

      } else if (DOMUtil.XSD_BOOLEAN.equals(valueType)) {
        panel = new TriStateComboPanel(id, new PropertyModel<Boolean>(model, baseExpression));

      } else if (SchemaConstants.T_POLY_STRING_TYPE.equals(valueType)) {
        InputPanel inputPanel;
        PrismPropertyDefinition def = property.getDefinition();

        if (def.getValueEnumerationRef() != null) {
          PrismReferenceValue valueEnumerationRef = def.getValueEnumerationRef();
          String lookupTableUid = valueEnumerationRef.getOid();
          Task task = pageBase.createSimpleTask("loadLookupTable");
          OperationResult result = task.getResult();

          Collection<SelectorOptions<GetOperationOptions>> options =
              SelectorOptions.createCollection(
                  LookupTableType.F_ROW,
                  GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
          final PrismObject<LookupTableType> lookupTable =
              WebModelUtils.loadObject(
                  LookupTableType.class, lookupTableUid, options, pageBase, task, result);

          inputPanel =
              new AutoCompleteTextPanel<String>(
                  id,
                  new LookupPropertyModel<String>(
                      model, baseExpression + ".orig", lookupTable.asObjectable()),
                  String.class) {

                @Override
                public Iterator<String> getIterator(String input) {
                  return prepareAutoCompleteList(input, lookupTable).iterator();
                }
              };

        } else {

          inputPanel =
              new TextPanel<>(
                  id, new PropertyModel<String>(model, baseExpression + ".orig"), String.class);
        }

        if (ObjectType.F_NAME.equals(def.getName()) || UserType.F_FULL_NAME.equals(def.getName())) {
          inputPanel.getBaseFormComponent().setRequired(true);
        }
        panel = inputPanel;

      } else if (DOMUtil.XSD_BASE64BINARY.equals(valueType)) {
        panel =
            new UploadDownloadPanel(id, model.getObject().isReadonly()) {

              @Override
              public InputStream getStream() {
                return new ByteArrayInputStream(
                    (byte[]) ((PrismPropertyValue) model.getObject().getValue()).getValue());
                //                		return super.getStream();
              }

              @Override
              public void updateValue(byte[] file) {
                ((PrismPropertyValue) model.getObject().getValue()).setValue(file);
              }

              @Override
              public void uploadFilePerformed(AjaxRequestTarget target) {
                super.uploadFilePerformed(target);
                target.add(PrismValuePanel.this.get(ID_FEEDBACK));
              }

              @Override
              public void removeFilePerformed(AjaxRequestTarget target) {
                super.removeFilePerformed(target);
                target.add(PrismValuePanel.this.get(ID_FEEDBACK));
              }

              @Override
              public void uploadFileFailed(AjaxRequestTarget target) {
                super.uploadFileFailed(target);
                target.add(PrismValuePanel.this.get(ID_FEEDBACK));
                target.add(((PageBase) getPage()).getFeedbackPanel());
              }
            };

      } else if (ObjectDeltaType.COMPLEX_TYPE.equals(valueType)) {
        panel =
            new ModificationsPanel(
                id,
                new AbstractReadOnlyModel<DeltaDto>() {
                  @Override
                  public DeltaDto getObject() {
                    if (model.getObject() == null
                        || model.getObject().getValue() == null
                        || ((PrismPropertyValue) model.getObject().getValue()).getValue() == null) {
                      return null;
                    }
                    PrismContext prismContext = ((PageBase) getPage()).getPrismContext();
                    ObjectDeltaType objectDeltaType =
                        (ObjectDeltaType)
                            ((PrismPropertyValue) model.getObject().getValue()).getValue();
                    try {
                      ObjectDelta delta =
                          DeltaConvertor.createObjectDelta(objectDeltaType, prismContext);
                      return new DeltaDto(delta);
                    } catch (SchemaException e) {
                      throw new IllegalStateException(
                          "Couldn't convert object delta: " + objectDeltaType);
                    }
                  }
                });
      } else {
        Class type = XsdTypeMapper.getXsdToJavaMapping(valueType);
        if (type != null && type.isPrimitive()) {
          type = ClassUtils.primitiveToWrapper(type);
        }

        if (isEnum(property)) {
          return WebMiscUtil.createEnumPanel(
              definition, id, new PropertyModel<>(model, baseExpression), this);
        }
        //                  // default QName validation is a bit weird, so let's treat QNames as
        // strings [TODO finish this - at the parsing side]
        //                  if (type == QName.class) {
        //                      type = String.class;
        //                  }

        PrismPropertyDefinition def = property.getDefinition();

        if (def.getValueEnumerationRef() != null) {
          PrismReferenceValue valueEnumerationRef = def.getValueEnumerationRef();
          String lookupTableUid = valueEnumerationRef.getOid();
          Task task = pageBase.createSimpleTask("loadLookupTable");
          OperationResult result = task.getResult();

          Collection<SelectorOptions<GetOperationOptions>> options =
              SelectorOptions.createCollection(
                  LookupTableType.F_ROW,
                  GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
          final PrismObject<LookupTableType> lookupTable =
              WebModelUtils.loadObject(
                  LookupTableType.class, lookupTableUid, options, pageBase, task, result);

          panel =
              new AutoCompleteTextPanel<String>(
                  id,
                  new LookupPropertyModel<String>(
                      model,
                      baseExpression,
                      lookupTable == null ? null : lookupTable.asObjectable()),
                  type) {

                @Override
                public Iterator<String> getIterator(String input) {
                  return prepareAutoCompleteList(input, lookupTable).iterator();
                }

                @Override
                public void checkInputValue(
                    AutoCompleteTextField input,
                    AjaxRequestTarget target,
                    LookupPropertyModel model) {
                  Iterator<String> lookupTableValuesIterator =
                      prepareAutoCompleteList("", lookupTable).iterator();

                  String value = input.getInput();
                  boolean isValueExist = false;
                  if (value != null) {
                    if (value.trim().equals("")) {
                      isValueExist = true;
                    } else {
                      while (lookupTableValuesIterator.hasNext()) {
                        String lookupTableValue = lookupTableValuesIterator.next();
                        if (value.trim().equals(lookupTableValue)) {
                          isValueExist = true;
                          break;
                        }
                      }
                    }
                  }
                  if (isValueExist) {
                    input.setModelValue(new String[] {value});
                    target.add(PrismValuePanel.this.get(ID_FEEDBACK));
                  } else {
                    input.error(
                        "Entered value doesn't match any of available values and will not be saved.");
                    target.add(PrismValuePanel.this.get(ID_FEEDBACK));
                  }
                }
              };

        } else {
          panel = new TextPanel<>(id, new PropertyModel<String>(model, baseExpression), type);
        }
      }
    } else if (item instanceof PrismReference) {
      //        	((PrismReferenceDefinition) item.getDefinition()).
      Class typeFromName = null;
      PrismContext prismContext = item.getPrismContext();
      if (prismContext == null) {
        prismContext = pageBase.getPrismContext();
      }
      QName targetTypeName = ((PrismReferenceDefinition) item.getDefinition()).getTargetTypeName();
      if (targetTypeName != null && prismContext != null) {
        typeFromName = prismContext.getSchemaRegistry().determineCompileTimeClass(targetTypeName);
      }
      final Class typeClass =
          typeFromName != null
              ? typeFromName
              : (item.getDefinition().getTypeClassIfKnown() != null
                  ? item.getDefinition().getTypeClassIfKnown()
                  : FocusType.class);
      panel =
          new ValueChoosePanel(
              id, new PropertyModel<>(model, "value"), item.getValues(), false, typeClass);
    }

    return panel;
  }
예제 #30
0
  private WorkItemDto loadWorkItemDtoIfNecessary() {
    if (workItemDtoModel.isLoaded()) {
      return workItemDtoModel.getObject();
    }
    Task task = createSimpleTask(OPERATION_LOAD_WORK_ITEM);
    OperationResult result = task.getResult();
    WorkItemDto workItemDto = null;
    try {
      final ObjectQuery query =
          QueryBuilder.queryFor(WorkItemType.class, getPrismContext())
              .item(F_WORK_ITEM_ID)
              .eq(taskId)
              .build();
      final Collection<SelectorOptions<GetOperationOptions>> options =
          resolveItemsNamed(F_ASSIGNEE_REF);
      List<WorkItemType> workItems =
          getModelService().searchContainers(WorkItemType.class, query, options, task, result);
      if (workItems.size() > 1) {
        throw new SystemException("More than one work item with ID of " + taskId);
      } else if (workItems.size() == 0) {
        throw new SystemException("No work item with ID of " + taskId);
      }
      final WorkItemType workItem = workItems.get(0);

      final String taskOid = workItem.getTaskRef() != null ? workItem.getTaskRef().getOid() : null;
      TaskType taskType = null;
      List<TaskType> relatedTasks = new ArrayList<>();
      if (taskOid != null) {
        final Collection<SelectorOptions<GetOperationOptions>> getTaskOptions =
            resolveItemsNamed(new ItemPath(F_WORKFLOW_CONTEXT, F_REQUESTER_REF));
        getTaskOptions.addAll(retrieveItemsNamed(new ItemPath(F_WORKFLOW_CONTEXT, F_WORK_ITEM)));
        try {
          taskType =
              getModelService()
                  .getObject(TaskType.class, taskOid, getTaskOptions, task, result)
                  .asObjectable();
        } catch (AuthorizationException e) {
          LoggingUtils.logExceptionOnDebugLevel(
              LOGGER, "Access to the task {} was denied", e, taskOid);
        }

        if (taskType != null && taskType.getParent() != null) {
          final ObjectQuery relatedTasksQuery =
              QueryBuilder.queryFor(TaskType.class, getPrismContext())
                  .item(F_PARENT)
                  .eq(taskType.getParent())
                  .build();
          List<PrismObject<TaskType>> relatedTaskObjects =
              getModelService()
                  .searchObjects(TaskType.class, relatedTasksQuery, null, task, result);
          for (PrismObject<TaskType> relatedObject : relatedTaskObjects) {
            relatedTasks.add(relatedObject.asObjectable());
          }
        }
      }
      workItemDto = new WorkItemDto(workItem, taskType, relatedTasks);
      workItemDto.prepareDeltaVisualization(
          "pageWorkItem.delta", getPrismContext(), getModelInteractionService(), task, result);
      result.recordSuccessIfUnknown();
    } catch (CommonException | RuntimeException ex) {
      result.recordFatalError("Couldn't get work item.", ex);
      LoggingUtils.logUnexpectedException(LOGGER, "Couldn't get work item.", ex);
    }
    showResult(result, false);
    if (!result.isSuccess()) {
      throw getRestartResponseException(PageDashboard.class);
    }
    return workItemDto;
  }