org.jboss.dmr.ModelNode Java Examples

The following examples show how to use org.jboss.dmr.ModelNode. 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: ModelTestUtils.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Scans for entries of type STRING containing expression formatted strings. This is to trap where parsers
 * call ModelNode.set("${A}") when ModelNode.setExpression("${A}) should have been used
 *
 * @param model the model to check
 */
public static void scanForExpressionFormattedStrings(ModelNode model) {
    if (model.getType().equals(ModelType.STRING)) {
        if (EXPRESSION_PATTERN.matcher(model.asString()).matches()) {
            Assert.fail("ModelNode with type==STRING contains an expression formatted string: " + model.asString());
        }
    } else if (model.getType() == ModelType.OBJECT) {
        for (String key : model.keys()) {
            final ModelNode child = model.get(key);
            scanForExpressionFormattedStrings(child);
        }
    } else if (model.getType() == ModelType.LIST) {
        List<ModelNode> list = model.asList();
        for (ModelNode entry : list) {
            scanForExpressionFormattedStrings(entry);
        }

    } else if (model.getType() == ModelType.PROPERTY) {
        Property prop = model.asProperty();
        scanForExpressionFormattedStrings(prop.getValue());
    }
}
 
Example #2
Source File: LdapConnectionPropertyResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private PropertyManipulator(OperationContext context, ModelNode operation) {
    PathAddress address = PathAddress.pathAddress(operation.require(OP_ADDR));

    LdapConnectionManagerService service = null;
    String propertyName = null;

    for (PathElement current : address) {
        String currentKey = current.getKey();
        if (currentKey.equals(LDAP_CONNECTION)) {
            String connectionName = current.getValue();
            ServiceName svcName = LdapConnectionManagerService.ServiceUtil.createServiceName(connectionName);
            ServiceRegistry registry = context.getServiceRegistry(true);
            ServiceController<?> controller = registry.getService(svcName);
            service = LdapConnectionManagerService.class.cast(controller.getValue());
        } else if (currentKey.equals(PROPERTY)) {
            propertyName = current.getValue();
        }
    }

    this.service = service;
    this.propertyName = propertyName;
    this.isBooting = context.isBooting();
}
 
Example #3
Source File: DefaultBatchedCommand.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public DefaultBatchedCommand(CommandContext ctx, String command, ModelNode request, ResponseHandler handler) {
    if (command == null) {
        throw new IllegalArgumentException("Command is null.");
    }
    this.command = command;
    if(request == null) {
        throw new IllegalArgumentException("Request is null.");
    }
    this.request = request;
    if (ctx == null) {
        throw new IllegalArgumentException("Context is null.");
    }
    this.ctx = ctx;
    // Keep a ref on description to speedup validation.
    description = (ModelNode) ctx.get(CommandContext.Scope.REQUEST,
            Util.DESCRIPTION_RESPONSE);
    this.handler = handler;
}
 
Example #4
Source File: JobExecutorAdd.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model)
        throws OperationFailedException {

    String jobExecutorThreadPoolName =
            SubsystemAttributeDefinitons.THREAD_POOL_NAME.resolveModelAttribute(context, model).asString();
    ServiceName jobExecutorThreadPoolServiceName = ServiceNames.forManagedThreadPool(jobExecutorThreadPoolName);

    performRuntimeThreadPool(context, model, jobExecutorThreadPoolName, jobExecutorThreadPoolServiceName);

    MscExecutorService service = new MscExecutorService();
    ServiceController<MscExecutorService> serviceController =
            context.getServiceTarget().addService(ServiceNames.forMscExecutorService(), service)
                    .addDependency(jobExecutorThreadPoolServiceName, ManagedQueueExecutorService.class,
                            service.getManagedQueueInjector())
                    .setInitialMode(Mode.ACTIVE).install();
}
 
Example #5
Source File: Configuration.java    From keycloak with Apache License 2.0 6 votes vote down vote up
void updateModel(final ModelNode operation, final ModelNode model, final boolean checkSingleton) throws OperationFailedException {
    ModelNode node = config;

    final List<Property> addressNodes = operation.get("address").asPropertyList();
    final int lastIndex = addressNodes.size() - 1;
    for (int i = 0; i < addressNodes.size(); i++) {
        Property addressNode = addressNodes.get(i);
        // if checkSingleton is true, we verify if the key for the last element (e.g. SP or IDP) in the address path is already defined
        if (i == lastIndex && checkSingleton) {
            if (node.get(addressNode.getName()).isDefined()) {
                // found an existing resource, throw an exception
                throw new OperationFailedException("Duplicate resource: " + addressNode.getName());
            }
        }
        node = node.get(addressNode.getName()).get(addressNode.getValue().asString());
    }
    node.set(model);
}
 
Example #6
Source File: RecursiveDiscardAndRemoveTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void sanityTestNonDiscardedResource() throws Exception {
    ModelNode op = Util.createAddOperation(PathAddress.pathAddress(PATH));
    TransformedOperation transformed = transformOperation(op);
    Assert.assertEquals(op, transformed.getTransformedOperation());
    Assert.assertFalse(transformed.rejectOperation(success()));
    Assert.assertNull(transformed.getFailureDescription());

    op = Util.getWriteAttributeOperation(PathAddress.pathAddress(PATH), "test", new ModelNode("a"));
    transformed = transformOperation(op);
    Assert.assertEquals(op, transformed.getTransformedOperation());
    Assert.assertFalse(transformed.rejectOperation(success()));
    Assert.assertNull(transformed.getFailureDescription());

    op = Util.getUndefineAttributeOperation(PathAddress.pathAddress(PATH), "test");
    transformed = transformOperation(op);
    Assert.assertEquals(op, transformed.getTransformedOperation());
    Assert.assertFalse(transformed.rejectOperation(success()));
    Assert.assertNull(transformed.getFailureDescription());
}
 
Example #7
Source File: DomainServerGroupTransformersTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testRejectTransformers9x() throws Exception {
    if (modelVersion.getMajor() <= 1 || modelVersion.getMinor() <= 3) {
        return;
    }
    KernelServicesBuilder builder = createKernelServicesBuilder(TestModelType.DOMAIN)
            .setModelInitializer(StandardServerGroupInitializers.XML_MODEL_INITIALIZER, StandardServerGroupInitializers.XML_MODEL_WRITE_SANITIZER)
            .createContentRepositoryContent("12345678901234567890")
            .createContentRepositoryContent("09876543210987654321");

    // Add legacy subsystems
    StandardServerGroupInitializers.addServerGroupInitializers(builder.createLegacyKernelServicesBuilder(modelVersion, testControllerVersion));
    KernelServices mainServices = builder.build();

    List<ModelNode> ops = builder.parseXmlResource("servergroup.xml");
    ModelTestUtils.checkFailedTransformedBootOperations(mainServices, modelVersion, ops, new FailedOperationTransformationConfig()
            .addFailedAttribute(PathAddress.pathAddress(PathElement.pathElement(SERVER_GROUP)),
                    FailedOperationTransformationConfig.ChainedConfig.createBuilder(
                            MANAGEMENT_SUBSYSTEM_ENDPOINT, SOCKET_BINDING_PORT_OFFSET, SOCKET_BINDING_DEFAULT_INTERFACE)
                            .addConfig(new FailedOperationTransformationConfig.RejectExpressionsConfig(MANAGEMENT_SUBSYSTEM_ENDPOINT,
                                    SOCKET_BINDING_PORT_OFFSET))
                            .addConfig(new FailedOperationTransformationConfig.NewAttributesConfig(SOCKET_BINDING_DEFAULT_INTERFACE))
                            .build().setReadOnly(MANAGEMENT_SUBSYSTEM_ENDPOINT)));

}
 
Example #8
Source File: AnalysisContextTest.java    From revapi with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigurationHandling_mergeOldStyle() throws Exception {
    Dummy.schema = "{\"type\": \"object\", \"properties\": {\"a\": {\"type\": \"integer\"}," +
            " \"b\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}}}}";
    Dummy.extensionId = "ext";
    ModelNode cfg1 = ModelNode.fromJSONString("[{\"extension\": \"ext\", \"configuration\": {\"a\": 1, \"b\": [\"x\"]}}]");
    ModelNode cfg2 = ModelNode.fromJSONString("{\"ext\": {\"b\": [\"y\"]}}");
    ModelNode newCfg = ModelNode.fromJSONString(
            "[{\"extension\": \"ext\", \"configuration\": {\"a\": 1, \"b\": [\"x\", \"y\"]}}]");

    Revapi revapi = Revapi.builder().withAnalyzers(Dummy.class).withReporters(TestReporter.class).build();

    AnalysisContext ctx = AnalysisContext.builder(revapi)
            .withConfiguration(cfg1)
            .mergeConfiguration(cfg2)
            .build();

    Assert.assertEquals(newCfg, ctx.getConfiguration());
}
 
Example #9
Source File: CustomComponentDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
        throws OperationFailedException {
    ServiceTarget serviceTarget = context.getServiceTarget();

    String address = context.getCurrentAddressValue();
    RuntimeCapability<?> primaryCapability = runtimeCapabilities[0];
    ServiceName primaryServiceName = toServiceName(primaryCapability, address);

    final String module = MODULE.resolveModelAttribute(context, model).asStringOrNull();
    final String className = CLASS_NAME.resolveModelAttribute(context, model).asString();

    final Map<String, String> configurationMap;
    configurationMap = CONFIGURATION.unwrap(context, model);

    ServiceBuilder<?> serviceBuilder = serviceTarget.addService(primaryServiceName);
    for (int i = 1; i < runtimeCapabilities.length; i++) {
        serviceBuilder.addAliases(toServiceName(runtimeCapabilities[i], address));
    }

    commonRequirements(serviceBuilder)
        .setInstance(new TrivialService<>(() -> createValue(module, className, configurationMap)))
        .setInitialMode(Mode.ACTIVE)
        .install();
}
 
Example #10
Source File: HostXml_Legacy.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void parseHttpManagementInterfaceAttributes_1_5(XMLExtendedStreamReader reader, ModelNode addOp) throws XMLStreamException {
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        final String value = reader.getAttributeValue(i);
        if (!isNoNamespaceAttribute(reader, i)) {
            throw unexpectedAttribute(reader, i);
        } else {
            final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
            switch (attribute) {
                case SECURITY_REALM: {
                    HttpManagementResourceDefinition.SECURITY_REALM.parseAndSetParameter(value, addOp, reader);
                    break;
                }
                case CONSOLE_ENABLED: {
                    HttpManagementResourceDefinition.CONSOLE_ENABLED.parseAndSetParameter(value, addOp, reader);
                    break;
                }
                default:
                    throw unexpectedAttribute(reader, i);
            }
        }
    }
}
 
Example #11
Source File: DeploymentRollbackFailureTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private ModelNode getDeploymentCompositeOp() throws MalformedURLException {
    ModelNode op = new ModelNode();
    op.get(OP).set(COMPOSITE);
    ModelNode steps = op.get(STEPS);

    ModelNode depAdd = Util.createAddOperation(PathAddress.pathAddress(DEPLOYMENT_PATH));
    ModelNode content = new ModelNode();
    content.get(URL).set(deployment.toURI().toURL().toString());
    depAdd.get(CONTENT).add(content);

    steps.add(depAdd);

    ModelNode sgAdd = Util.createAddOperation(PathAddress.pathAddress(MAIN_SERVER_GROUP, DEPLOYMENT_PATH));
    sgAdd.get(ENABLED).set(true);
    steps.add(sgAdd);
    return op;
}
 
Example #12
Source File: CompositeOperationHandlerUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Before
public void setupController() throws InterruptedException {
    System.out.println("=========  New Test \n");

    container = ServiceContainer.Factory.create("test");
    ServiceTarget target = container.subTarget();
    TestModelControllerService svc = new ModelControllerImplUnitTestCase.ModelControllerService();
    target.addService(ServiceName.of("ModelController")).setInstance(svc).install();
    sharedState = svc.getSharedState();
    svc.awaitStartup(30, TimeUnit.SECONDS);
    controller = svc.getValue();
    ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
    controller.execute(setup, null, null, null);

    assertEquals(ControlledProcessState.State.RUNNING, svc.getCurrentProcessState());
}
 
Example #13
Source File: AbstractLoggingProfilesTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testDeploymentConfigurationResource() throws Exception {
    try {
        deploy(RUNTIME_NAME1, PROFILE1);
        // Get the resulting model
        final ModelNode loggingConfiguration = readDeploymentResource(RUNTIME_NAME1, "profile-" + PROFILE1);

        Assert.assertTrue("No logging subsystem resource found on the deployment", loggingConfiguration.isDefined());

        // Check the handler exists on the configuration
        final ModelNode handler = loggingConfiguration.get("handler", "DUMMY1");
        Assert.assertTrue("The DUMMY1 handler was not found effective configuration", handler.isDefined());
        Assert.assertEquals("The level should be ERROR", "ERROR", handler.get("level").asString());
    } finally {
        undeploy(RUNTIME_NAME1);
    }
}
 
Example #14
Source File: ExtraSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Test that the model created from the xml looks as expected
 */
@Test
public void testInstallIntoController() throws Exception {
    //Parse the subsystem xml and install into the controller
    String subsystemXml =
            "<subsystem xmlns=\"" + DependencySubsystemExtension.NAMESPACE + "\">" +
            "</subsystem>" +
            "<subsystem xmlns=\"" + MainSubsystemExtension.NAMESPACE + "\">" +
            "</subsystem>";
    KernelServices services = createKernelServicesBuilder(new DependencyAdditionalInitialization())
            .setSubsystemXml(subsystemXml)
            .build();

    //Read the whole model and make sure it looks as expected
    ModelNode model = services.readWholeModel();
    Assert.assertTrue(model.get(SUBSYSTEM).hasDefined(DependencySubsystemExtension.SUBSYSTEM_NAME));
    Assert.assertTrue(model.get(SUBSYSTEM).hasDefined(MainSubsystemExtension.SUBSYSTEM_NAME));

    Assert.assertNotNull(services.getContainer().getService(Dependency.NAME));
    Assert.assertNotNull(services.getContainer().getService(MainService.NAME));
    MainService mainService = (MainService)services.getContainer().getService(MainService.NAME).getValue();
    Assert.assertNotNull(mainService.dependencyValue.getValue());

}
 
Example #15
Source File: LoggingSubsystemParser_1_4.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
void parsePatternFormatterElement(final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException {
    final EnumSet<Attribute> required = EnumSet.of(Attribute.PATTERN);
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        requireNoNamespaceAttribute(reader, i);
        final String value = reader.getAttributeValue(i);
        final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
        required.remove(attribute);
        switch (attribute) {
            case PATTERN: {
                PatternFormatterResourceDefinition.PATTERN.parseAndSetParameter(value, operation, reader);
                break;
            }
            case COLOR_MAP: {
                PatternFormatterResourceDefinition.COLOR_MAP.parseAndSetParameter(value, operation, reader);
                break;
            }
            default:
                throw unexpectedAttribute(reader, i);
        }
    }
    if (!required.isEmpty()) {
        throw missingRequired(reader, required);
    }
    requireNoContent(reader);
}
 
Example #16
Source File: LegacyTypeConverterUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testJsonObject() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT);

    TypeConverter converter = getConverter(description);

    Assert.assertEquals(SimpleType.STRING, converter.getOpenType());

    ModelNode node = new ModelNode();
    node.get("long").set(5L);
    node.get("string").set("Value");
    node.get("a", "b").set(true);
    node.get("c", "d").set(40);

    String json = node.toJSONString(false);
    String data = assertCast(String.class, converter.fromModelNode(node));
    Assert.assertEquals(json, data);

    Assert.assertEquals(ModelNode.fromJSONString(json), converter.toModelNode(data));
}
 
Example #17
Source File: JmxManagementInterface.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private ModelNode getInfo(ObjectName objectName) {
    MBeanServerConnection connection = getConnection();
    ModelNode attributes = null;
    ModelNode headers = null;
    Exception exception = null;
    try {
        MBeanInfo mBeanInfo = connection.getMBeanInfo(objectName);
        MBeanAttributeInfo[] attributeInfos = mBeanInfo.getAttributes();
        ModelNode[] data = modelNodeAttributesInfo(attributeInfos, objectName);
        attributes = data[0];
        headers = data[1];
    } catch (Exception e) {
        if (e instanceof JMException || e instanceof JMRuntimeException) {
            exception = e;
        } else {
            throw new RuntimeException(e);
        }
    }
    return modelNodeResult(attributes, exception, headers);
}
 
Example #18
Source File: OperationWithManyStepsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testSendNotificationForRollingBackOperation() throws Exception {
    ListBackedNotificationHandler handler = new ListBackedNotificationHandler();
    getController().getNotificationRegistry().registerNotificationHandler(ANY_ADDRESS, handler, ALL);

    ModelNode operation = createOperation(MY_OPERATION);
    operation.get(ROLLBACK.getName()).set(true);
    try {
        executeForResult(operation);
        fail("operation must have been rolled back");
    } catch (OperationFailedException e) {
        assertEquals("rolled back", e.getFailureDescription().asString());
    }

    assertTrue("the notification handler did not receive any notifications", handler.getNotifications().isEmpty());

    getController().getNotificationRegistry().unregisterNotificationHandler(ANY_ADDRESS, handler, ALL);
}
 
Example #19
Source File: FullReplaceUndeployTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static boolean hasDeployment(final ModelControllerClient client, final String name) throws IOException {
    final ModelNode op = Operations.createOperation(ClientConstants.READ_CHILDREN_NAMES_OPERATION);
    op.get(CHILD_TYPE).set(DEPLOYMENT);
    final ModelNode listDeploymentsResult;
    try {
        listDeploymentsResult = client.execute(op);
        // Check to make sure there is an outcome
        if (Operations.isSuccessfulOutcome(listDeploymentsResult)) {
            final List<ModelNode> deployments = Operations.readResult(listDeploymentsResult).asList();
            for (ModelNode deployment : deployments) {
                if (name.equals(deployment.asString())) {
                    return true;
                }
            }
        } else {
            throw new IllegalStateException(Operations.getFailureDescription(listDeploymentsResult).asString());
        }
    } catch (IOException e) {
        throw new IllegalStateException(String.format("Could not execute operation '%s'", op), e);
    }
    return false;
}
 
Example #20
Source File: StandaloneXml_9.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void parseNativeManagementInterface(XMLExtendedStreamReader reader, ModelNode address, List<ModelNode> list) throws XMLStreamException {
    final ModelNode operationAddress = address.clone();
    operationAddress.add(MANAGEMENT_INTERFACE, NATIVE_INTERFACE);
    final ModelNode addOp = Util.getEmptyOperation(ADD, operationAddress);

    // Handle attributes
    parseNativeManagementInterfaceAttributes(reader, addOp);

    // Handle elements
    while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
        requireNamespace(reader, namespace);
        final Element element = Element.forName(reader.getLocalName());
        switch (element) {
            case SOCKET:
                throw ControllerLogger.ROOT_LOGGER.unsupportedElement(reader.getName(),reader.getLocation(), SOCKET_BINDING);
            case SOCKET_BINDING:
                parseNativeManagementSocketBinding(reader, addOp);
                break;
            default:
                throw unexpectedElement(reader);
        }
    }

    list.add(addOp);
}
 
Example #21
Source File: PersistentResourceXMLParserTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testComplexAttributesStuff() throws Exception {
    CoreParser parser = new CoreParser();

    String xml = readResource("core-subsystem.xml");
    StringReader strReader = new StringReader(xml);

    XMLMapper mapper = XMLMapper.Factory.create();
    mapper.registerRootElement(new QName("urn:jboss:domain:core:1.0", "subsystem"), parser);

    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StreamSource(strReader));
    List<ModelNode> operations = new ArrayList<>();
    mapper.parseDocument(operations, reader);

    Assert.assertEquals(2, operations.size());
    Assert.assertEquals(2, operations.get(1).get("listeners").asList().size());
    ModelNode subsystem = opsToModel(operations);

    StringWriter stringWriter = new StringWriter();
    XMLExtendedStreamWriter xmlStreamWriter = createXMLStreamWriter(XMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter));
    SubsystemMarshallingContext context = new SubsystemMarshallingContext(subsystem, xmlStreamWriter);
    mapper.deparseDocument(parser, context, xmlStreamWriter);
    String out = stringWriter.toString();
    Assert.assertEquals(normalizeXML(xml), normalizeXML(out));
}
 
Example #22
Source File: ExpressionTypeConverterUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testJsonObject() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT);

    TypeConverter converter = getConverter(description);

    Assert.assertEquals(SimpleType.STRING, converter.getOpenType());

    ModelNode node = new ModelNode();
    node.get("long").set(5L);
    node.get("string").set("Value");
    node.get("a", "b").set(true);
    node.get("c", "d").set(40);

    String json = node.toJSONString(false);
    String data = assertCast(String.class, converter.fromModelNode(node));
    Assert.assertEquals(json, data);

    Assert.assertEquals(ModelNode.fromJSONString(json), converter.toModelNode(data));
}
 
Example #23
Source File: HostXml_5.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void parseDiscoveryOption(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list, final Set<String> discoveryOptionNames) throws XMLStreamException {

        // Handle attributes
        final ModelNode addOp = parseDiscoveryOptionAttributes(reader, address, list, discoveryOptionNames);

        // Handle elements
        while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
            requireNamespace(reader, namespace);
            final Element element = Element.forName(reader.getLocalName());
            switch (element) {
                case PROPERTY: {
                    parseDiscoveryOptionProperty(reader, addOp.get(PROPERTIES));
                    break;
                }
                default:
                    throw unexpectedElement(reader);
            }
        }
    }
 
Example #24
Source File: EchoDMRTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testCompact() throws CliInitializationException, CommandLineException {
    ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream();
    CommandContextConfiguration config = new CommandContextConfiguration.Builder().setConsoleOutput(consoleOutput).build();
    CommandContext ctx = CommandContextFactory.getInstance().newCommandContext(config);
    try {
        String cmd = "/subsystem=foo:op(arg1=14, arg2=[{i1=\"val1\", i2=\"val2\"}], arg3=\"val3\")";
        ctx.handle("echo-dmr " + cmd);
        String out = consoleOutput.toString();
        out = out.substring(0, out.lastIndexOf("\n"));
        consoleOutput.reset();
        ctx.handle("echo-dmr --compact " + cmd);
        String compact = consoleOutput.toString();
        compact = compact.substring(0, compact.lastIndexOf("\n"));
        Assert.assertTrue(out, out.contains("\n"));
        Assert.assertFalse(compact, compact.contains("\n"));
        ModelNode mn = ModelNode.fromString(out);
        ModelNode mnCompact = ModelNode.fromString(compact);
        Assert.assertEquals(mnCompact.toString(), mn, mnCompact);
    } finally {
        ctx.terminateSession();
    }
}
 
Example #25
Source File: ListAttributeDefinitionTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testStringList() {
    StringListAttributeDefinition list = new StringListAttributeDefinition.Builder("string-list")
            .setAllowExpression(true)
            .setRequired(true)
            .build();
    assertEquals(list.getValueType(), ModelType.STRING);
    ModelNode desc = list.getNoTextDescription(false);
    ModelNode expressionNode = desc.get(EXPRESSIONS_ALLOWED);
    assertNotNull("Expression element should be present!", expressionNode);
    Assert.assertTrue("expressions should be supported", expressionNode.asBoolean());
}
 
Example #26
Source File: CoreAbstractSecurityDomainSetup.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected static void applyUpdates(final ModelControllerClient client, final List<ModelNode> updates) {
    for (ModelNode update : updates) {
        try {
            applyUpdate(client, update, false);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #27
Source File: OutboundBindAddressRemoveHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException {
    final CidrAddressTable<InetSocketAddress> bindingsTable = getWorkerService(context).getBindingsTable();
    if (bindingsTable != null) {
        final CidrAddress cidrAddress = getCidrAddress(model, context);
        final InetSocketAddress bindAddress = getBindAddress(model, context);
        bindingsTable.removeExact(cidrAddress, bindAddress);
    }
}
 
Example #28
Source File: AbstractCollectionHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void populateModel(final ModelNode operation, final ModelNode model) throws OperationFailedException {
    NAME.validateAndSet(operation, model);
    for (AttributeDefinition attr : attributes) {
        if (attr == VALUE){//don't validate VALUE attribute WFCORE-826
            model.get(VALUE.getName()).set(operation.get(VALUE.getName()));
        }else {
            attr.validateAndSet(operation, model);
        }
    }
}
 
Example #29
Source File: SyslogAuditLogTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Tests that the syslog configuration operation fails if an invalid reconnect-attempts number is used
 */
@Test
public void testBadIntegerReconnectAttempts() {
    udpOperation.get(ElytronDescriptionConstants.RECONNECT_ATTEMPTS).set(BAD_RECONNECT_NUMBER);
    ModelNode response = services.executeOperation(udpOperation);
    assertCorrectError(response, new String[] {"WFLYCTL0117", Integer.toString(BAD_RECONNECT_NUMBER)});
    assertFailed(response);
}
 
Example #30
Source File: DomainDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
        throws OperationFailedException {
    RuntimeCapability<Void> runtimeCapability = SECURITY_DOMAIN_RUNTIME_CAPABILITY.fromBaseCapability(context.getCurrentAddressValue());
    ServiceName domainName = runtimeCapability.getCapabilityServiceName(SecurityDomain.class);

    installService(context, domainName, model);
}