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

The following examples show how to use org.jboss.dmr.ModelNode#asPropertyList() . 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: 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 2
Source File: Address.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
/**
 * Obtains the address from the given ModelNode which is assumed to be a property list that
 * contains all the address parts and only the address parts.
 *
 * @param node address node
 * @return the address
 */
public static Address fromModelNode(ModelNode node) {
    // Rather than just store node as this.addressNode, we want to make sure it can be used as a valid address.
    // This also builds our own instance of ModelNode rather than use the one the caller gave us.
    Address address = Address.root();

    // if the node is not defined, this simply represents the root address
    if (!node.isDefined()) {
        return address;
    }

    try {
        List<Property> addressList = node.asPropertyList();
        for (Property addressProperty : addressList) {
            String resourceType = addressProperty.getName();
            String resourceName = addressProperty.getValue().asString();
            address.add(resourceType, resourceName);
        }
        return address;
    } catch (Exception e) {
        throw new IllegalArgumentException("Node cannot be used as an address: " + node.toJSONString(true));
    }
}
 
Example 3
Source File: ArgumentValueParsingTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testPropertyListInBrackets() throws Exception {
    final ModelNode value = parse("[a=b,c=d]");
    assertNotNull(value);
    assertEquals(ModelType.LIST, value.getType());
    final List<Property> list = value.asPropertyList();
    assertEquals(2, list.size());
    Property prop = list.get(0);
    assertNotNull(prop);
    assertEquals("a", prop.getName());
    assertEquals("b", prop.getValue().asString());
    prop = list.get(1);
    assertNotNull(prop);
    assertEquals("c", prop.getName());
    assertEquals("d", prop.getValue().asString());
}
 
Example 4
Source File: HostControllerRegistrationHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Create the transformers. This will remotely resolve the subsystem versions.
 *
 * @param extensions the extensions
 * @throws OperationFailedException
 */
private void processSubsystems(final Transformers transformers, final ModelNode extensions) throws OperationFailedException {
    this.transformers = transformers;
    final ModelNode subsystems = executeBlocking(new IOTask<ModelNode>() {
        @Override
        void sendMessage(FlushableDataOutput output) throws IOException {
            sendResponse(output, DomainControllerProtocol.PARAM_OK, extensions);
        }
    });
    if(failed) {
        throw new OperationFailedException("failed to setup transformers");
    }
    final TransformationTarget target = transformers.getTarget();
    for(final Property subsystem : subsystems.asPropertyList()) {
        final String subsystemName = subsystem.getName();
        final ModelNode version = subsystem.getValue();
        target.addSubsystemVersion(subsystemName, ModelVersion.fromString(version.asString()));
    }
}
 
Example 5
Source File: FilterConversionTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Removes undefined attributes from the model.
 *
 * @param model the model to remove undefined attributes from
 *
 * @return the new model
 */
static ModelNode removeUndefined(final ModelNode model) {
    final ModelNode result = new ModelNode();
    if (model.getType() == ModelType.OBJECT) {
        for (Property property : model.asPropertyList()) {
            final ModelNode value = property.getValue();
            if (value.isDefined()) {
                if (value.getType() == ModelType.OBJECT) {
                    final ModelNode m = removeUndefined(property.getValue());
                    if (m.isDefined()) {
                        result.get(property.getName()).set(m);
                    }
                } else {
                    result.get(property.getName()).set(value);
                }
            }
        }
    }
    return result;
}
 
Example 6
Source File: ReadFeatureDescriptionHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addOpParam(ModelNode annotation, ModelNode requestProperties, Map<String, String> featureParamMappings) {
        if (!requestProperties.isDefined()) {
            return;
        }
        List<Property> request = requestProperties.asPropertyList();
        StringJoiner params = new StringJoiner(",");
        StringJoiner paramMappings = new StringJoiner(",");
        boolean keepMapping = false;
        for (Property att : request) {
//            if(isDeprecated(att.getValue())) {
//                continue;
//            }
            String realName = att.getName();
            if (featureParamMappings.containsKey(realName)) {
                keepMapping = true;
                params.add(featureParamMappings.get(realName));
            } else {
                params.add(realName);
            }
            paramMappings.add(realName);
        }
        if (keepMapping) {
            annotation.get(OP_PARAMS_MAPPING).set(paramMappings.toString());
        }
        annotation.get(OP_PARAMS).set(params.toString());
    }
 
Example 7
Source File: DiscoveryOptionsResource.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected Resource getOption(String type, String name) {
    final ModelNode options = delegate.getModel().get(ModelDescriptionConstants.OPTIONS);
    if (!options.isDefined()) {
        return null;
    }
    final boolean staticOption = ModelDescriptionConstants.STATIC_DISCOVERY.equals(type);
    for (Property prop : options.asPropertyList()) {
        if (staticOption) {
            if (prop.getName().equals(ModelDescriptionConstants.STATIC_DISCOVERY)
                    && prop.getValue().has(ModelDescriptionConstants.NAME)
                    && prop.getValue().get(ModelDescriptionConstants.NAME).asString().equals(name)) {
                return getResource(prop);
            }
        } else if (prop.getName().equals(ModelDescriptionConstants.CUSTOM_DISCOVERY) && prop.getValue().has(ModelDescriptionConstants.NAME)
                && prop.getValue().get(ModelDescriptionConstants.NAME).asString().equals(name)) {
            return getResource(prop);
        }
    }
    return null;
}
 
Example 8
Source File: ManagementVersionTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testExtensions() throws Exception {
    ModelNode op = createOpNode(null, "read-children-resources");
    op.get("child-type").set("extension");
    op.get("recursive").set(true);
    op.get("include-runtime").set(true);

    ModelNode result = executeOperation(op);
    for (Property extension : result.asPropertyList()) {
        String extensionName = extension.getName();
        ModelNode subsystems = extension.getValue().get("subsystem");
        Assert.assertEquals(extensionName + " has no subsystems", ModelType.OBJECT, subsystems.getType());
        for (Property subsystem : subsystems.asPropertyList()) {
            String subsystemName = subsystem.getName();
            ModelNode value = subsystem.getValue();
            Assert.assertEquals(subsystemName + " has major version", ModelType.INT, value.get("management-major-version").getType());
            Assert.assertEquals(subsystemName + " has minor version", ModelType.INT, value.get("management-minor-version").getType());
            Assert.assertEquals(subsystemName + " has micro version", ModelType.INT, value.get("management-micro-version").getType());
            Assert.assertEquals(subsystemName + " has namespaces", ModelType.LIST, value.get("xml-namespaces").getType());
            Assert.assertTrue(subsystemName + " has positive major version", value.get("management-major-version").asInt() > 0);
            Assert.assertTrue(subsystemName + " has positive minor version", value.get("management-minor-version").asInt() >= 0);
            Assert.assertTrue(subsystemName + " has positive micro version", value.get("management-micro-version").asInt() >= 0);
            Assert.assertTrue(subsystemName + " has more than zero namespaces", value.get("xml-namespaces").asInt() > 0);
        }
    }
}
 
Example 9
Source File: ManagedServerOperationsFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addNamespaces(Map<String, ModelNode> map, ModelNode namespaces) {
    if (namespaces.isDefined()) {
        for (Property prop : namespaces.asPropertyList()) {
            map.put(prop.getName(), NamespaceAddHandler.getAddNamespaceOperation(EMPTY, prop.getName(), prop.getValue().asString()));
        }
    }
}
 
Example 10
Source File: AuthorizedAddress.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static AuthorizedAddress authorizeAddress(OperationContext context, ModelNode operation) {
    ModelNode address = operation.get(ModelDescriptionConstants.OP_ADDR);
    ModelNode testOp = new ModelNode();
    testOp.get(OP).set(READ_RESOURCE_OPERATION);
    testOp.get(OP_ADDR).set(address);

    AuthorizationResult authResult = context.authorize(testOp, ADDRESS_EFFECT);
    if (authResult.getDecision() == AuthorizationResult.Decision.PERMIT) {
        return new AuthorizedAddress(address, false);
    }

    // Failed. Now we need to see how far we can go
    ModelNode partialAddress = new ModelNode().setEmptyList();
    ModelNode elidedAddress = new ModelNode().setEmptyList();
    for (Property prop : address.asPropertyList()) {
        partialAddress.add(prop);
        testOp.get(OP_ADDR).set(partialAddress);
        authResult = context.authorize(testOp, ADDRESS_EFFECT);
        if (authResult.getDecision() == AuthorizationResult.Decision.DENY) {
            elidedAddress.add(prop.getName(), HIDDEN);
            return new AuthorizedAddress(elidedAddress, true);
        } else {
            elidedAddress.add(prop);
        }
    }

    // Should not be reachable, but in case of a bug, be conservative and hide data
    ModelNode strange = new ModelNode();
    strange.add(HIDDEN, HIDDEN);
    return new AuthorizedAddress(strange, true);
}
 
Example 11
Source File: OperationTimeoutTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String findActiveOperation(DomainClient client, PathAddress address, String opName, OperationContext.ExecutionStatus targetStatus, long executionStart, boolean serverOpOnly) throws Exception {
    ModelNode op = Util.createEmptyOperation(READ_CHILDREN_RESOURCES_OPERATION, address);
    op.get(CHILD_TYPE).set(ACTIVE_OPERATION);
    long maxTime = TimeoutUtil.adjust(5000);
    long timeout = executionStart + maxTime;
    List<String> activeOps = new ArrayList<String>();
    String opToCancel = null;
    do {
        activeOps.clear();
        ModelNode result = executeForResult(op, client);
        if (result.isDefined()) {
            assertEquals(result.asString(), ModelType.OBJECT, result.getType());
            for (Property prop : result.asPropertyList()) {
                if (prop.getValue().get(OP).asString().equals(opName)) {
                    PathAddress pa = PathAddress.pathAddress(prop.getValue().get(OP_ADDR));
                    if (!serverOpOnly || pa.size() > 2 && pa.getElement(1).getKey().equals(SERVER)) {
                        activeOps.add(prop.getName() + " -- " + prop.getValue().toString());
                        if (targetStatus == null || prop.getValue().get(EXECUTION_STATUS).asString().equals(targetStatus.toString())) {
                            opToCancel = prop.getName();
                        }
                    }
                }
            }
        }
        if (opToCancel == null) {
            Thread.sleep(50);
        }

    } while ((opToCancel == null || activeOps.size() > 1) && System.currentTimeMillis() <= timeout);

    assertTrue(opName + " not present after " + maxTime + " ms", activeOps.size() > 0);
    assertEquals("Multiple instances of " + opName + " present: " + activeOps, 1, activeOps.size());
    assertNotNull(opName + " not in status " + targetStatus + " after " + maxTime + " ms", opToCancel);

    return opToCancel;
}
 
Example 12
Source File: IgnoredNonAffectedServerGroupsUtil.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Set<ServerConfigInfo> createConfigsFromModel(final ModelNode model) {
    final Set<ServerConfigInfo> serverConfigs = new HashSet<>();
    ModelNode initialServerGroups = model.get(INITIAL_SERVER_GROUPS);
    for (Property prop : initialServerGroups.asPropertyList()) {
        final List<ModelNode> servers = prop.getValue().asList();
        for (ModelNode server : servers) {
            final String socketBindingGroupOverride = server.hasDefined(SOCKET_BINDING_GROUP) ? server.get(SOCKET_BINDING_GROUP).asString() : null;
            final ServerConfigInfo serverConfigInfo = IgnoredNonAffectedServerGroupsUtil.createServerConfigInfo(prop.getValue().get(GROUP).asString(), socketBindingGroupOverride);
            serverConfigs.add(serverConfigInfo);
        }
    }
    return serverConfigs;
}
 
Example 13
Source File: ReadFeatureDescriptionTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static int validateFeature(ModelNode feature, String expectedName, int maxChildDepth, int featureDepth) {
    int highestDepth = featureDepth;
    for (Property prop : feature.asPropertyList()) {
        switch (prop.getName()) {
            case NAME:
                if (expectedName != null) {
                    Assert.assertEquals(feature.toString(), expectedName, prop.getValue().asString());
                }
                break;
            case CHILDREN:
                if (prop.getValue().isDefined()) {
                    Assert.assertTrue(feature.toString(), maxChildDepth > 0);
                    for (Property child : prop.getValue().asPropertyList()) {
                        int treeDepth = validateFeature(child.getValue(), child.getName(),
                                maxChildDepth - 1, featureDepth + 1);
                        highestDepth = Math.max(highestDepth, treeDepth);
                    }
                }
                break;
            case ANNOTATION:
            case "params":
            case "refs":
            case "provides":
            case "requires":
            case "packages":
                // all ok; no other validation right now
                break;
            default:
                Assert.fail("Unknown key " + prop.getName() + " in " + feature.toString());
        }
    }
    return highestDepth;
}
 
Example 14
Source File: PropertyAttributeMarshaller.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void marshallAsElement(AttributeDefinition attribute, ModelNode resourceModel, boolean marshallDefault, XMLStreamWriter writer) throws XMLStreamException {
    resourceModel = resourceModel.get(attribute.getName());
    if (resourceModel.isDefined()) {
        writer.writeStartElement(attribute.getName());
        for (Property property : resourceModel.asPropertyList()) {
            writer.writeEmptyElement(Element.PROPERTY.getLocalName());
            writer.writeAttribute(Attribute.NAME.getLocalName(), property.getName());
            writer.writeAttribute(Attribute.VALUE.getLocalName(), property.getValue().asString());
        }
        writer.writeEndElement();
    }
}
 
Example 15
Source File: ManagedServerOperationsFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addSchemaLocations(Map<String, ModelNode> map, ModelNode namespaces) {
    if (namespaces.isDefined()) {
        for (Property prop : namespaces.asPropertyList()) {
            map.put(prop.getName(), SchemaLocationAddHandler.getAddSchemaLocationOperation(EMPTY, prop.getName(), prop.getValue().asString()));
        }
    }
}
 
Example 16
Source File: AccessControlXml.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void writeServerGroupScopedRoles(XMLExtendedStreamWriter writer, ModelNode scopedRoles) throws XMLStreamException {
    writer.writeStartElement(Element.SERVER_GROUP_SCOPED_ROLES.getLocalName());

    for (Property property : scopedRoles.asPropertyList()) {
        writer.writeStartElement(Element.ROLE.getLocalName());
        writer.writeAttribute(Attribute.NAME.getLocalName(), property.getName());
        ModelNode value = property.getValue();
        ServerGroupScopedRoleResourceDefinition.BASE_ROLE.marshallAsAttribute(value, writer);
        ServerGroupScopedRoleResourceDefinition.SERVER_GROUPS.marshallAsElement(value, writer);
        writer.writeEndElement();
    }
    writer.writeEndElement();
}
 
Example 17
Source File: BpmPlatformParser.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void writeProcessEnginesContent(final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context) throws XMLStreamException {
  
  writer.writeStartElement(Element.PROCESS_ENGINES.getLocalName());

  ModelNode node = context.getModelNode();
  
  ModelNode processEngineConfigurations = node.get(Element.PROCESS_ENGINES.getLocalName());
  if (processEngineConfigurations.isDefined()) {
    for (Property property : processEngineConfigurations.asPropertyList()) {
      // write each child element to xml
      writer.writeStartElement(Element.PROCESS_ENGINE.getLocalName());
      
      ModelNode propertyValue = property.getValue();
      for (AttributeDefinition processEngineAttribute : SubsystemAttributeDefinitons.PROCESS_ENGINE_ATTRIBUTES) {
        if (processEngineAttribute.equals(SubsystemAttributeDefinitons.NAME) || processEngineAttribute.equals(SubsystemAttributeDefinitons.DEFAULT)) {
          ((SimpleAttributeDefinition) processEngineAttribute).marshallAsAttribute(propertyValue, writer);
        } else {
          processEngineAttribute.marshallAsElement(propertyValue, writer);
        }
      }


      writer.writeEndElement();
    }
  }
  // end process-engines
  writer.writeEndElement();
}
 
Example 18
Source File: ParsedInterfaceCriteria.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static ParsedInterfaceCriteria parse(final ModelNode model, final boolean specified, final ExpressionResolver expressionResolver) {
    if (model.getType() != ModelType.OBJECT) {
        return new ParsedInterfaceCriteria(ControllerLogger.ROOT_LOGGER.illegalInterfaceCriteria(model.getType(), ModelType.OBJECT));
    }
    // Remove operation params
    final ModelNode subModel = model.clone();
    subModel.remove(ModelDescriptionConstants.OP);
    subModel.remove(ModelDescriptionConstants.OP_ADDR);
    subModel.remove(ModelDescriptionConstants.OPERATION_HEADERS);
    final ParsedInterfaceCriteria parsed;
    if(subModel.hasDefined(ANY_ADDRESS) && subModel.get(ANY_ADDRESS).asBoolean(false)) {
        parsed = ParsedInterfaceCriteria.ANY;
    } else {
        try {
            final List<Property> nodes = subModel.asPropertyList();
            final Set<InterfaceCriteria> criteriaSet = new LinkedHashSet<InterfaceCriteria>();
            for (final Property property : nodes) {
                final InterfaceCriteria criterion = parseCriteria(property, false, expressionResolver);
                if (criterion instanceof WildcardInetAddressInterfaceCriteria) {
                    // AS7-1668: stop processing and just return the any binding.
                    if (nodes.size() > 1) {
                        MGMT_OP_LOGGER.wildcardAddressDetected();
                    }
                    return ParsedInterfaceCriteria.ANY;
                }
                else if (criterion != null) {
                    criteriaSet.add(criterion);
                }
            }
            String validation = new CriteriaValidator(criteriaSet).validate();
            parsed = validation == null ? new ParsedInterfaceCriteria(criteriaSet) : new ParsedInterfaceCriteria(validation);
        } catch (ParsingException p) {
            return new ParsedInterfaceCriteria(p.msg);
        } catch (OperationFailedException e) {
            return new ParsedInterfaceCriteria(e.getMessage());
        }
    }
    if (specified && parsed.getFailureMessage() == null && ! parsed.isAnyLocal() && parsed.getCriteria().size() == 0) {
        return new ParsedInterfaceCriteria(ControllerLogger.ROOT_LOGGER.noInterfaceCriteria());
    }
    return parsed;
}
 
Example 19
Source File: KeycloakSubsystemParser.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void writeCredentials(XMLExtendedStreamWriter writer, ModelNode credentials) throws XMLStreamException {
    Map<String, Object> parsed = new LinkedHashMap<>();
    for (Property credential : credentials.asPropertyList()) {
        String credName = credential.getName();
        String credValue = credential.getValue().get(CredentialDefinition.VALUE.getName()).asString();

        if (credName.contains(".")) {
            String[] parts = credName.split("\\.");
            String provider = parts[0];
            String propKey = parts[1];

            Map<String, String> currentProviderMap = (Map<String, String>) parsed.get(provider);
            if (currentProviderMap == null) {
                currentProviderMap = new LinkedHashMap<>();
                parsed.put(provider, currentProviderMap);
            }
            currentProviderMap.put(propKey, credValue);
        } else {
            parsed.put(credName, credValue);
        }
    }

    for (Map.Entry<String, Object> entry : parsed.entrySet()) {
        writer.writeStartElement(CredentialDefinition.TAG_NAME);
        writer.writeAttribute("name", entry.getKey());

        Object value = entry.getValue();
        if (value instanceof String) {
            writeCharacters(writer, (String) value);
        } else {
            Map<String, String> credentialProps = (Map<String, String>) value;
            for (Map.Entry<String, String> prop : credentialProps.entrySet()) {
                writer.writeStartElement(prop.getKey());
                writeCharacters(writer, prop.getValue());
                writer.writeEndElement();
            }
        }

        writer.writeEndElement();
    }
}
 
Example 20
Source File: DefaultOperationCandidatesProvider.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
    public List<CommandArgument> getProperties(CommandContext ctx, String operationName, OperationRequestAddress address) {

        final ModelControllerClient client = ctx.getModelControllerClient();
        if(client == null) {
            return Collections.emptyList();
        }

/*        if(address.endsOnType()) {
            throw new IllegalArgumentException("The prefix isn't expected to end on a type.");
        }
*/
        final ModelNode request;
        final DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder(address);
        try {
            builder.setOperationName(Util.READ_OPERATION_DESCRIPTION);
            builder.addProperty(Util.NAME, operationName);
            request = builder.buildRequest();
        } catch (OperationFormatException e1) {
            throw new IllegalStateException("Failed to build operation", e1);
        }

        List<CommandArgument> result;
        try {
            ModelNode outcome = client.execute(request);
            if (!Util.isSuccess(outcome)) {
                result = Collections.emptyList();
            } else {
                final ModelNode resultNode = outcome.get(Util.RESULT);
                if(!resultNode.isDefined()) {
                    return Collections.emptyList();
                }
                final ModelNode reqProps = resultNode.get(Util.REQUEST_PROPERTIES);
                if(!reqProps.isDefined()) {
                    return Collections.emptyList();
                }
                final List<Property> propList = reqProps.asPropertyList();
                result = getPropertiesFromPropList(propList, ctx, operationName, address);
            }
        } catch (Exception e) {
            result = Collections.emptyList();
        }
        return result;
    }