Search in sources :

Example 1 with ValidationFailure

use of org.openremote.model.ValidationFailure in project openremote by openremote.

the class KNXProtocol method validateProtocolConfiguration.

@Override
public AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration) {
    AttributeValidationResult result = super.validateProtocolConfiguration(protocolConfiguration);
    if (result.isValid()) {
        boolean ipFound = false;
        if (protocolConfiguration.getMeta() != null && !protocolConfiguration.getMeta().isEmpty()) {
            for (int i = 0; i < protocolConfiguration.getMeta().size(); i++) {
                MetaItem actionMetaItem = protocolConfiguration.getMeta().get(i);
                if (isMetaNameEqualTo(actionMetaItem, META_KNX_IP_CONNECTION_TYPE)) {
                    String connectionType = actionMetaItem.getValueAsString().orElse("TUNNELLING");
                    if (!connectionType.equals("TUNNELLING") && !connectionType.equals("ROUTING")) {
                        result.addMetaFailure(new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_MISMATCH, PATTERN_FAILURE_CONNECTION_TYPE));
                    }
                    ipFound = "ROUTING".equals(connectionType);
                } else if (isMetaNameEqualTo(actionMetaItem, META_KNX_GATEWAY_IP)) {
                    ipFound = true;
                    if (isNullOrEmpty(actionMetaItem.getValueAsString().orElse(null))) {
                        result.addMetaFailure(new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED, ValueType.STRING.name()));
                    }
                }
            }
        }
        if (!ipFound) {
            result.addMetaFailure(new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, META_KNX_GATEWAY_IP));
        }
    }
    return result;
}
Also used : Datapoint(tuwien.auto.calimero.datapoint.Datapoint) ValidationFailure(org.openremote.model.ValidationFailure)

Example 2 with ValidationFailure

use of org.openremote.model.ValidationFailure in project openremote by openremote.

the class AssetStorageService method merge.

/**
 * @param overrideVersion If <code>true</code>, the merge will override the data in the database, independent of version.
 * @param userName        the user which this asset needs to be assigned to.
 * @return The current stored asset state.
 * @throws IllegalArgumentException if the realm or parent is illegal, or other asset constraint is violated.
 */
public ServerAsset merge(ServerAsset asset, boolean overrideVersion, String userName) {
    return persistenceService.doReturningTransaction(em -> {
        // Update all empty attribute timestamps with server-time (a caller which doesn't have a
        // reliable time source such as a browser should clear the timestamp when setting an attribute
        // value).
        asset.getAttributesStream().forEach(attribute -> {
            Optional<Long> timestamp = attribute.getValueTimestamp();
            if (!timestamp.isPresent() || timestamp.get() <= 0) {
                attribute.setValueTimestamp(timerService.getCurrentTimeMillis());
            }
        });
        // Validate parent
        if (asset.getParentId() != null) {
            // If this is a not a root asset...
            ServerAsset parent = find(em, asset.getParentId(), true);
            // .. the parent must exist
            if (parent == null)
                throw new IllegalStateException("Parent not found: " + asset.getParentId());
            // ... the parent can not be a child of the asset
            if (parent.pathContains(asset.getId()))
                throw new IllegalStateException("Invalid parent");
            // .. the parent should be in the same realm
            if (asset.getRealmId() != null && !parent.getRealmId().equals(asset.getRealmId())) {
                throw new IllegalStateException("Parent not in same realm as asset: " + asset.getRealmId());
            } else if (asset.getRealmId() == null) {
                // ... and if we don't have a realm identifier, use the parent's
                asset.setRealmId(parent.getRealmId());
            }
        }
        // Validate realm
        if (!identityService.getIdentityProvider().isActiveTenant(asset.getRealmId())) {
            throw new IllegalStateException("Realm not found/active: " + asset.getRealmId());
        }
        // Validate attributes
        int invalid = 0;
        for (AssetAttribute attribute : asset.getAttributesList()) {
            List<ValidationFailure> validationFailures = attribute.getValidationFailures();
            if (!validationFailures.isEmpty()) {
                LOG.warning("Validation failure(s) " + validationFailures + ", can't store: " + attribute);
                invalid++;
            }
        }
        if (invalid > 0) {
            throw new IllegalStateException("Storing asset failed, invalid attributes: " + invalid);
        }
        // concurrent updates
        if (asset.getId() != null && overrideVersion) {
            ServerAsset existing = em.find(ServerAsset.class, asset.getId());
            if (existing != null) {
                asset.setVersion(existing.getVersion());
            }
        }
        // If username present
        User user = null;
        if (!TextUtil.isNullOrEmpty(userName)) {
            user = identityService.getIdentityProvider().getUser(asset.getRealmId(), userName);
            if (user == null) {
                throw new IllegalStateException("User not found: " + userName);
            }
        }
        LOG.fine("Storing: " + asset);
        ServerAsset updatedAsset = em.merge(asset);
        if (user != null) {
            storeUserAsset(em, new UserAsset(user.getRealmId(), user.getId(), updatedAsset.getId()));
        }
        return updatedAsset;
    });
}
Also used : User(org.openremote.model.security.User) Point(com.vividsolutions.jts.geom.Point) ValidationFailure(org.openremote.model.ValidationFailure)

Example 3 with ValidationFailure

use of org.openremote.model.ValidationFailure in project openremote by openremote.

the class MetaItem method getValidationFailures.

public List<ValidationFailure> getValidationFailures(Optional<MetaItemDescriptor> metaItemDescriptor) {
    List<ValidationFailure> failures = super.getValidationFailures();
    // Check name
    if (!getName().isPresent())
        failures.add(new ValidationFailure(META_ITEM_NAME_IS_REQUIRED));
    // MetaItemDescriptor validation takes priority
    metaItemDescriptor.ifPresent(descriptor -> descriptor.getValidator().map(validator -> validator.apply(getValue().orElse(null)).map(failures::add).orElse(true)).orElseGet(() -> {
        if (!getValue().isPresent()) {
            failures.add(new ValidationFailure(META_ITEM_VALUE_IS_REQUIRED, descriptor.getValueType().name()));
        }
        if (getValue().map(Value::getType).map(type -> descriptor.getValueType() != type).orElse(true)) {
            failures.add(new ValidationFailure(META_ITEM_VALUE_MISMATCH, descriptor.getValueType().name()));
            return true;
        }
        if (getValue().isPresent() && !isNullOrEmpty(descriptor.getPattern())) {
            String valueStr = getValue().get().toString();
            if (isNullOrEmpty(valueStr)) {
                failures.add(new ValidationFailure(MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED, descriptor.getValueType().name()));
                return true;
            }
            // Do case insensitive regex (can't include this flag in the pattern like in normal java)
            if (!RegExp.compile(descriptor.getPattern(), "i").test(valueStr)) {
                failures.add(new ValidationFailure(MetaItemFailureReason.META_ITEM_VALUE_MISMATCH, descriptor.getPatternFailureMessage()));
                return true;
            }
        }
        // Here because Optional doesn't support ifAbsent
        return true;
    }));
    if (!metaItemDescriptor.isPresent() && !getValue().isPresent()) {
        failures.add(new ValidationFailure(META_ITEM_VALUE_IS_REQUIRED));
    }
    return failures;
}
Also used : ValidationFailure(org.openremote.model.ValidationFailure)

Example 4 with ValidationFailure

use of org.openremote.model.ValidationFailure in project openremote by openremote.

the class MetaEditor method addItem.

protected boolean addItem(MetaItem item, boolean viewOnly) {
    if (!viewOnly) {
        MetaItemDescriptor[] descriptor = new MetaItemDescriptor[1];
        // Check item can be added
        boolean canAdd = Arrays.stream(metaItemDescriptors).filter(metaItemDescriptor -> metaItemDescriptor.getUrn().equals(item.getName().orElse(null))).findFirst().map(metaItemDescriptor -> {
            descriptor[0] = metaItemDescriptor;
            return metaItemDescriptor.getMaxPerAttribute();
        }).map(maxCount -> attribute.getMeta().stream().filter(metaItem -> metaItem.getName().map(name -> name.equals(item.getName().orElse(null))).orElse(false)).count() < maxCount).orElse(true);
        if (!canAdd) {
            showValidationError(attribute.getName().orElse(""), null, new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_DUPLICATION, getMetaItemDisplayName(environment, descriptor[0].name())));
            return false;
        }
        attribute.getMeta().add(item);
        // Notify the presenter that the attribute has changed
        notifyAttributeModified();
    }
    int index = itemListPanel.getWidgetCount();
    MetaItemEditor metaItemEditor = createMetaItemEditor(item, false);
    itemListPanel.add(metaItemEditor);
    setLabelVisible(itemListPanel.getWidgetCount() > 0);
    // Check if we have a validation failure for this editor
    if (lastValidationResult != null && lastValidationResult.getMetaFailures() != null) {
        List<ValidationFailure> failures = lastValidationResult.getMetaFailures().get(index);
        if (failures != null && !failures.isEmpty()) {
            metaItemEditor.setError(true);
        }
    }
    return true;
}
Also used : IntStream(java.util.stream.IntStream) Supplier(org.openremote.model.interop.Supplier) java.util(java.util) ValueType(org.openremote.model.value.ValueType) Environment(org.openremote.app.client.Environment) MetaItemDescriptor(org.openremote.model.attribute.MetaItemDescriptor) Pair(org.openremote.model.util.Pair) EnumUtil(org.openremote.model.util.EnumUtil) ValidationFailure(org.openremote.model.ValidationFailure) org.openremote.app.client.widget(org.openremote.app.client.widget) Collectors(java.util.stream.Collectors) AssetMeta(org.openremote.model.asset.AssetMeta) AttributeValidationResult(org.openremote.model.attribute.AttributeValidationResult) MetaItem(org.openremote.model.attribute.MetaItem) AgentLink(org.openremote.model.asset.agent.AgentLink) Value(org.openremote.model.value.Value) FlowPanel(com.google.gwt.user.client.ui.FlowPanel) ProtocolDescriptor(org.openremote.model.asset.agent.ProtocolDescriptor) IsWidget(com.google.gwt.user.client.ui.IsWidget) Values(org.openremote.model.value.Values) TextUtil.isNullOrEmpty(org.openremote.model.util.TextUtil.isNullOrEmpty) AssetAttribute(org.openremote.model.asset.AssetAttribute) MetaItemDescriptor(org.openremote.model.attribute.MetaItemDescriptor) ValidationFailure(org.openremote.model.ValidationFailure)

Example 5 with ValidationFailure

use of org.openremote.model.ValidationFailure in project openremote by openremote.

the class MetaEditor method showMetaItemFailure.

protected void showMetaItemFailure(MetaItemEditor metaItemEditor, List<ValidationFailure> failures) {
    if (failures != null) {
        Optional<MetaItemDescriptor> optionalMetaItemDescriptor = metaItemEditor.getCurrentDescriptor();
        String displayName = optionalMetaItemDescriptor.map(metaItemDescriptor -> getMetaItemDisplayName(environment, metaItemDescriptor.name())).orElse(metaItemEditor.getItem().getName().orElse(""));
        failures.forEach(failure -> {
            if (failure.getReason() == MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED) {
                // Substitute in value type info
                String parameter = EnumUtil.enumFromString(ValueType.class, metaItemEditor.getTypeList().getSelectedValue()).map(Enum::name).orElse("Value");
                failure = new ValidationFailure(failure.getReason(), parameter);
            }
            showValidationError(attribute.getName().orElse(""), displayName, failure);
        });
    }
}
Also used : IntStream(java.util.stream.IntStream) Supplier(org.openremote.model.interop.Supplier) java.util(java.util) ValueType(org.openremote.model.value.ValueType) Environment(org.openremote.app.client.Environment) MetaItemDescriptor(org.openremote.model.attribute.MetaItemDescriptor) Pair(org.openremote.model.util.Pair) EnumUtil(org.openremote.model.util.EnumUtil) ValidationFailure(org.openremote.model.ValidationFailure) org.openremote.app.client.widget(org.openremote.app.client.widget) Collectors(java.util.stream.Collectors) AssetMeta(org.openremote.model.asset.AssetMeta) AttributeValidationResult(org.openremote.model.attribute.AttributeValidationResult) MetaItem(org.openremote.model.attribute.MetaItem) AgentLink(org.openremote.model.asset.agent.AgentLink) Value(org.openremote.model.value.Value) FlowPanel(com.google.gwt.user.client.ui.FlowPanel) ProtocolDescriptor(org.openremote.model.asset.agent.ProtocolDescriptor) IsWidget(com.google.gwt.user.client.ui.IsWidget) Values(org.openremote.model.value.Values) TextUtil.isNullOrEmpty(org.openremote.model.util.TextUtil.isNullOrEmpty) AssetAttribute(org.openremote.model.asset.AssetAttribute) MetaItemDescriptor(org.openremote.model.attribute.MetaItemDescriptor) ValidationFailure(org.openremote.model.ValidationFailure)

Aggregations

ValidationFailure (org.openremote.model.ValidationFailure)15 MetaItem (org.openremote.model.attribute.MetaItem)6 Value (org.openremote.model.value.Value)5 AssetAttribute (org.openremote.model.asset.AssetAttribute)4 IsWidget (com.google.gwt.user.client.ui.IsWidget)3 java.util (java.util)3 Collectors (java.util.stream.Collectors)3 Environment (org.openremote.app.client.Environment)3 org.openremote.app.client.widget (org.openremote.app.client.widget)3 SimulatorElement (org.openremote.model.simulator.SimulatorElement)3 FlowPanel (com.google.gwt.user.client.ui.FlowPanel)2 IntStream (java.util.stream.IntStream)2 AssetMeta (org.openremote.model.asset.AssetMeta)2 AgentLink (org.openremote.model.asset.agent.AgentLink)2 ProtocolDescriptor (org.openremote.model.asset.agent.ProtocolDescriptor)2 AttributeValidationResult (org.openremote.model.attribute.AttributeValidationResult)2 MetaItemDescriptor (org.openremote.model.attribute.MetaItemDescriptor)2 Supplier (org.openremote.model.interop.Supplier)2 ColorSimulatorElement (org.openremote.model.simulator.element.ColorSimulatorElement)2 NumberSimulatorElement (org.openremote.model.simulator.element.NumberSimulatorElement)2