Java Code Examples for org.jboss.dmr.ModelNode#equals()

The following examples show how to use org.jboss.dmr.ModelNode#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AttributeDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Finds a value in the given {@code operationObject} whose key matches this attribute's {@link #getName() name},
 * validates it using this attribute's {@link #getValidator() validator}, and, stores it under this attribute's name in the given {@code model}.
 *
 * @param operationObject model node of type {@link ModelType#OBJECT}, typically representing an operation request
 * @param model model node in which the value should be stored
 *
 * @throws OperationFailedException if the value is not valid
 */
public final void validateAndSet(ModelNode operationObject, final ModelNode model) throws OperationFailedException {
    if (operationObject.hasDefined(name) && deprecationData != null && deprecationData.isNotificationUseful()) {
        ControllerLogger.DEPRECATED_LOGGER.attributeDeprecated(getName(),
                PathAddress.pathAddress(operationObject.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString());
    }
    // AS7-6224 -- convert expression strings to ModelType.EXPRESSION *before* correcting
    ModelNode newValue = convertParameterExpressions(operationObject.get(name));
    final ModelNode correctedValue = correctValue(newValue, model.get(name));
    if (!correctedValue.equals(operationObject.get(name))) {
        operationObject.get(name).set(correctedValue);
    }
    ModelNode node = validateOperation(operationObject, true);
    if (node.getType() == ModelType.EXPRESSION
            && (referenceRecorder != null || flags.contains(AttributeAccess.Flag.EXPRESSIONS_DEPRECATED))) {
        ControllerLogger.DEPRECATED_LOGGER.attributeExpressionDeprecated(getName(),
            PathAddress.pathAddress(operationObject.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString());
    }
    model.get(name).set(node);
}
 
Example 2
Source File: PrimitiveListAttributeDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
static ModelNode parseSingleElementToList(AttributeDefinition ad, ModelNode original, ModelNode resolved) {
    ModelNode result = resolved;
    if (original.isDefined()
            && !resolved.equals(original)
            && resolved.getType() == ModelType.LIST
            && resolved.asInt() == 1) {
        // WFCORE-3448. We have a list with 1 element that is not the same as the defined original.
        // So that implies we had an expression as the element, which is what we would have gotten
        // if the expression string was passed by an xml parser to parseAndSetParameter. See if the
        // resolved form of that expression in turn parses to a list and if it does, used the parsed list.
        ModelNode element = resolved.get(0);
        if (element.getType() == ModelType.STRING) {
            ModelNode holder = new ModelNode();
            try {
                ad.getParser().parseAndSetParameter(ad, element.asString(), holder, null);
                ModelNode parsed = holder.get(ad.getName());
                if (parsed.getType() == ModelType.LIST && parsed.asInt() > 1) {
                    result = parsed;
                }
            } catch (XMLStreamException | RuntimeException e) {
                // ignore and just return the original value
            }
        }
    }
    return result;
}
 
Example 3
Source File: ObjectMapAttributeDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public ModelNode correct(ModelNode newValue, ModelNode currentValue) {
    ModelNode result = newValue;
    if (newValue.isDefined()) {
        for (String key : newValue.keys()) {
            ModelNode toCorrect = newValue.get(key);
            ModelNode corrected = valueCorrector.correct(toCorrect, currentValue.has(key) ? currentValue.get(key) : new ModelNode());
            if (!corrected.equals(toCorrect)) {
                toCorrect.set(corrected);
            }
        }
    }
    if (listCorrector != null) {
        result = listCorrector.correct(result, currentValue);
    }
    return result;
}
 
Example 4
Source File: ConfigMigrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void compareConfigs(String masterConfig, String migratedConfig) throws IOException {
    File masterFile = new File(TARGET_DIR, masterConfig);
    Assert.assertTrue(masterFile.exists());
    File migratedFile = new File(TARGET_DIR, migratedConfig);
    Assert.assertTrue(migratedFile.exists());
    
    try (
        FileInputStream masterStream = new FileInputStream(masterFile);
        FileInputStream migratedStream = new FileInputStream(migratedFile);
    ) {
        // Convert to ModelNode to test equality.
        // A textual diff might have things out of order.
        ModelNode master = ModelNode.fromStream(masterStream);
        ModelNode migrated = ModelNode.fromStream(migratedStream);

        if (master.equals(migrated)) {
            // ok
        } else {
            if (Boolean.parseBoolean(System.getProperty("get.simple.full.comparison"))) {
                assertThat(migrated, is(equalTo(master)));
            }
            compareConfigsDeeply("root", master, migrated);
        }
    } 
}
 
Example 5
Source File: DefaultDeploymentOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public Set<String> getUnrelatedDeployments(ModelNode owner) {
    final ModelNode op = Util.getEmptyOperation(READ_CHILDREN_RESOURCES_OPERATION, new ModelNode());
    op.get(CHILD_TYPE).set(DEPLOYMENT);
    ModelNode response = privilegedExecution().execute(controllerClient::execute, op);

    // Ensure the operation succeeded before we use the result
    if(response.get(OUTCOME).isDefined() && !SUCCESS.equals(response.get(OUTCOME).asString()))
       throw ROOT_LOGGER.deployModelOperationFailed(response.get(FAILURE_DESCRIPTION).asString());

    final ModelNode result = response.get(RESULT);
    final Set<String> deployments = new HashSet<String>();
    if (result.isDefined()) {
        for (Property property : result.asPropertyList()) {
            if(!owner.equals(property.getValue().get(OWNER))) {
                deployments.add(property.getName());
            }
        }
    }
    return deployments;
}
 
Example 6
Source File: ReadConfigAsFeaturesTestBase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected int getListElementIndex(ModelNode list, String spec, ModelNode id) {
    for (int i = 0; i < list.asList().size(); i++) {
        if (list.get(i).get(SPEC).asString().equals(spec) &&
                (id == null || id.equals(list.get(i).get(ID)))) {
            return i;
        }
    }
    throw new IllegalArgumentException("no element for spec " + spec + " and id " + ((id == null) ? "null" : id.toJSONString(true)));
}
 
Example 7
Source File: ElytronUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void addRealm(CommandContext ctx, SecurityDomain securityDomain, Realm realm, ModelNode steps) throws OperationFormatException {
    ModelNode realms = retrieveSecurityDomainRealms(ctx, securityDomain);
    ModelNode newRealm = buildRealmResource(realm);
    int index = 0;
    boolean found = false;
    for (ModelNode r : realms.asList()) {
        if (r.hasDefined(Util.REALM)) {
            String n = r.get(Util.REALM).asString();
            // Already present, skip....
            if (n.equals(realm.getResourceName())) {
                if (newRealm.equals(r)) {
                    return;
                }
                // We need to replace it with the new one.
                found = true;
                break;
            }
        }
        index += 1;
    }
    if (found) {
        realms.remove(index);
        realms.insert(newRealm, index);
    } else {
        realms.add(newRealm);
    }
    DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
    builder.setOperationName(Util.WRITE_ATTRIBUTE);
    builder.addNode(Util.SUBSYSTEM, Util.ELYTRON);
    builder.addNode(Util.SECURITY_DOMAIN, securityDomain.getName());
    builder.getModelNode().get(Util.VALUE).set(realms);
    builder.getModelNode().get(Util.NAME).set(Util.REALMS);
    steps.add(builder.buildRequest());
}
 
Example 8
Source File: WriteAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void emitAttributeValueWrittenNotification(OperationContext context, PathAddress address, String attributeName, ModelNode oldValue, ModelNode newValue) {
    // only emit a notification if the value has been successfully changed
    if (oldValue.equals(newValue)) {
        return;
    }
    ModelNode data = new ModelNode();
    data.get(NAME.getName()).set(attributeName);
    data.get(GlobalNotifications.OLD_VALUE).set(oldValue);
    data.get(GlobalNotifications.NEW_VALUE).set(newValue);
    Notification notification = new Notification(ATTRIBUTE_VALUE_WRITTEN_NOTIFICATION, address, ControllerLogger.ROOT_LOGGER.attributeValueWritten(attributeName, oldValue, newValue), data);
    context.emit(notification);
}
 
Example 9
Source File: DiscardAttributeChecker.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected boolean isValueDiscardable(PathAddress address, String attributeName, ModelNode attributeValue,
        TransformationContext context) {
    if (attributeValue.getType() != ModelType.EXPRESSION) {
        for (ModelNode value : values) {
            if (attributeValue.equals(value)){
                return true;
            }
        }
    }
    return false;
}
 
Example 10
Source File: DiscardAttributeChecker.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean isOperationParameterDiscardable(PathAddress address, String attributeName, ModelNode attributeValue, ModelNode operation, TransformationContext context) {
    String operationName = operation.get(ModelDescriptionConstants.OP).asString();
    if (operationName.equals(ModelDescriptionConstants.WRITE_ATTRIBUTE_OPERATION)) {
        return this.isResourceAttributeDiscardable(address, attributeName, attributeValue, context);
    }
    ImmutableManagementResourceRegistration registration = context.getResourceRegistrationFromRoot(PathAddress.EMPTY_ADDRESS);
    OperationDefinition definition = registration.getOperationEntry(address, operationName).getOperationDefinition();
    for (AttributeDefinition parameter : definition.getParameters()) {
        if (parameter.getName().equals(attributeName)) {
            return attributeValue.equals(parameter.getDefaultValue());
        }
    }
    return false;
}
 
Example 11
Source File: DomainIncludesValidationWriteAttributeHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void finishModelStage(OperationContext context, ModelNode operation, String attributeName, ModelNode newValue,
                                ModelNode oldValue, Resource model) throws OperationFailedException {
    super.finishModelStage(context, operation, attributeName, newValue, oldValue, model);
    if (newValue.equals(oldValue)) {
        //Set an attachment to avoid propagation to the servers, we don't want them to go into restart-required if nothing changed
        ServerOperationResolver.addToDontPropagateToServersAttachment(context, operation);
    }

    DomainModelIncludesValidator.addValidationStep(context, operation);
}
 
Example 12
Source File: FailedOperationTransformationConfig.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ModelNode correctOperation(ModelNode operation) {
    for (AttributesPathAddressConfig<?> link : list) {
        ModelNode op = link.correctOperation(operation);
        if (!op.equals(operation)) {
            return op;
        }
    }
    return operation;
}
 
Example 13
Source File: ListAttributeDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Iterates through the elements in the {@code parameter} list, calling {@link #convertParameterElementExpressions(ModelNode)}
 * for each.
 * <p>
 * <strong>Note</strong> that the default implementation of {@link #convertParameterElementExpressions(ModelNode)}
 * will only convert simple {@link ModelType#STRING} elements. If users need to handle complex elements
 * with embedded expressions, they should use a subclass that overrides that method.
 * </p>
 *
 * {@inheritDoc}
 */
@Override
protected ModelNode convertParameterExpressions(ModelNode parameter) {
    ModelNode result = parameter;

    List<ModelNode> asList;
    try {
        asList = parameter.asList();
    } catch (IllegalArgumentException iae) {
        // We can't convert; we'll just return parameter
        asList = null;
    }

    if (asList != null) {
        boolean changeMade = false;
        ModelNode newList = new ModelNode().setEmptyList();
        for (ModelNode item : asList) {
            ModelNode converted = convertParameterElementExpressions(item);
            newList.add(converted);
            changeMade |= !converted.equals(item);
        }
        if (changeMade) {
            result = newList;
        }
    }
    return result;
}
 
Example 14
Source File: AbstractOperationContext.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void createWarning(final Level level, final ModelNode warning){

        final ModelNode warningEntry = new ModelNode();
        warningEntry.get(WARNING).set(warning);
        warningEntry.get(LEVEL).set(level.toString());
        final ModelNode operation = activeStep.operation;
        if(operation != null){
            final ModelNode operationEntry =  warningEntry.get(OP);
            operationEntry.get(OP_ADDR).set(operation.get(OP_ADDR));
            operationEntry.get(OP).set(operation.get(OP));
        }

        final ModelNode warnings = getResponseHeaders().get(WARNINGS);
        boolean unique = true;
        if (warnings.isDefined()) {
            // Don't repeat a warning. This is basically a secondard safeguard
            // against different steps for the same op ending up reporting the
            // same warning. List iteration is not efficient but > 1 warning
            // in an op is an edge case
            for (ModelNode existing : warnings.asList()) {
                if (existing.equals(warningEntry)) {
                    unique = false;
                    break;
                }
            }
        }
        if (unique) {
            warnings.add(warningEntry);
        }
    }
 
Example 15
Source File: KeycloakSubsystemWriteAttributeHandler.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean attribNotChanging(String attributeName, ModelNode newValue, ModelNode oldValue) {
    AttributeDefinition attribDef = KeycloakSubsystemDefinition.lookup(attributeName);
    if (!oldValue.isDefined()) {
        oldValue = attribDef.getDefaultValue();
    }
    if (!newValue.isDefined()) {
        newValue = attribDef.getDefaultValue();
    }
    return newValue.equals(oldValue);
}
 
Example 16
Source File: ReadConfigAsFeaturesTestBase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This is the entry-point for the {@code ModelNode} comparison, eschewing list order.
 */
protected boolean equalsWithoutListOrder(ModelNode model1, ModelNode model2) {
    if (!model1.getType().equals(model2.getType())) {
        return false;
    }

    switch (model1.getType()) {
        case OBJECT:
            return compareObjects(model1, model2);
        case LIST:
            return compareLists(model1, model2);
        default:
            return model1.equals(model2);
    }
}
 
Example 17
Source File: ReadConfigAsFeaturesTestBase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected ModelNode getListElement(ModelNode list, String spec, ModelNode id) {
    for (ModelNode element : list.asList()) {
        if (element.get(SPEC).asString().equals(spec) &&
                (id == null || id.equals(element.get(ID)))) {
            return element;
        }
    }

    throw new IllegalArgumentException("no element for spec " + spec + " and id " + ((id == null) ? "null" : id.toJSONString(true)));
}
 
Example 18
Source File: ConfigMigrationTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void compareConfigsDeeply(String id, ModelNode master, ModelNode migrated) {
    nav.add(id);
    
    master.protect();
    migrated.protect();

    assertEquals(getMessage(), master.getType(), migrated.getType());
    
    switch (master.getType()) {
        case OBJECT:
            //check nodes are equal
            if (master.equals(migrated)) {
                break;
            }
            //check keys are equal
            assertThat(getMessage(), migrated.keys(), is(equalTo(master.keys())));

            for (String key : master.keys()) {
                compareConfigsDeeply(key, master.get(key), migrated.get(key));
            }
            break;
        case LIST:
            List<ModelNode> masterAsList = new ArrayList<>(master.asList());
            List<ModelNode> migratedAsList = new ArrayList<>(migrated.asList());
            
            if (masterAsList.equals(migratedAsList)) {
                break;
            }
            
            masterAsList.sort(nodeStringComparator);
            migratedAsList.sort(nodeStringComparator);
            
            if (masterAsList.toString().contains("subsystem")) {
                assertEquals("Subsystem names are not equal.", 
                        getSubsystemNames(masterAsList).toString(), 
                        getSubsystemNames(migratedAsList).toString());
            }

            //remove equaled nodes and keep just different ones
            List<ModelNode> diffNodesInMaster = new ArrayList<>(masterAsList);
            diffNodesInMaster.removeAll(migratedAsList);
            for (ModelNode diffNodeInMaster : diffNodesInMaster) {
                String navigation = diffNodeInMaster.getType().toString();
                if (diffNodeInMaster.toString().contains("subsystem")) {
                    navigation = getSubsystemNames(Arrays.asList(diffNodeInMaster)).toString();
                } 
                compareConfigsDeeply(navigation, 
                        diffNodeInMaster, 
                        migratedAsList.get(masterAsList.indexOf(diffNodeInMaster)));
            }
            break;
        case BOOLEAN:
            assertEquals(getMessage(), master.asBoolean(), migrated.asBoolean());
            break;
        case STRING:
            assertEquals(getMessage(), master.asString(), migrated.asString());
            break;
        case UNDEFINED:
            //nothing to test
            break;
        case LONG:
            assertEquals(getMessage(), master.asLong(), migrated.asLong());
            break;
        case EXPRESSION:
            assertEquals(getMessage(), master.asExpression(), migrated.asExpression());
            break;
        case INT:
            assertEquals(getMessage(), master.asInt(), migrated.asInt());
            break;
        case DOUBLE:
            assertEquals(getMessage(), master.asDouble(), migrated.asDouble(), new Double("0.0"));
            break;
        default:
            assertThat(getMessage(), migrated, is(equalTo(master)));
            throw new UnsupportedOperationException(getMessage() + ". There is missing case " + master.getType().name());
    }
    nav.pollLast();
}
 
Example 19
Source File: DiscardAttributeChecker.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public boolean isResourceAttributeDiscardable(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) {
    ImmutableManagementResourceRegistration registration = context.getResourceRegistrationFromRoot(PathAddress.EMPTY_ADDRESS);
    AttributeDefinition definition = registration.getAttributeAccess(address, attributeName).getAttributeDefinition();
    return attributeValue.equals(definition.getDefaultValue());
}
 
Example 20
Source File: QueryOperationHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static boolean matchesFilter(final ModelNode resource, final ModelNode filter, final Operator operator) throws OperationFailedException {
    boolean isMatching = false;
    List<Property> filterProperties = filter.asPropertyList();
    List<Boolean> matches = new ArrayList<>(filterProperties.size());

    for (Property property : filterProperties) {

        final String filterName = property.getName();
        final ModelNode filterValue = property.getValue();

        boolean isEqual = false;

        if(!filterValue.isDefined() || filterValue.asString().equals(UNDEFINED))  {
            // query for undefined attributes
            isEqual = !resource.get(filterName).isDefined();
        }  else {

            final ModelType targetValueType = resource.get(filterName).getType();

            try {
                // query for attribute values (throws exception when types don't match)
                switch (targetValueType) {
                    case BOOLEAN:
                        isEqual = filterValue.asBoolean() == resource.get(filterName).asBoolean();
                        break;
                    case LONG:
                        isEqual = filterValue.asLong() == resource.get(filterName).asLong();
                        break;
                    case INT:
                        isEqual = filterValue.asInt() == resource.get(filterName).asInt();
                        break;
                    case DOUBLE:
                        isEqual = filterValue.asDouble() == resource.get(filterName).asDouble();
                        break;
                    default:
                        isEqual = filterValue.equals(resource.get(filterName));
                }
            } catch (IllegalArgumentException e) {
                throw ControllerLogger.MGMT_OP_LOGGER.selectFailedCouldNotConvertAttributeToType(filterName, targetValueType);
            }

        }

        if(isEqual) {
            matches.add(resource.get(filterName).equals(filterValue));
        }

    }

    if (Operator.AND.equals(operator)) {
        // all matches must be true
        isMatching = matches.size() == filterProperties.size();

    } else if(Operator.OR.equals(operator)){
        // at least one match must be true
        for (Boolean match : matches) {
            if (match) {
                isMatching = true;
                break;
            }
        }
    }
    else {
        // This is just to catch programming errors where a new case isn't added above
        throw new IllegalArgumentException(
                ControllerLogger.MGMT_OP_LOGGER.invalidValue(
                        operator.toString(),
                        OPERATOR,
                        Arrays.asList(Operator.values())
                )
        );
    }


    return isMatching;
}