Exemple #1
0
  @Test
  public void testUserSimplePropertyDiffReplace() throws Exception {
    System.out.println("\n\n===[ testUserSimplePropertyDiffReplace ]===\n");
    // GIVEN
    PrismObjectDefinition<UserType> userDef = getUserTypeDefinition();

    PrismObject<UserType> user1 = userDef.instantiate();
    user1.setOid(USER_JACK_OID);
    user1.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("test name"));

    PrismObject<UserType> user2 = userDef.instantiate();
    user2.setOid(USER_JACK_OID);
    user2.setPropertyRealValue(UserType.F_NAME, PrismTestUtil.createPolyString("other name"));

    // WHEN
    ObjectDelta<UserType> delta = user1.diff(user2);

    // THEN
    assertNotNull(delta);
    System.out.println(delta.debugDump());
    assertEquals("Unexpected number of midifications", 1, delta.getModifications().size());
    PrismAsserts.assertPropertyReplace(
        delta, UserType.F_NAME, PrismTestUtil.createPolyString("other name"));
    assertEquals("Wrong OID", USER_JACK_OID, delta.getOid());
    delta.checkConsistence();
  }
  /**
   * 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);
  }
Exemple #3
0
  @Test
  public void testUserSimpleDiffMultiAdd() throws Exception {
    System.out.println("\n\n===[ testUserSimpleDiffMulti ]===\n");

    // GIVEN
    PrismObjectDefinition<UserType> userDef = getUserTypeDefinition();

    PrismObject<UserType> user1 = userDef.instantiate();
    user1.setOid(USER_JACK_OID);
    PrismProperty<String> anamesProp1 = user1.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES);
    anamesProp1.addRealValue("foo");
    anamesProp1.addRealValue("bar");

    PrismObject<UserType> user2 = userDef.instantiate();
    user2.setOid(USER_JACK_OID);
    PrismProperty<String> anamesProp2 = user2.findOrCreateProperty(UserType.F_ADDITIONAL_NAMES);
    anamesProp2.addRealValue("foo");
    anamesProp2.addRealValue("bar");
    anamesProp2.addRealValue("baz");

    // WHEN
    ObjectDelta<UserType> delta = user1.diff(user2);

    // THEN
    assertNotNull(delta);
    System.out.println(delta.debugDump());
    assertEquals("Unexpected number of midifications", 1, delta.getModifications().size());
    PrismAsserts.assertPropertyAdd(delta, UserType.F_ADDITIONAL_NAMES, "baz");
    assertEquals("Wrong OID", USER_JACK_OID, delta.getOid());
    delta.checkConsistence();
  }
Exemple #4
0
 public void normalize() throws SchemaException {
   ObjectDelta delta = getObjectDelta();
   if (ChangeType.ADD.equals(delta.getChangeType())) {
     object = delta.getObjectToAdd();
   } else {
     delta.applyTo(object);
   }
 }
  private <F extends FocusType> boolean wasExecuted(
      ObjectDelta<UserType> userDelta, LensFocusContext<F> focusContext) {

    for (LensObjectDeltaOperation<F> executedDeltaOperation : focusContext.getExecutedDeltas()) {
      ObjectDelta<F> executedDelta = executedDeltaOperation.getObjectDelta();
      if (!executedDelta.isAdd()) {
        continue;
      } else if (executedDelta.getObjectToAdd() != null
          && executedDelta.getObjectTypeClass().equals(UserType.class)) {
        return true;
      }
    }

    return false;
  }
  private void updateAccountStatusPerformed(
      AjaxRequestTarget target, AccountContentDto dto, boolean enabled) {
    List<AccountContentDto> accounts = isAnythingSelected(target, dto);
    OperationResult result = new OperationResult(OPERATION_ADJUST_ACCOUNT_STATUS);

    if (accounts.isEmpty()) {
      return;
    }

    ActivationStatusType status =
        enabled ? ActivationStatusType.ENABLED : ActivationStatusType.DISABLED;

    for (AccountContentDto acc : accounts) {

      ObjectDelta delta =
          ObjectDelta.createModificationReplaceProperty(
              ShadowType.class,
              acc.getAccountOid(),
              new ItemPath(ShadowType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS),
              getPrismContext(),
              status);

      try {
        Task task = createSimpleTask(OPERATION_ADJUST_ACCOUNT_STATUS);
        getModelService()
            .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
      } catch (Exception e) {
        LoggingUtils.logException(LOGGER, "Couldn't enable/disable account(s) on resource", e);
        result.recordPartialError("Couldn't enable/disable account(s) on resource", e);
      }
    }
    result.recomputeStatus();
    showResult(result);
    target.add(getFeedbackPanel());
  }
  private void deleteDefinitionPerformed(
      AjaxRequestTarget target, AccessCertificationDefinitionType definition) {
    OperationResult result = new OperationResult(OPERATION_DELETE_DEFINITION);
    try {
      Task task = createSimpleTask(OPERATION_DELETE_DEFINITION);
      ObjectDelta<AccessCertificationDefinitionType> delta =
          ObjectDelta.createDeleteDelta(
              AccessCertificationDefinitionType.class, definition.getOid(), getPrismContext());
      getModelService()
          .executeChanges(WebComponentUtil.createDeltaCollection(delta), null, task, result);
    } catch (Exception ex) {
      result.recordPartialError("Couldn't delete campaign definition.", ex);
      LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete campaign definition", ex);
    }

    result.computeStatusIfUnknown();
    if (result.isSuccess()) {
      result.recordStatus(
          OperationResultStatus.SUCCESS, "The definition has been successfully deleted.");
    }

    getDefinitionsTable().clearCache();

    showResult(result);
    target.add(getFeedbackPanel(), getDefinitionsTable());
  }
  @Test(enabled = true)
  public void test100SerializeContext() throws Exception {

    OperationResult result = new OperationResult("test100SerializeContext");

    LensContext<UserType> context =
        new LensContext<UserType>(UserType.class, prismContext, provisioningService);
    PrismObject<UserType> bill = prismContext.parseObject(USER_BARBOSSA_FILE);
    CryptoUtil.encryptValues(protector, bill);
    ObjectDelta<UserType> userDelta = ObjectDelta.createAddDelta(bill);
    LensFocusContext<UserType> focusContext = context.getOrCreateFocusContext();
    focusContext.setPrimaryDelta(userDelta);

    LensContextType contextType = context.toLensContextType();
    JaxbValueContainer<LensContextType> container =
        new JaxbValueContainer<LensContextType>(contextType, prismContext);
    container.clearActualValue();
    System.out.println("XML value = " + container.getXmlValue());
    LensContextType contextTypeRetrieved = container.getValue();
    LensContext<UserType> contextRetrieved =
        LensContext.fromLensContextType(
            contextTypeRetrieved, prismContext, provisioningService, result);

    assertEquals(
        "Context after serialization/deserialization does not match context before it (object to add is changed)",
        context.getFocusContext().getPrimaryDelta().getObjectToAdd(),
        contextRetrieved.getFocusContext().getPrimaryDelta().getObjectToAdd());
  }
  /* (non-Javadoc)
   * @see com.evolveum.midpoint.model.sync.Action#handle(com.evolveum.midpoint.model.lens.LensContext, com.evolveum.midpoint.model.sync.SynchronizationSituation, java.util.Map, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult)
   */
  @Override
  public <F extends FocusType> void handle(
      LensContext<F> context,
      SynchronizationSituation<F> situation,
      Map<QName, Object> parameters,
      Task task,
      OperationResult parentResult) {
    ActivationStatusType desiredStatus = ActivationStatusType.DISABLED;

    LensProjectionContext projectionContext = context.getProjectionContextsIterator().next();
    PrismObject<ShadowType> objectCurrent = projectionContext.getObjectCurrent();
    if (objectCurrent != null) {
      PrismProperty<Object> administrativeStatusProp =
          objectCurrent.findProperty(SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS);
      if (administrativeStatusProp != null) {
        if (desiredStatus.equals(administrativeStatusProp.getRealValue())) {
          // Desired status already set, nothing to do
          return;
        }
      }
    }
    ObjectDelta<ShadowType> activationDelta =
        ObjectDelta.createModificationReplaceProperty(
            ShadowType.class,
            projectionContext.getOid(),
            SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS,
            getPrismContext(),
            desiredStatus);
    projectionContext.setPrimaryDelta(activationDelta);
  }
 private <F extends FocusType> boolean willResetIterationCounter(LensFocusContext<F> focusContext)
     throws SchemaException {
   ObjectDelta<F> focusDelta = focusContext.getDelta();
   if (focusDelta == null) {
     return false;
   }
   if (focusContext.isAdd() || focusContext.isDelete()) {
     return false;
   }
   if (focusDelta.findPropertyDelta(FocusType.F_ITERATION) != null) {
     // there was a reset already in previous projector runs
     return false;
   }
   // Check for rename
   PropertyDelta<Object> nameDelta = focusDelta.findPropertyDelta(new ItemPath(FocusType.F_NAME));
   return nameDelta != null;
 }
  <F extends ObjectType> void processPasswordPolicy(
      LensProjectionContext projectionContext,
      LensContext<F> context,
      Task task,
      OperationResult result)
      throws SchemaException, PolicyViolationException {

    ObjectDelta accountDelta = projectionContext.getDelta();

    if (accountDelta == null) {
      LOGGER.trace("Skipping processing password policies. Shadow delta not specified.");
      return;
    }

    if (ChangeType.DELETE == accountDelta.getChangeType()) {
      return;
    }

    PrismObject<ShadowType> accountShadow = null;
    PrismProperty<PasswordType> password = null;
    if (ChangeType.ADD == accountDelta.getChangeType()) {
      accountShadow = accountDelta.getObjectToAdd();
      if (accountShadow != null) {
        password = accountShadow.findProperty(SchemaConstants.PATH_PASSWORD_VALUE);
      }
    }
    if (ChangeType.MODIFY == accountDelta.getChangeType() || password == null) {
      PropertyDelta<PasswordType> passwordValueDelta = null;
      if (accountDelta != null) {
        passwordValueDelta = accountDelta.findPropertyDelta(SchemaConstants.PATH_PASSWORD_VALUE);
        // Modification sanity check
        if (accountDelta.getChangeType() == ChangeType.MODIFY
            && passwordValueDelta != null
            && (passwordValueDelta.isAdd() || passwordValueDelta.isDelete())) {
          throw new SchemaException(
              "Shadow password value cannot be added or deleted, it can only be replaced");
        }
        if (passwordValueDelta == null) {
          LOGGER.trace(
              "Skipping processing password policies. Shadow delta does not contain password change.");
          return;
        }
        password = (PrismProperty<PasswordType>) passwordValueDelta.getItemNewMatchingPath(null);
      }
    }

    //		PrismProperty<PasswordType> password = getPassword(projectionContext);
    ValuePolicyType passwordPolicy = null;
    if (isCheckOrgPolicy(context)) {
      passwordPolicy = determineValuePolicy(context.getFocusContext().getObjectAny(), task, result);
      context.getFocusContext().setOrgPasswordPolicy(passwordPolicy);
    } else {
      passwordPolicy = projectionContext.getEffectivePasswordPolicy();
    }

    processPasswordPolicy(passwordPolicy, password, result);
  }
Exemple #12
0
 public void revive(PrismContext prismContext) throws SchemaException {
   if (object != null) {
     object.revive(prismContext);
   }
   if (oldDelta != null) {
     oldDelta.revive(prismContext);
   }
   if (containers != null) {
     for (ContainerWrapper containerWrapper : containers) {
       containerWrapper.revive(prismContext);
     }
   }
 }
  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());
    }
  }
  @Test
  public void testParseTaskRoundtrip() throws Exception {
    System.out.println("===[ testParseTaskRoundtrip ]===");

    // GIVEN
    PrismContext prismContext = PrismTestUtil.getPrismContext();

    PrismObject<TaskType> task = prismContext.parseObject(TASK_FILE);

    System.out.println("Parsed task:");
    System.out.println(task.debugDump());

    assertTask(task);

    // SERIALIZE

    String serializedTask = prismContext.serializeObjectToString(task, PrismContext.LANG_XML);

    System.out.println("serialized task:");
    System.out.println(serializedTask);

    // RE-PARSE

    PrismObject<TaskType> reparsedTask = prismContext.parseObject(serializedTask);

    System.out.println("Re-parsed task:");
    System.out.println(reparsedTask.debugDump());

    // Cannot assert here. It will cause parsing of some of the raw values and diff will fail
    assertTask(reparsedTask);

    ObjectDelta<TaskType> objectDelta = task.diff(reparsedTask);
    System.out.println("Delta:");
    System.out.println(objectDelta.debugDump());
    assertTrue("Delta is not empty", objectDelta.isEmpty());

    PrismAsserts.assertEquivalent("Task re-parsed equivalence", task, reparsedTask);
  }
  private void deleteConfirmedPerformed(AjaxRequestTarget target) {
    List<AccountContentDto> selected = new ArrayList<AccountContentDto>();

    if (singleDelete != null) {
      selected.add(singleDelete);
    } else {
      selected = isAnythingSelected(target, null);
    }

    OperationResult result = new OperationResult(OPERATION_DELETE_ACCOUNT_FROM_RESOURCE);

    for (AccountContentDto acc : selected) {
      String accOid = acc.getAccountOid();

      try {
        Task task = createSimpleTask(OPERATION_DELETE_ACCOUNT_FROM_RESOURCE);

        ObjectDelta delta =
            ObjectDelta.createDeleteDelta(ShadowType.class, accOid, getPrismContext());
        getModelService()
            .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);

      } catch (Exception e) {
        result.recordPartialError("Couldn't delete account from resource.", e);
        LoggingUtils.logException(LOGGER, "Couldn't delete account from resource", e);
      }
    }

    if (result.isUnknown()) {
      result.recomputeStatus("Error occurred during resource account deletion.");
    }

    if (result.isSuccess()) {
      result.recordStatus(
          OperationResultStatus.SUCCESS, "Selected accounts have been successfully deleted.");
    }

    AccountContentDataProvider provider =
        (AccountContentDataProvider) getTable().getDataTable().getDataProvider();
    provider.clearCache();

    TablePanel table = getTable();
    target.add(table);
    showResult(result);
    target.add(getFeedbackPanel());
  }
  private ValuePolicyType determineValuePolicy(
      ObjectDelta<UserType> userDelta, Task task, OperationResult result) throws SchemaException {
    ReferenceDelta orgDelta = userDelta.findReferenceModification(UserType.F_PARENT_ORG_REF);
    ValuePolicyType passwordPolicy = null;
    LOGGER.trace("Determining password policy from org delta.");
    if (orgDelta != null) {
      PrismReferenceValue orgRefValue = orgDelta.getAnyValue();

      try {
        PrismObject<OrgType> org =
            resolver.resolve(orgRefValue, "resolving parent org ref", null, null, result);
        OrgType orgType = org.asObjectable();
        ObjectReferenceType ref = orgType.getPasswordPolicyRef();
        if (ref != null) {
          LOGGER.trace("Org {} has specified password policy.", orgType);
          passwordPolicy =
              resolver.resolve(
                  ref,
                  ValuePolicyType.class,
                  null,
                  "resolving password policy for organization",
                  task,
                  result);
          LOGGER.trace("Resolved password policy {}", passwordPolicy);
        }

        if (passwordPolicy == null) {
          passwordPolicy = determineValuePolicy(org, task, result);
        }

      } catch (ObjectNotFoundException e) {
        throw new IllegalStateException(e);
      }
    }

    return passwordPolicy;
  }
  private void ownerChangePerformed(AjaxRequestTarget target, UserType user) {
    AccountOwnerChangeDto dto = ownerChangeModel.getObject();
    OperationResult result = new OperationResult(OPERATION_CHANGE_OWNER);
    try {
      Task task = createSimpleTask(OPERATION_CHANGE_OWNER);
      if (StringUtils.isNotEmpty(dto.getOldOwnerOid())) {
        ObjectDelta delta = new ObjectDelta(UserType.class, ChangeType.MODIFY, getPrismContext());
        delta.setOid(dto.getOldOwnerOid());
        PrismReferenceValue refValue = new PrismReferenceValue(dto.getAccountOid());
        refValue.setTargetType(dto.getAccountType());
        delta.addModification(
            ReferenceDelta.createModificationDelete(
                UserType.class, UserType.F_LINK_REF, getPrismContext(), refValue));
        getModelService()
            .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
      }

      if (user != null) {
        ObjectDelta delta = new ObjectDelta(UserType.class, ChangeType.MODIFY, getPrismContext());
        delta.setOid(user.getOid());
        PrismReferenceValue refValue = new PrismReferenceValue(dto.getAccountOid());
        refValue.setTargetType(dto.getAccountType());
        delta.addModification(
            ReferenceDelta.createModificationAdd(
                UserType.class, UserType.F_LINK_REF, getPrismContext(), refValue));

        getModelService()
            .executeChanges(WebMiscUtil.createDeltaCollection(delta), null, task, result);
      }
      result.recomputeStatus();
    } catch (Exception ex) {
      result.recordFatalError("Couldn't submit user.", ex);
      LoggingUtils.logException(LOGGER, "Couldn't submit user", ex);
    }

    showResult(result);
    target.add(getFeedbackPanel());
  }
  <F extends FocusType> void processPasswordPolicy(
      LensFocusContext<F> focusContext, LensContext<F> context, Task task, OperationResult result)
      throws PolicyViolationException, SchemaException {

    if (!UserType.class.isAssignableFrom(focusContext.getObjectTypeClass())) {
      LOGGER.trace("Skipping processing password policies because focus is not user");
      return;
    }

    //		PrismProperty<PasswordType> password = getPassword(focusContext);
    ObjectDelta userDelta = focusContext.getDelta();

    if (userDelta == null) {
      LOGGER.trace("Skipping processing password policies. User delta not specified.");
      return;
    }

    if (userDelta.isDelete()) {
      LOGGER.trace("Skipping processing password policies. User will be deleted.");
      return;
    }

    PrismProperty<PasswordType> password = null;
    PrismObject<F> user;
    if (ChangeType.ADD == userDelta.getChangeType()) {
      user = focusContext.getDelta().getObjectToAdd();
      if (user != null) {
        password = user.findProperty(SchemaConstants.PATH_PASSWORD_VALUE);
      }
      if (password == null) {
        if (wasExecuted(userDelta, focusContext)) {
          LOGGER.trace(
              "Skipping processing password policies. User addition was already executed.");
          return;
        }
      }
    } else if (ChangeType.MODIFY == userDelta.getChangeType()) {
      PropertyDelta<PasswordType> passwordValueDelta;
      if (userDelta != null) {
        passwordValueDelta = userDelta.findPropertyDelta(SchemaConstants.PATH_PASSWORD_VALUE);
        if (passwordValueDelta == null) {
          LOGGER.trace(
              "Skipping processing password policies. User delta does not contain password change.");
          return;
        }
        if (userDelta.getChangeType() == ChangeType.MODIFY && passwordValueDelta != null) {
          if (passwordValueDelta.isAdd()) {
            password =
                (PrismProperty<PasswordType>) passwordValueDelta.getItemNewMatchingPath(null);
          } else if (passwordValueDelta.isDelete()) {
            password = null;
          } else {
            password =
                (PrismProperty<PasswordType>) passwordValueDelta.getItemNewMatchingPath(null);
          }
        } else {
          password = (PrismProperty<PasswordType>) passwordValueDelta.getItemNewMatchingPath(null);
        }
      }
    }

    ValuePolicyType passwordPolicy;
    if (focusContext.getOrgPasswordPolicy() == null) {
      passwordPolicy =
          determineValuePolicy(userDelta, focusContext.getObjectAny(), context, task, result);
      focusContext.setOrgPasswordPolicy(passwordPolicy);
    } else {
      passwordPolicy = focusContext.getOrgPasswordPolicy();
    }

    processPasswordPolicy(passwordPolicy, password, result);
  }
  @Test(enabled = true)
  public void test020FormatUserModification() throws Exception {

    // GIVEN

    ObjectDelta<UserType> delta = parseDelta(USER_JACK_MODIFICATION_FILE);
    PrismObject<UserType> jack = PrismTestUtil.parseObject(new File(USER_JACK_FILE));

    System.out.println(delta.debugDump());
    // WHEN

    String deltaFormattedHideNone =
        textFormatter.formatObjectModificationDelta(delta, null, true, jack, null);
    System.out.println("no hidden paths + show operational attributes: " + deltaFormattedHideNone);

    String deltaFormattedHideOper =
        textFormatter.formatObjectModificationDelta(delta, null, false, jack, null);
    System.out.println("no hidden paths + hide operational attributes: " + deltaFormattedHideOper);

    String deltaFormattedHideAux =
        textFormatter.formatObjectModificationDelta(delta, auxiliaryPaths, true, jack, null);
    System.out.println(
        "hide auxiliary paths + show operational attributes: " + deltaFormattedHideAux);

    String deltaFormattedHideAuxAndOper =
        textFormatter.formatObjectModificationDelta(delta, auxiliaryPaths, false, jack, null);
    System.out.println(
        "hide auxiliary paths + hide operational attributes: " + deltaFormattedHideAuxAndOper);

    // THEN

    checkNotes(deltaFormattedHideAux);
    checkNotes(deltaFormattedHideAuxAndOper);
    checkNotes(deltaFormattedHideNone);
    checkNotes(deltaFormattedHideOper);

    assertTrue(
        "hidden operational attribute when it should be shown ('hide none')",
        deltaFormattedHideNone.contains("createTimestamp:"));
    assertTrue(
        "hidden auxiliary attribute (family name) when it should be shown ('hide none')",
        deltaFormattedHideNone.contains("SPARROW"));
    assertTrue(
        "hidden password change when it should be shown ('hide none')",
        deltaFormattedHideNone.contains("(protected string)"));
    assertTrue(
        "hidden standard attribute when it should be shown ('hide none')",
        deltaFormattedHideNone.contains("BLACK PEARL"));

    assertTrue(
        "shown operational attribute when it should be hidden ('hide oper')",
        !deltaFormattedHideOper.contains("createTimestamp:"));
    assertTrue(
        "hidden auxiliary attribute (family name) when it should be shown ('hide oper')",
        deltaFormattedHideOper.contains("SPARROW"));
    assertTrue(
        "hidden password change when it should be shown ('hide oper')",
        deltaFormattedHideOper.contains("(protected string)"));
    assertTrue(
        "hidden standard attribute when it should be shown ('hide oper')",
        deltaFormattedHideOper.contains("BLACK PEARL"));

    assertTrue(
        "shown auxiliary attribute (metadata) when it should be hidden ('hide aux')",
        !deltaFormattedHideAux.contains("createTimestamp:"));
    assertTrue(
        "shown auxiliary attribute (family name) when it should be hidden ('hide aux')",
        !deltaFormattedHideAux.contains("SPARROW"));
    assertTrue(
        "hidden standard attribute when it should be shown ('hide aux')",
        deltaFormattedHideAux.contains("BLACK PEARL"));

    assertTrue(
        "shown operational attribute when it should be hidden ('hide aux and oper')",
        !deltaFormattedHideAuxAndOper.contains("createTimestamp:"));
    assertTrue(
        "shown auxiliary attribute (family name) when it should be hidden ('hide aux and oper')",
        !deltaFormattedHideAuxAndOper.contains("SPARROW"));
    assertTrue(
        "hidden standard attribute when it should be shown ('hide aux and oper')",
        deltaFormattedHideAuxAndOper.contains("BLACK PEARL"));
  }
  private void updateQuestions(String useroid, AjaxRequestTarget target) {

    Task task = createSimpleTask(OPERATION_SAVE_QUESTIONS);
    OperationResult result = new OperationResult(OPERATION_SAVE_QUESTIONS);
    SchemaRegistry registry = getPrismContext().getSchemaRegistry();
    SecurityQuestionAnswerType[] answerTypeList = new SecurityQuestionAnswerType[questionNumber];

    try {
      int listnum = 0;
      for (Iterator iterator = pqPanels.iterator(); iterator.hasNext(); ) {
        MyPasswordQuestionsPanel type = (MyPasswordQuestionsPanel) iterator.next();

        SecurityQuestionAnswerType answerType = new SecurityQuestionAnswerType();
        ProtectedStringType answer = new ProtectedStringType();

        answer.setClearValue(
            ((TextField<String>) type.get(MyPasswordQuestionsPanel.F_ANSWER)).getModelObject());
        answerType.setQuestionAnswer(answer);

        // used apache's unescapeHtml method for special chars like \'
        String results =
            StringEscapeUtils.unescapeHtml(
                (type.get(MyPasswordQuestionsPanel.F_QUESTION)).getDefaultModelObjectAsString());
        answerType.setQuestionIdentifier(getQuestionIdentifierFromQuestion(results));
        answerTypeList[listnum] = answerType;
        listnum++;
      }

      // if(answerTypeList.length !=)

      // fill in answerType data here
      ItemPath path =
          new ItemPath(
              UserType.F_CREDENTIALS,
              CredentialsType.F_SECURITY_QUESTIONS,
              SecurityQuestionsCredentialsType.F_QUESTION_ANSWER);
      ObjectDelta<UserType> objectDelta =
          ObjectDelta.createModificationReplaceContainer(
              UserType.class, useroid, path, getPrismContext(), answerTypeList);

      Collection<ObjectDelta<? extends ObjectType>> deltas =
          MiscSchemaUtil.createCollection(objectDelta);
      getModelService().executeChanges(deltas, null, task, result);

      /*
      	System.out.println("getModel");
      	 Collection<ObjectDelta<? extends ObjectType>> deltas = new ArrayList<ObjectDelta<? extends ObjectType>>();
      	PasswordQuestionsDto dto = new PasswordQuestionsDto();
      	 PrismObjectDefinition objDef =registry.findObjectDefinitionByCompileTimeClass(UserType.class);
      	 Class<? extends ObjectType> type =  UserType.class;

      	 final ItemPath valuePath = new ItemPath(SchemaConstantsGenerated.C_CREDENTIALS,
                       CredentialsType.F_SECURITY_QUESTIONS, SecurityQuestionsCredentialsType.F_QUESTION_ANSWER);
      	 SecurityQuestionAnswerType secQuesAnsType= new SecurityQuestionAnswerType();
      	 ProtectedStringType protStrType= new ProtectedStringType();
      	 protStrType.setClearValue("deneme");
      	 secQuesAnsType.setQuestionAnswer(protStrType);
      	 dto.setSecurityAnswers(new ArrayList<SecurityQuestionAnswerType>());
      	 dto.getSecurityAnswers().add(secQuesAnsType);

      	PropertyDelta delta = PropertyDelta.createModificationReplaceProperty(valuePath, objDef, dto.getSecurityAnswers().get(0).getQuestionAnswer());
      //	PropertyDelta delta= PropertyDelta.createModifica

      	 System.out.println("Update Questions3");
      	deltas.add(ObjectDelta.createModifyDelta(useroid, delta, type, getPrismContext()));
      	System.out.println("Update Questions4");
      	getModelService().executeChanges(deltas, null, createSimpleTask(OPERATION_SAVE_QUESTIONS), result);
      	System.out.println("Update Questions5");

      	 */
      success(getString("message.success"));
      target.add(getFeedbackPanel());
    } catch (Exception ex) {

      error(getString("message.error"));
      target.add(getFeedbackPanel());
      ex.printStackTrace();
    }
  }
Exemple #21
0
  public ObjectDelta getObjectDelta() throws SchemaException {
    if (ContainerStatus.ADDING.equals(getStatus())) {
      return createAddingObjectDelta();
    }

    ObjectDelta delta =
        new ObjectDelta(object.getCompileTimeClass(), ChangeType.MODIFY, object.getPrismContext());
    delta.setOid(object.getOid());

    List<ContainerWrapper> containers = getContainers();
    // sort containers by path size
    Collections.sort(containers, new PathSizeComparator());

    for (ContainerWrapper containerWrapper : getContainers()) {
      // create ContainerDelta for association container
      // HACK HACK HACK create correct procession for association container data
      // according to its structure
      if (containerWrapper.getItemDefinition().getName().equals(ShadowType.F_ASSOCIATION)) {
        ContainerDelta<ShadowAssociationType> associationDelta =
            ContainerDelta.createDelta(
                ShadowType.F_ASSOCIATION, containerWrapper.getItemDefinition());
        List<AssociationWrapper> associationItemWrappers =
            (List<AssociationWrapper>) containerWrapper.getItems();
        for (AssociationWrapper associationItemWrapper : associationItemWrappers) {
          List<ValueWrapper> assocValueWrappers = associationItemWrapper.getValues();
          for (ValueWrapper assocValueWrapper : assocValueWrappers) {
            PrismContainerValue<ShadowAssociationType> assocValue =
                (PrismContainerValue<ShadowAssociationType>) assocValueWrapper.getValue();
            if (assocValueWrapper.getStatus() == ValueStatus.DELETED) {
              associationDelta.addValueToDelete(assocValue.clone());
            } else if (assocValueWrapper.getStatus().equals(ValueStatus.ADDED)) {
              associationDelta.addValueToAdd(assocValue.clone());
            }
          }
        }
        delta.addModification(associationDelta);
      } else {
        if (!containerWrapper.hasChanged()) {
          continue;
        }

        for (ItemWrapper itemWrapper : (List<ItemWrapper>) containerWrapper.getItems()) {
          if (!itemWrapper.hasChanged()) {
            continue;
          }
          ItemPath containerPath =
              containerWrapper.getPath() != null ? containerWrapper.getPath() : new ItemPath();
          if (itemWrapper instanceof PropertyWrapper) {
            ItemDelta pDelta = computePropertyDeltas((PropertyWrapper) itemWrapper, containerPath);
            if (!pDelta.isEmpty()) {
              delta.addModification(pDelta);
            }
          }

          if (itemWrapper instanceof ReferenceWrapper) {
            ReferenceDelta pDelta =
                computeReferenceDeltas((ReferenceWrapper) itemWrapper, containerPath);
            if (!pDelta.isEmpty()) {
              delta.addModification(pDelta);
            }
          }
        }
      }
    }
    // returning container to previous order
    Collections.sort(containers, new ItemWrapperComparator());

    // Make sure we have all the definitions
    if (object.getPrismContext() != null) {
      object.getPrismContext().adopt(delta);
    }
    return delta;
  }
Exemple #22
0
  private ObjectDelta createAddingObjectDelta() throws SchemaException {
    PrismObject object = this.object.clone();

    List<ContainerWrapper> containers = getContainers();
    // sort containers by path size
    Collections.sort(containers, new PathSizeComparator());

    for (ContainerWrapper containerWrapper : getContainers()) {

      if (containerWrapper.getItemDefinition().getName().equals(ShadowType.F_ASSOCIATION)) {
        PrismContainer associationContainer =
            object.findOrCreateContainer(ShadowType.F_ASSOCIATION);
        List<AssociationWrapper> associationItemWrappers =
            (List<AssociationWrapper>) containerWrapper.getItems();
        for (AssociationWrapper associationItemWrapper : associationItemWrappers) {
          List<ValueWrapper> assocValueWrappers = associationItemWrapper.getValues();
          for (ValueWrapper assocValueWrapper : assocValueWrappers) {
            PrismContainerValue<ShadowAssociationType> assocValue =
                (PrismContainerValue<ShadowAssociationType>) assocValueWrapper.getValue();
            associationContainer.add(assocValue.clone());
          }
        }
        continue;
      }

      if (!containerWrapper.hasChanged()) {
        continue;
      }

      PrismContainer container = containerWrapper.getItem();
      ItemPath path = containerWrapper.getPath();
      if (containerWrapper.getPath() != null) {
        container = container.clone();
        if (path.size() > 1) {
          ItemPath parentPath = path.allExceptLast();
          PrismContainer parent = object.findOrCreateContainer(parentPath);
          parent.add(container);
        } else {
          PrismContainer existing = object.findContainer(container.getElementName());
          if (existing == null) {
            object.add(container);
          } else {
            continue;
          }
        }
      } else {
        container = object;
      }

      for (ItemWrapper propertyWrapper : (List<ItemWrapper>) containerWrapper.getItems()) {
        if (!propertyWrapper.hasChanged()) {
          continue;
        }

        Item property = propertyWrapper.getItem().clone();
        if (container.findProperty(property.getElementName()) != null) {
          continue;
        }
        for (ValueWrapper valueWrapper : propertyWrapper.getValues()) {
          valueWrapper.normalize(object.getPrismContext());
          if (!valueWrapper.hasValueChanged()
              || ValueStatus.DELETED.equals(valueWrapper.getStatus())) {
            continue;
          }

          if (property.hasRealValue(valueWrapper.getValue())) {
            continue;
          }

          PrismValue cloned = clone(valueWrapper.getValue());
          if (cloned != null) {
            property.add(cloned);
          }
        }

        if (!property.isEmpty()) {
          container.add(property);
        }
      }
    }

    // cleanup empty containers
    cleanupEmptyContainers(object);

    ObjectDelta delta = ObjectDelta.createAddDelta(object);

    // returning container to previous order
    Collections.sort(containers, new ItemWrapperComparator());

    if (InternalsConfig.consistencyChecks) {
      delta.checkConsistence(true, true, true, ConsistencyCheckScope.THOROUGH);
    }

    return delta;
  }