public <IV extends PrismValue, ID extends ItemDefinition> XNode serializeItem(
      Item<IV, ID> item, SerializationContext ctx) throws SchemaException {
    ListXNode xlist = new ListXNode();
    List<IV> values = item.getValues();
    ItemDefinition definition = item.getDefinition();

    for (IV val : values) {
      XNode xsubnode = serializeItemValue(val, definition, ctx);
      xlist.add(xsubnode);
    }

    boolean asList;
    if (definition != null) {
      asList = definition.isMultiValue();
    } else {
      asList = values.size() > 1;
    }

    if (asList) {
      return xlist;
    } else {
      if (xlist.isEmpty()) {
        return null;
      } else {
        return xlist.iterator().next();
      }
    }
  }
Exemple #2
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);
  }
  private boolean isAddButtonVisible() {
    ValueWrapper valueWrapper = model.getObject();

    if (valueWrapper.isReadonly()) {
      return false;
    }

    ItemWrapper propertyWrapper = valueWrapper.getItem();
    Item property = propertyWrapper.getItem();

    ItemDefinition definition = property.getDefinition();
    int max = definition.getMaxOccurs();
    List<ValueWrapper> usableValues = getUsableValues(propertyWrapper);
    if (usableValues.indexOf(valueWrapper) != usableValues.size() - 1) {
      return false;
    }

    if (max == -1) {
      return true;
    }

    if (countNonDeletedValues(propertyWrapper) >= max) {
      return false;
    }

    return isAccessible(definition, propertyWrapper.getContainer().getObject().getStatus());
  }
  private boolean isAddButtonVisible() {
    Component inputPanel = this.get(ID_VALUE_CONTAINER).get(ID_INPUT);
    ValueWrapper valueWrapper = valueWrapperModel.getObject();

    if (valueWrapper.isReadonly()) {
      return false;
    }

    ItemWrapper propertyWrapper = valueWrapper.getItem();
    Item property = propertyWrapper.getItem();

    ItemDefinition definition = property.getDefinition();
    int max = definition.getMaxOccurs();
    List<ValueWrapper> usableValues = getUsableValues(propertyWrapper);
    if (usableValues.indexOf(valueWrapper) != usableValues.size() - 1) {
      return false;
    }

    if (max == -1) {
      return true;
    }

    if (countNonDeletedValues(propertyWrapper) >= max) {
      return false;
    }

    if (propertyWrapper.getContainer() == null) {
      return true; // TODO
    }
    return isAccessible(definition, getContainerStatus(propertyWrapper));
  }
  private Panel createInputComponent(String id, IModel<String> labelModel, Form form) {
    ValueWrapper valueWrapper = valueWrapperModel.getObject();
    ObjectWrapper objectWrapper = null;
    if (valueWrapper.getItem().getContainer() != null) {
      objectWrapper = valueWrapper.getItem().getContainer().getObject();
    }
    Item property = valueWrapper.getItem().getItem();
    boolean required = property.getDefinition().getMinOccurs() > 0;

    Panel component = createTypedInputComponent(id);

    if (component instanceof InputPanel) {
      InputPanel inputPanel = (InputPanel) component;
      // adding valid from/to date range validator, if necessary
      ItemPath activation = new ItemPath(UserType.F_ACTIVATION);
      if (ActivationType.F_VALID_FROM.equals(property.getElementName())) {
        DateValidator validator = getActivationRangeValidator(form, activation);
        validator.setDateFrom((DateTimeField) inputPanel.getBaseFormComponent());
      } else if (ActivationType.F_VALID_TO.equals(property.getElementName())) {
        DateValidator validator = getActivationRangeValidator(form, activation);
        validator.setDateTo((DateTimeField) inputPanel.getBaseFormComponent());
      }

      final List<FormComponent> formComponents = inputPanel.getFormComponents();
      for (FormComponent formComponent : formComponents) {
        formComponent.setLabel(labelModel);
        formComponent.setRequired(required);

        if (formComponent instanceof TextField) {
          formComponent.add(new AttributeModifier("size", "42"));
        }
        formComponent.add(
            new AjaxFormComponentUpdatingBehavior("blur") {

              @Override
              protected void onUpdate(AjaxRequestTarget target) {}
            });

        // Validation occurs when submitting the form
        //            if (form != null) {
        //                AjaxFormValidatingBehavior validator = new
        // AjaxFormValidatingBehavior(form, "Blur");
        //
        //                formComponent.add(validator);
        //            }
      }
    }
    if (component == null) {
      throw new RuntimeException(
          "Cannot create input component for item "
              + property
              + " ("
              + valueWrapper
              + ") in "
              + objectWrapper);
    }
    return component;
  }
  public static <T> T deserializeValue(
      String value,
      Class clazz,
      QName itemName,
      ItemDefinition itemDef,
      PrismContext prismContext,
      String language)
      throws SchemaException {
    // System.out.println("item value deserialization");

    XNode xnode = prismContext.getParserDom().parse(value);

    //		System.out.println("xnode: " + xnode.debugDump());

    XNode xmap = null;
    if (xnode instanceof RootXNode) {
      xmap = ((RootXNode) xnode).getSubnode();
    }

    //		System.out.println("xmap: " + xmap);
    //		else if (xnode instanceof MapXNode){
    //			xmap = (MapXNode) xnode;
    //		} else if (xnode instanceof PrimitiveXNode){
    //			xmap = new MapXNode();
    //			xmap.put(itemName, xnode);
    //		}

    Item item = prismContext.getXnodeProcessor().parseItem(xmap, itemName, itemDef);

    //		System.out.println("item: " + item.debugDump());

    if (item instanceof PrismProperty) {
      PrismProperty prop = (PrismProperty) item;

      if (prop.isSingleValue()) {
        return (T) prop.getRealValue();
      }
      return (T) prop.getRealValues();
    } else if (item instanceof PrismContainer) {
      PrismContainer cont = (PrismContainer) item;
      return (T) cont.getValue().asContainerable();
    } else if (item instanceof PrismReference) {
      PrismReference ref = (PrismReference) item;
      return (T) ref.getValue();
    }
    if (item != null) {
      return (T) item.getValue(0);
    }
    //		if (prismContext.getBeanConverter().canConvert(clazz)){
    //			prismContext.getBeanConverter().unmarshall(xmap, clazz);
    //		} else{
    //			prismContext.getXnodeProcessor().parseContainer(xnode, clazz);
    //		}

    throw new UnsupportedOperationException("need to be implemented");
  }
  static String getDisplayNameFromItem(Item item) {
    Validate.notNull(item, "Item must not be null.");

    String displayName = item.getDisplayName();
    if (StringUtils.isEmpty(displayName)) {
      QName name = item.getElementName();
      if (name != null) {
        displayName = name.getLocalPart();
      } else {
        displayName = item.getDefinition().getTypeName().getLocalPart();
      }
    }

    return displayName;
  }
 public static Collection<? extends PrismValue> deserializeItemValues(
     String value, Item item, String language) throws SchemaException {
   // System.out.println("item value deserialization");
   PrismContext prismContext = item.getPrismContext();
   XNode xnode = prismContext.getParserDom().parse(value);
   if (xnode instanceof RootXNode) {
     xnode = ((RootXNode) xnode).getSubnode();
   }
   // System.out.println("value: " + value);
   Item parsedItem =
       prismContext
           .getXnodeProcessor()
           .parseItem(xnode, item.getElementName(), item.getDefinition());
   return parsedItem.getValues();
   //		throw new UnsupportedOperationException("need to be implemented");
 }
  private void removeValue(AjaxRequestTarget target) {
    ValueWrapper wrapper = valueWrapperModel.getObject();
    ItemWrapper propertyWrapper = wrapper.getItem();
    LOGGER.debug("Removing value of {}", propertyWrapper);

    List<ValueWrapper> values = propertyWrapper.getValues();
    Component inputPanel = this.get(ID_VALUE_CONTAINER).get(ID_INPUT);

    switch (wrapper.getStatus()) {
      case ADDED:
        values.remove(wrapper);
        break;
      case DELETED:
        error("Couldn't delete already deleted item: " + wrapper.toString());
        target.add(((PageBase) getPage()).getFeedbackPanel());
      case NOT_CHANGED:
        if (inputPanel instanceof AssociationValueChoicePanel) {
          ((PropertyWrapper) propertyWrapper).setStatus(ValueStatus.DELETED);
        }
        wrapper.setStatus(ValueStatus.DELETED);
        break;
    }

    //        wrapper.getItem().getContainer().

    int count = countUsableValues(propertyWrapper);
    if (count == 0 && !hasEmptyPlaceholder(propertyWrapper)) {
      if (inputPanel instanceof ValueChoosePanel) {
        values.add(
            new ValueWrapper(propertyWrapper, new PrismReferenceValue(null), ValueStatus.ADDED));
      } else if (inputPanel instanceof AssociationValueChoicePanel) {
        Item item = propertyWrapper.getItem();
        ItemPath path = item.getPath();
        if (path != null) {}

        //                values.add(new ValueWrapper(propertyWrapper, new PrismPropertyValue(null),
        // ValueStatus.ADDED));
      } else {
        values.add(
            new ValueWrapper(propertyWrapper, new PrismPropertyValue(null), ValueStatus.ADDED));
      }
    }
    ListView parent = findParent(ListView.class);
    target.add(parent.getParent());
  }
  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);
      }
    }
  }
Exemple #11
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;
  }
Exemple #12
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) {
    //        ValueWrapper valueWrapper = model.getObject();
    //        ItemWrapper itemWrapper =
    final Item item = valueWrapperModel.getObject().getItem().getItem();

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

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

      // 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(valueWrapperModel, baseExpression), null);
      }

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

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

      } else if (ProtectedStringType.COMPLEX_TYPE.equals(valueType)) {
        boolean showRemovePasswordButton = true;
        if (pageBase instanceof PageUser
            && ((PageUser) pageBase).getObjectWrapper().getObject() != null
            && ((PageUser) pageBase).getObjectWrapper().getObject().getOid() != null
            && ((PageUser) pageBase)
                .getObjectWrapper()
                .getObject()
                .getOid()
                .equals(SecurityUtils.getPrincipalUser().getOid())) {
          showRemovePasswordButton = false;
        }
        panel =
            new PasswordPanel(
                id,
                new PropertyModel<ProtectedStringType>(valueWrapperModel, baseExpression),
                valueWrapperModel.getObject().isReadonly(),
                showRemovePasswordButton);
      } else if (DOMUtil.XSD_BOOLEAN.equals(valueType)) {
        panel =
            new TriStateComboPanel(
                id, new PropertyModel<Boolean>(valueWrapperModel, 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 =
              WebModelServiceUtils.loadObject(
                  LookupTableType.class, lookupTableUid, options, pageBase, task, result);

          if (lookupTable != null) {

            inputPanel =
                new AutoCompleteTextPanel<String>(
                    id,
                    new LookupPropertyModel<String>(
                        valueWrapperModel, 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>(valueWrapperModel, baseExpression + ".orig"),
                    String.class);
          }

        } else {

          inputPanel =
              new TextPanel<>(
                  id,
                  new PropertyModel<String>(valueWrapperModel, 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, valueWrapperModel.getObject().isReadonly()) {

              @Override
              public InputStream getStream() {
                Object object =
                    ((PrismPropertyValue) valueWrapperModel.getObject().getValue()).getValue();
                return object != null
                    ? new ByteArrayInputStream((byte[]) object)
                    : new ByteArrayInputStream(new byte[0]);
                //                		return super.getStream();
              }

              @Override
              public void updateValue(byte[] file) {
                ((PrismPropertyValue) valueWrapperModel.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 (valueWrapperModel.getObject() == null
                        || valueWrapperModel.getObject().getValue() == null
                        || ((PrismPropertyValue) valueWrapperModel.getObject().getValue())
                                .getValue()
                            == null) {
                      return null;
                    }
                    PrismContext prismContext = ((PageBase) getPage()).getPrismContext();
                    ObjectDeltaType objectDeltaType =
                        (ObjectDeltaType)
                            ((PrismPropertyValue) valueWrapperModel.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 if (QueryType.COMPLEX_TYPE.equals(valueType)
          || CleanupPoliciesType.COMPLEX_TYPE.equals(valueType)) {
        return new TextAreaPanel(
            id,
            new AbstractReadOnlyModel() {
              @Override
              public Object getObject() {
                if (valueWrapperModel.getObject() == null
                    || valueWrapperModel.getObject().getValue() == null) {
                  return null;
                }
                PrismPropertyValue ppv =
                    (PrismPropertyValue) valueWrapperModel.getObject().getValue();
                if (ppv == null || ppv.getValue() == null) {
                  return null;
                }
                QName name = property.getElementName();
                if (name == null && property.getDefinition() != null) {
                  name = property.getDefinition().getName();
                }
                if (name == null) {
                  name = SchemaConstants.C_VALUE;
                }
                PrismContext prismContext = ((PageBase) getPage()).getPrismContext();
                try {
                  return prismContext.serializeAnyData(ppv.getValue(), name, PrismContext.LANG_XML);
                } catch (SchemaException e) {
                  throw new SystemException(
                      "Couldn't serialize property value of type: "
                          + valueType
                          + ": "
                          + e.getMessage(),
                      e);
                }
              }
            },
            10);
      } else {
        Class type = XsdTypeMapper.getXsdToJavaMapping(valueType);
        if (type != null && type.isPrimitive()) {
          type = ClassUtils.primitiveToWrapper(type);
        }

        if (isEnum(property)) {
          return WebComponentUtil.createEnumPanel(
              definition, id, new PropertyModel<>(valueWrapperModel, 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 =
              WebModelServiceUtils.loadObject(
                  LookupTableType.class, lookupTableUid, options, pageBase, task, result);

          if (lookupTable != null) {

            panel =
                new AutoCompleteTextPanel<String>(
                    id,
                    new LookupPropertyModel<String>(
                        valueWrapperModel,
                        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>(valueWrapperModel, baseExpression), type);
          }

        } else {
          panel =
              new TextPanel<>(
                  id, new PropertyModel<String>(valueWrapperModel, baseExpression), type);
        }
      }
    } else if (item instanceof PrismReference) {
      PrismContext prismContext = item.getPrismContext();
      if (prismContext == null) {
        prismContext = pageBase.getPrismContext();
      }
      QName targetTypeName = ((PrismReferenceDefinition) item.getDefinition()).getTargetTypeName();
      Class targetClass = null;
      if (targetTypeName != null && prismContext != null) {
        targetClass = prismContext.getSchemaRegistry().determineCompileTimeClass(targetTypeName);
      }
      final Class typeClass =
          targetClass != null
              ? targetClass
              : (item.getDefinition().getTypeClassIfKnown() != null
                  ? item.getDefinition().getTypeClassIfKnown()
                  : FocusType.class);
      Collection typeClasses = new ArrayList();

      // HACK HACK MID-3201 MID-3231
      if (isUserOrgItem(item, typeClass)) {
        typeClasses.add(UserType.class);
        typeClasses.add(OrgType.class);
      } else {
        typeClasses.add(typeClass);
      }

      panel =
          new ValueChoosePanel(
              id,
              new PropertyModel<>(valueWrapperModel, "value"),
              item.getValues(),
              false,
              typeClasses);

    } else if (item instanceof PrismContainer<?>) {
      AssociationWrapper itemWrapper = (AssociationWrapper) valueWrapperModel.getObject().getItem();
      final PrismContainer container = (PrismContainer) item;
      PrismContainerDefinition definition = container.getDefinition();
      QName valueType = definition.getTypeName();

      if (ShadowAssociationType.COMPLEX_TYPE.equals(valueType)) {

        PrismContext prismContext = item.getPrismContext();
        if (prismContext == null) {
          prismContext = pageBase.getPrismContext();
        }

        ShadowType shadowType =
            ((ShadowType) itemWrapper.getContainer().getObject().getObject().asObjectable());
        PrismObject<ResourceType> resource = shadowType.getResource().asPrismObject();
        // 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(shadowType.asPrismObject());
        } catch (SchemaException e) {
          throw new SystemException(e.getMessage(), e);
        }
        RefinedAssociationDefinition assocDef = itemWrapper.getRefinedAssociationDefinition();
        RefinedObjectClassDefinition assocTargetDef = assocDef.getAssociationTarget();

        ObjectQuery query =
            getAssociationsSearchQuery(
                prismContext,
                resource,
                assocTargetDef.getTypeName(),
                assocTargetDef.getKind(),
                assocTargetDef.getIntent());

        List values = item.getValues();
        return new AssociationValueChoicePanel(
            id, valueWrapperModel, values, false, ShadowType.class, query, assocTargetDef);
      }
    }

    return panel;
  }
  @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;
  }
Exemple #14
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;
  }
  // 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;
  }
Exemple #16
0
 private boolean isUserOrgItem(Item item, Class referenceType) {
   return (referenceType == ObjectType.class || referenceType == FocusType.class)
       && (AbstractRoleType.F_APPROVER_REF.equals(item.getElementName())
           || AbstractRoleType.F_OWNER_REF.equals(item.getElementName()));
 }
 public <IV extends PrismValue, ID extends ItemDefinition> RootXNode serializeItemAsRoot(
     Item<IV, ID> item) throws SchemaException {
   Validate.notNull(item.getDefinition(), "Item without a definition");
   XNode valueNode = serializeItem(item);
   return new RootXNode(item.getDefinition().getName(), valueNode);
 }