Esempio n. 1
0
  private void cleanupEmptyContainers(PrismContainer container) {
    List<PrismContainerValue> values = container.getValues();
    List<PrismContainerValue> valuesToBeRemoved = new ArrayList<PrismContainerValue>();
    for (PrismContainerValue value : values) {
      List<? extends Item> items = value.getItems();
      if (items != null) {
        Iterator<? extends Item> iterator = items.iterator();
        while (iterator.hasNext()) {
          Item item = iterator.next();

          if (item instanceof PrismContainer) {
            cleanupEmptyContainers((PrismContainer) item);

            if (item.isEmpty()) {
              iterator.remove();
            }
          }
        }
      }

      if (items == null || value.isEmpty()) {
        valuesToBeRemoved.add(value);
      }
    }

    container.removeAll(valuesToBeRemoved);
  }
Esempio n. 2
0
  private AssignmentItemDto createAssignmentItem(
      PrismObject<UserType> user,
      PrismContainerValue assignment,
      Task task,
      OperationResult result) {
    PrismReference targetRef = assignment.findReference(AssignmentType.F_TARGET_REF);
    if (targetRef == null || targetRef.isEmpty()) {
      // account construction
      PrismContainer construction = assignment.findContainer(AssignmentType.F_CONSTRUCTION);
      String name = null;
      String description = null;
      if (construction.getValue().asContainerable() != null && !construction.isEmpty()) {
        ConstructionType constr = (ConstructionType) construction.getValue().asContainerable();
        description =
            (String)
                construction.getPropertyRealValue(ConstructionType.F_DESCRIPTION, String.class);

        if (constr.getResourceRef() != null) {
          ObjectReferenceType resourceRef = constr.getResourceRef();

          PrismObject resource =
              WebModelUtils.loadObject(
                  ResourceType.class, resourceRef.getOid(), this, task, result);
          name = WebMiscUtil.getName(resource);
        }
      }

      return new AssignmentItemDto(
          AssignmentEditorDtoType.ACCOUNT_CONSTRUCTION, name, description, null);
    }

    PrismReferenceValue refValue = targetRef.getValue();
    PrismObject value = refValue.getObject();
    if (value == null) {
      // resolve reference
      value = WebModelUtils.loadObject(ObjectType.class, refValue.getOid(), this, task, result);
    }

    if (value == null) {
      // we couldn't resolve assignment details
      return new AssignmentItemDto(null, null, null, null);
    }

    String name = WebMiscUtil.getName(value);
    AssignmentEditorDtoType type = AssignmentEditorDtoType.getType(value.getCompileTimeClass());
    String relation = refValue.getRelation() != null ? refValue.getRelation().getLocalPart() : null;
    String description = null;
    if (RoleType.class.isAssignableFrom(value.getCompileTimeClass())) {
      description = (String) value.getPropertyRealValue(RoleType.F_DESCRIPTION, String.class);
    }

    return new AssignmentItemDto(type, name, description, relation);
  }
Esempio n. 3
0
 public List<PrismContainerValue<AccessCertificationCaseType>> getCertificationCampaignCases(
     String campaignName)
     throws SchemaException, SecurityViolationException, ConfigurationException,
         ObjectNotFoundException {
   List<AccessCertificationCaseType> cases = getCertificationCampaignCasesAsBeans(campaignName);
   return PrismContainerValue.toPcvList(cases);
 }
  @Override
  public void setObject(Object object) {
    try {
      PrismProperty property = getPrismObject().findOrCreateProperty(path);

      if (object != null) {
        PrismPropertyDefinition def = property.getDefinition();
        if (PolyString.class.equals(def.getTypeClass())) {
          object = new PolyString((String) object);
        }

        property.setValue(new PrismPropertyValue(object, OriginType.USER_ACTION, null));
      } else {
        PrismContainerValue parent = (PrismContainerValue) property.getParent();
        parent.remove(property);
      }
    } catch (Exception ex) {
      LoggingUtils.logException(LOGGER, "Couldn't update prism property model", ex);
    }
  }
Esempio n. 5
0
 public List<PrismContainerValue<AccessCertificationDecisionType>>
     getCertificationCampaignDecisions(String campaignName, Integer stageNumber)
         throws SchemaException, SecurityViolationException, ConfigurationException,
             ObjectNotFoundException {
   List<AccessCertificationCaseType> cases = getCertificationCampaignCasesAsBeans(campaignName);
   List<AccessCertificationDecisionType> decisions = new ArrayList<>();
   for (AccessCertificationCaseType aCase : cases) {
     for (AccessCertificationDecisionType decision : aCase.getDecision()) {
       if (stageNumber == null || decision.getStageNumber() == stageNumber) {
         decisions.add(decision);
       }
     }
   }
   return PrismContainerValue.toPcvList(decisions);
 }
  private void assertTask(PrismObject<TaskType> task) {

    task.checkConsistence();

    assertEquals("Wrong oid", "44444444-4444-4444-4444-000000001111", task.getOid());
    PrismObjectDefinition<TaskType> usedDefinition = task.getDefinition();
    assertNotNull("No task definition", usedDefinition);
    PrismAsserts.assertObjectDefinition(
        usedDefinition,
        new QName(SchemaConstantsGenerated.NS_COMMON, "task"),
        TaskType.COMPLEX_TYPE,
        TaskType.class);
    assertEquals("Wrong class in task", TaskType.class, task.getCompileTimeClass());
    TaskType taskType = task.asObjectable();
    assertNotNull("asObjectable resulted in null", taskType);

    assertPropertyValue(task, "name", PrismTestUtil.createPolyString("Task2"));
    assertPropertyDefinition(task, "name", PolyStringType.COMPLEX_TYPE, 0, 1);

    assertPropertyValue(task, "taskIdentifier", "44444444-4444-4444-4444-000000001111");
    assertPropertyDefinition(task, "taskIdentifier", DOMUtil.XSD_STRING, 0, 1);

    assertPropertyDefinition(
        task, "executionStatus", JAXBUtil.getTypeQName(TaskExecutionStatusType.class), 1, 1);
    PrismProperty<TaskExecutionStatusType> executionStatusProperty =
        task.findProperty(TaskType.F_EXECUTION_STATUS);
    PrismPropertyValue<TaskExecutionStatusType> executionStatusValue =
        executionStatusProperty.getValue();
    TaskExecutionStatusType executionStatus = executionStatusValue.getValue();
    assertEquals("Wrong execution status", TaskExecutionStatusType.RUNNABLE, executionStatus);

    PrismContainer extension = task.getExtension();
    PrismContainerValue extensionValue = extension.getValue();
    assertTrue("Extension parent", extensionValue.getParent() == extension);
    assertNull("Extension ID", extensionValue.getId());
  }
  private void generateIdForObject(
      PrismObject object, IdGeneratorResult result, Operation operation) {
    if (object == null) {
      return;
    }

    List<PrismContainer> containers = getChildrenContainers(object);
    Set<Long> usedIds = new HashSet<>();
    for (PrismContainer c : containers) {
      if (c == null || c.getValues() == null) {
        continue;
      }

      for (PrismContainerValue val : (List<PrismContainerValue>) c.getValues()) {
        if (val.getId() != null) {
          usedIds.add(val.getId());
        }
      }
    }

    Long nextId = 1L;
    for (PrismContainer c : containers) {
      if (c == null || c.getValues() == null) {
        continue;
      }

      for (PrismContainerValue val : (List<PrismContainerValue>) c.getValues()) {
        if (val.getId() != null) {
          if (Operation.ADD.equals(operation)) {
            result.getValues().add(val);
          }
          continue;
        }

        while (usedIds.contains(nextId)) {
          nextId++;
        }

        val.setId(nextId);
        usedIds.add(nextId);

        if (!Operation.ADD_WITH_OVERWRITE.equals(operation)
            && !Operation.MODIFY.equals(operation)) {
          result.getValues().add(val);
        }
      }
    }
  }
Esempio n. 8
0
  private <C extends Containerable> void serializeContainerValue(
      MapXNode xmap,
      PrismContainerValue<C> containerVal,
      PrismContainerDefinition<C> containerDefinition,
      SerializationContext ctx)
      throws SchemaException {
    Long id = containerVal.getId();
    if (id != null) {
      xmap.put(XNode.KEY_CONTAINER_ID, createPrimitiveXNodeAttr(id, DOMUtil.XSD_LONG));
    }
    if (containerVal.getConcreteType() != null) {
      xmap.setTypeQName(containerVal.getConcreteType());
      xmap.setExplicitTypeDeclaration(true);
    }

    Collection<QName> serializedItems = new ArrayList<>();
    if (containerDefinition != null) {
      // We have to serialize in the definition order. Some data formats (XML) are
      // ordering-sensitive. We need to keep that ordering otherwise the resulting
      // document won't pass schema validation
      for (ItemDefinition itemDef : containerDefinition.getDefinitions()) {
        QName elementName = itemDef.getName();
        Item<?, ?> item = containerVal.findItem(elementName);
        if (item != null) {
          XNode xsubnode = serializeItem(item, ctx);
          xmap.put(elementName, xsubnode);
          serializedItems.add(elementName);
        }
      }
    }
    // There are some cases when we do not have list of all elements in a container.
    // E.g. in run-time schema. Therefore we must also iterate over items and not just item
    // definitions.
    if (containerVal.getItems() != null) {
      for (Item<?, ?> item : containerVal.getItems()) {
        QName elementName = item.getElementName();
        if (serializedItems.contains(elementName)) {
          continue;
        }
        XNode xsubnode = serializeItem(item, ctx);
        xmap.put(elementName, xsubnode);
      }
    }
  }
  /**
   * Transforms midPoint XML configuration of the connector to the ICF configuration.
   *
   * <p>The "configuration" part of the XML resource definition will be used.
   *
   * <p>The provided ICF APIConfiguration will be modified, some values may be overwritten.
   *
   * @param apiConfig ICF connector configuration
   * @param resourceType midPoint XML configuration
   * @throws SchemaException
   * @throws ConfigurationException
   */
  public APIConfiguration transformConnectorConfiguration(PrismContainerValue configuration)
      throws SchemaException, ConfigurationException {

    APIConfiguration apiConfig = cinfo.createDefaultAPIConfiguration();
    ConfigurationProperties configProps = apiConfig.getConfigurationProperties();

    // The namespace of all the configuration properties specific to the
    // connector instance will have a connector instance namespace. This
    // namespace can be found in the resource definition.
    String connectorConfNs = connectorType.getNamespace();

    PrismContainer configurationPropertiesContainer =
        configuration.findContainer(
            ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_QNAME);
    if (configurationPropertiesContainer == null) {
      // Also try this. This is an older way.
      configurationPropertiesContainer =
          configuration.findContainer(
              new QName(
                  connectorConfNs,
                  ConnectorFactoryIcfImpl
                      .CONNECTOR_SCHEMA_CONFIGURATION_PROPERTIES_ELEMENT_LOCAL_NAME));
    }

    transformConnectorConfiguration(configProps, configurationPropertiesContainer, connectorConfNs);

    PrismContainer connectorPoolContainer =
        configuration.findContainer(
            new QName(
                ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION,
                ConnectorFactoryIcfImpl
                    .CONNECTOR_SCHEMA_CONNECTOR_POOL_CONFIGURATION_XML_ELEMENT_NAME));
    ObjectPoolConfiguration connectorPoolConfiguration = apiConfig.getConnectorPoolConfiguration();
    transformConnectorPoolConfiguration(connectorPoolConfiguration, connectorPoolContainer);

    PrismProperty producerBufferSizeProperty =
        configuration.findProperty(
            new QName(
                ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION,
                ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_PRODUCER_BUFFER_SIZE_XML_ELEMENT_NAME));
    if (producerBufferSizeProperty != null) {
      apiConfig.setProducerBufferSize(parseInt(producerBufferSizeProperty));
    }

    PrismContainer connectorTimeoutsContainer =
        configuration.findContainer(
            new QName(
                ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION,
                ConnectorFactoryIcfImpl.CONNECTOR_SCHEMA_TIMEOUTS_XML_ELEMENT_NAME));
    transformConnectorTimeoutsConfiguration(apiConfig, connectorTimeoutsContainer);

    PrismContainer resultsHandlerConfigurationContainer =
        configuration.findContainer(
            new QName(
                ConnectorFactoryIcfImpl.NS_ICF_CONFIGURATION,
                ConnectorFactoryIcfImpl
                    .CONNECTOR_SCHEMA_RESULTS_HANDLER_CONFIGURATION_ELEMENT_LOCAL_NAME));
    ResultsHandlerConfiguration resultsHandlerConfiguration =
        apiConfig.getResultsHandlerConfiguration();
    transformResultsHandlerConfiguration(
        resultsHandlerConfiguration, resultsHandlerConfigurationContainer);

    return apiConfig;
  }
  public static <T> String serializeValue(
      T value,
      ItemDefinition def,
      QName itemName,
      QName parentName,
      PrismContext prismContext,
      String language)
      throws SchemaException {
    //		System.out.println("value serialization");
    if (value == null) {
      return null;
    }

    XNodeSerializer serializer = prismContext.getXnodeProcessor().createSerializer();

    if (value instanceof List) {
      List<T> values = (List<T>) value;
      if (values.isEmpty()) {
        return null;
      }

      if (def instanceof PrismPropertyDefinition) {
        PrismProperty prop = (PrismProperty) def.instantiate(itemName);
        for (T val : values) {
          PrismPropertyValue<T> pValue = new PrismPropertyValue<T>(val);
          prop.add(pValue);
        }

        XNode node = serializer.serializeItem(prop);
        if (node instanceof ListXNode) {
          ListXNode xList = (ListXNode) node;
          if (xList.size() == 1) {
            XNode sub = xList.iterator().next();
            if (!(sub instanceof MapXNode)) {
              throw new IllegalArgumentException("must be a map");
            }

            String s = prismContext.getParserDom().serializeToString(sub, parentName);
            //						System.out.println("serialized: " + s);
            return s;

          } else {
            MapXNode xmap = new MapXNode();
            xmap.put(itemName, xList);
            String s = prismContext.getParserDom().serializeToString(xmap, parentName);
            //						System.out.println("serialized: " + s);
            return s;
            //						throw new IllegalArgumentException("Check your data.");
          }

          //					MapXNode xmap = xList.new MapXNode();
          //					xmap.put(def.getName(), xList);

        }
        String s = prismContext.getParserDom().serializeToString(node, def.getName());
        //				System.out.println("serialized: " + s);
        return s;
      } else if (def instanceof PrismContainerDefinition) {
        PrismContainer pc = (PrismContainer) def.instantiate();
        for (T val : values) {
          //					PrismContainerValue pcVal = new PrismContainerValue<Containerable>((Containerable)
          // val);
          PrismContainerValue pcVal = ((Containerable) val).asPrismContainerValue();
          pc.add(pcVal.clone());
        }
        XNode node = serializer.serializeItem(pc);
        if (node instanceof ListXNode) {
          ListXNode xList = (ListXNode) node;
          MapXNode xmap = new MapXNode();
          xmap.put(def.getName(), xList);
          String s = prismContext.getParserDom().serializeToString(xmap, parentName);
          //					System.out.println("serialized: " + s);
          return s;
        }
        String s = prismContext.getParserDom().serializeToString(node, def.getName());
        //				System.out.println("serialized: " + s);
        return s;
      }
    }

    PrismValue pVal = null;

    if (value instanceof Containerable) {
      pVal = ((Containerable) value).asPrismContainerValue();
    } else if (value instanceof Referencable) {
      pVal = ((Referencable) value).asReferenceValue();
    } else {
      pVal = new PrismPropertyValue<T>(value);
    }

    //		Class clazz = prismContext.getSchemaRegistry().determineCompileTimeClass(itemName);
    //		PrismContainerDefinition def =
    // prismContext.getSchemaRegistry().determineDefinitionFromClass(clazz);
    //
    //		ItemDefinition def =
    // prismContext.getSchemaRegistry().findItemDefinitionByElementName(itemName);

    //		QName itemName = null;
    if (def != null) {
      itemName = def.getName();
    }

    XNode node = serializer.serializeItemValue(pVal, def);
    String s = prismContext.getParserDom().serializeToString(node, itemName);
    //		System.out.println("serialized: " + s);
    return s;
    //		throw new UnsupportedOperationException("need to be implemented");
  }
  private List<ItemWrapper> createProperties(PageBase pageBase) {
    result = new OperationResult(CREATE_PROPERTIES);

    List<ItemWrapper> properties = new ArrayList<ItemWrapper>();

    PrismContainerDefinition definition = null;
    PrismObject parent = getObject().getObject();
    Class clazz = parent.getCompileTimeClass();
    if (ShadowType.class.isAssignableFrom(clazz)) {
      QName name = containerDefinition.getName();

      if (ShadowType.F_ATTRIBUTES.equals(name)) {
        try {
          definition = objectWrapper.getRefinedAttributeDefinition();

          if (definition == null) {
            PrismReference resourceRef = parent.findReference(ShadowType.F_RESOURCE_REF);
            PrismObject<ResourceType> resource = resourceRef.getValue().getObject();

            definition =
                pageBase
                    .getModelInteractionService()
                    .getEditObjectClassDefinition(
                        (PrismObject<ShadowType>) objectWrapper.getObject(),
                        resource,
                        AuthorizationPhaseType.REQUEST)
                    .toResourceAttributeContainerDefinition();

            if (LOGGER.isTraceEnabled()) {
              LOGGER.trace("Refined account def:\n{}", definition.debugDump());
            }
          }
        } catch (Exception ex) {
          LoggingUtils.logException(
              LOGGER, "Couldn't load definitions from refined schema for shadow", ex);
          result.recordFatalError(
              "Couldn't load definitions from refined schema for shadow, reason: "
                  + ex.getMessage(),
              ex);

          return properties;
        }
      } else {
        definition = containerDefinition;
      }
    } else if (ResourceType.class.isAssignableFrom(clazz)) {
      if (containerDefinition != null) {
        definition = containerDefinition;
      } else {
        definition = container.getDefinition();
      }
    } else {
      definition = containerDefinition;
    }

    if (definition == null) {
      LOGGER.error(
          "Couldn't get property list from null definition {}",
          new Object[] {container.getElementName()});
      return properties;
    }

    // assignments are treated in a special way -- we display names of
    // org.units and roles
    // (but only if ObjectWrapper.isShowAssignments() is true; otherwise
    // they are filtered out by ObjectWrapper)
    if (container.getCompileTimeClass() != null
        && AssignmentType.class.isAssignableFrom(container.getCompileTimeClass())) {

      for (Object o : container.getValues()) {
        PrismContainerValue<AssignmentType> pcv = (PrismContainerValue<AssignmentType>) o;

        AssignmentType assignmentType = pcv.asContainerable();

        if (assignmentType.getTargetRef() == null) {
          continue;
        }

        // hack... we want to create a definition for Name
        // PrismPropertyDefinition def = ((PrismContainerValue)
        // pcv.getContainer().getParent()).getContainer().findProperty(ObjectType.F_NAME).getDefinition();
        PrismPropertyDefinition def =
            new PrismPropertyDefinition(
                ObjectType.F_NAME, DOMUtil.XSD_STRING, pcv.getPrismContext());

        if (OrgType.COMPLEX_TYPE.equals(assignmentType.getTargetRef().getType())) {
          def.setDisplayName("Org.Unit");
          def.setDisplayOrder(100);
        } else if (RoleType.COMPLEX_TYPE.equals(assignmentType.getTargetRef().getType())) {
          def.setDisplayName("Role");
          def.setDisplayOrder(200);
        } else {
          continue;
        }

        PrismProperty<Object> temp = def.instantiate();

        String value = formatAssignmentBrief(assignmentType);

        temp.setValue(new PrismPropertyValue<Object>(value));
        // TODO: do this.isReadOnly() - is that OK? (originally it was the default behavior for all
        // cases)
        properties.add(new PropertyWrapper(this, temp, this.isReadonly(), ValueStatus.NOT_CHANGED));
      }

    } else if (isShadowAssociation()) {
      PrismContext prismContext = objectWrapper.getObject().getPrismContext();
      Map<QName, PrismContainer<ShadowAssociationType>> assocMap = new HashMap<>();
      if (objectWrapper.getAssociations() != null) {
        for (PrismContainerValue<ShadowAssociationType> cval : objectWrapper.getAssociations()) {
          ShadowAssociationType associationType = cval.asContainerable();
          QName assocName = associationType.getName();
          PrismContainer<ShadowAssociationType> fractionalContainer = assocMap.get(assocName);
          if (fractionalContainer == null) {
            fractionalContainer =
                new PrismContainer<>(
                    ShadowType.F_ASSOCIATION, ShadowAssociationType.class, cval.getPrismContext());
            fractionalContainer.setDefinition(cval.getParent().getDefinition());
            // HACK: set the name of the association as the element name so wrapper.getName() will
            // return correct data.
            fractionalContainer.setElementName(assocName);
            assocMap.put(assocName, fractionalContainer);
          }
          try {
            fractionalContainer.add(cval.clone());
          } catch (SchemaException e) {
            // Should not happen
            throw new SystemException("Unexpected error: " + e.getMessage(), e);
          }
        }
      }

      PrismReference resourceRef = parent.findReference(ShadowType.F_RESOURCE_REF);
      PrismObject<ResourceType> resource = resourceRef.getValue().getObject();

      // HACK. The revive should not be here. Revive is no good. The next use of the resource will
      // cause parsing of resource schema. We need some centralized place to maintain live cached
      // copies
      // of resources.
      try {
        resource.revive(prismContext);
      } catch (SchemaException e) {
        throw new SystemException(e.getMessage(), e);
      }
      RefinedResourceSchema refinedSchema;
      CompositeRefinedObjectClassDefinition rOcDef;
      try {
        refinedSchema = RefinedResourceSchema.getRefinedSchema(resource);
        rOcDef = refinedSchema.determineCompositeObjectClassDefinition(parent);
      } catch (SchemaException e) {
        throw new SystemException(e.getMessage(), e);
      }
      // Make sure even empty associations have their wrappers so they can be displayed and edited
      for (RefinedAssociationDefinition assocDef : rOcDef.getAssociations()) {
        QName name = assocDef.getName();
        if (!assocMap.containsKey(name)) {
          PrismContainer<ShadowAssociationType> fractionalContainer =
              new PrismContainer<>(
                  ShadowType.F_ASSOCIATION, ShadowAssociationType.class, prismContext);
          fractionalContainer.setDefinition(getItemDefinition());
          // HACK: set the name of the association as the element name so wrapper.getName() will
          // return correct data.
          fractionalContainer.setElementName(name);
          assocMap.put(name, fractionalContainer);
        }
      }

      for (Entry<QName, PrismContainer<ShadowAssociationType>> assocEntry : assocMap.entrySet()) {
        // HACK HACK HACK, the container wrapper should not parse itself. This code should not be
        // here.
        AssociationWrapper assocWrapper =
            new AssociationWrapper(
                this, assocEntry.getValue(), this.isReadonly(), ValueStatus.NOT_CHANGED);
        properties.add(assocWrapper);
      }

    } else { // if not an assignment

      if ((container.getValues().size() == 1 || container.getValues().isEmpty())
          && (containerDefinition == null || containerDefinition.isSingleValue())) {

        // there's no point in showing properties for non-single-valued
        // parent containers,
        // so we continue only if the parent is single-valued

        Collection<ItemDefinition> propertyDefinitions = definition.getDefinitions();
        for (ItemDefinition itemDef : propertyDefinitions) {
          if (itemDef instanceof PrismPropertyDefinition) {

            PrismPropertyDefinition def = (PrismPropertyDefinition) itemDef;
            if (def.isIgnored() || skipProperty(def)) {
              continue;
            }
            if (!showInheritedObjectAttributes
                && INHERITED_OBJECT_ATTRIBUTES.contains(def.getName())) {
              continue;
            }

            // capability handling for activation properties
            if (isShadowActivation() && !hasCapability(def)) {
              continue;
            }

            if (isShadowAssociation()) {
              continue;
            }

            PrismProperty property = container.findProperty(def.getName());
            boolean propertyIsReadOnly;
            // decision is based on parent object status, not this
            // container's one (because container can be added also
            // to an existing object)
            if (objectWrapper.getStatus() == ContainerStatus.MODIFYING) {

              propertyIsReadOnly = !def.canModify();
            } else {
              propertyIsReadOnly = !def.canAdd();
            }
            if (property == null) {
              properties.add(
                  new PropertyWrapper(
                      this, def.instantiate(), propertyIsReadOnly, ValueStatus.ADDED));
            } else {
              properties.add(
                  new PropertyWrapper(this, property, propertyIsReadOnly, ValueStatus.NOT_CHANGED));
            }
          } else if (itemDef instanceof PrismReferenceDefinition) {
            PrismReferenceDefinition def = (PrismReferenceDefinition) itemDef;

            if (INHERITED_OBJECT_ATTRIBUTES.contains(def.getName())) {
              continue;
            }

            PrismReference reference = container.findReference(def.getName());
            boolean propertyIsReadOnly;
            // decision is based on parent object status, not this
            // container's one (because container can be added also
            // to an existing object)
            if (objectWrapper.getStatus() == ContainerStatus.MODIFYING) {

              propertyIsReadOnly = !def.canModify();
            } else {
              propertyIsReadOnly = !def.canAdd();
            }
            if (reference == null) {
              properties.add(
                  new ReferenceWrapper(
                      this, def.instantiate(), propertyIsReadOnly, ValueStatus.ADDED));
            } else {
              properties.add(
                  new ReferenceWrapper(
                      this, reference, propertyIsReadOnly, ValueStatus.NOT_CHANGED));
            }
          }
        }
      }
    }

    Collections.sort(properties, new ItemWrapperComparator());

    result.recomputeStatus();

    return properties;
  }
Esempio n. 12
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;
  }
Esempio n. 13
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;
  }