<commit_before>/**
 *
 */
package org.jboss.as.controller;

import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.persistence.ConfigurationPersistenceException;
import org.jboss.as.controller.persistence.ConfigurationPersister;
import org.jboss.as.controller.registry.ModelNodeRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.OutputStream;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * Unit tests of {@link NewModelControllerImpl}.
 *
 * @author <NAME> (c) 2011 Red Hat Inc.
 */
public class ModelControllerImplUnitTestCase {

    private ServiceContainer container;
    private NewModelController controller;
    private AtomicBoolean sharedState;

    public static final void toggleRuntimeState(AtomicBoolean state) {
        boolean runtimeVal = false;
        while (!state.compareAndSet(runtimeVal, !runtimeVal)) {
            runtimeVal = !runtimeVal;
        }
    }

    @Before
    public void setupController() throws InterruptedException {
        container = ServiceContainer.Factory.create("test");
        ServiceTarget target = container.subTarget();
        ModelControllerService svc = new ModelControllerService(container);
        ServiceBuilder<NewModelController> builder = target.addService(ServiceName.of("ModelController"), svc);
        builder.install();
        sharedState = svc.state;
        svc.latch.await();
        controller = svc.getValue();
        ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
        controller.execute(setup, null, null, null);
    }

    @After
    public void shutdownServiceContainer() {
        if (container != null) {
            container.shutdown();
            try {
                container.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                container = null;
            }
        }
    }

    /** TODO make this an AbstractControllerService subclass once we sort setting up the registry */
    public static class ModelControllerService implements Service<NewModelController> {

        final AtomicBoolean state = new AtomicBoolean(true);
        final CountDownLatch latch = new CountDownLatch(1);
        private NewModelController value;
        private final ServiceContainer serviceContainer;

        ModelControllerService(final ServiceContainer serviceContainer) {
            this.serviceContainer = serviceContainer;
        }

        @Override
        public void start(StartContext context) throws StartException {
            ServiceTarget target = serviceContainer.subTarget();
            ServiceController<?> serviceController = context.getController();
            ModelNodeRegistration rootRegistration = ModelNodeRegistration.Factory.create(DESC_PROVIDER);

            rootRegistration.registerOperationHandler("setup", new SetupHandler(), DESC_PROVIDER, false);
//            rootRegistration.registerOperationHandler("composite", new NewCompositeOperationHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("good", new ModelStageGoodHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("bad", new ModelStageFailsHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("evil", new ModelStageThrowsExceptionHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("handleFailed", new RuntimeStageFailsHandler(state), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("runtimeException", new RuntimeStageThrowsExceptionHandler(state), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("good-service", new GoodServiceHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("bad-service", new BadServiceHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("missing-service", new MissingServiceHandler(), DESC_PROVIDER, false);

            value = new NewModelControllerImpl(serviceContainer, target, rootRegistration, new ContainerStateMonitor(serviceContainer, serviceController),
                    new NullConfigurationPersister(), NewOperationContext.Type.SERVER, null);
            latch.countDown();
        }

        @Override
        public void stop(StopContext context) {
            value = null;
        }

        @Override
        public NewModelController getValue() throws IllegalStateException, IllegalArgumentException {
            return value;
        }
    }


    @Test
    public void testGoodModelExecution() throws Exception {
        ModelNode result = controller.execute(getOperation("good", "attr1", 5), null, null, null);
        assertEquals(SUCCESS, result.get(OUTCOME).asString());
        assertEquals(1, result.get("result").asInt());
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals(SUCCESS, result.get(OUTCOME).asString());
        assertEquals(5, result.get(RESULT).asInt());
    }

    @Test
    public void testModelStageFailureExecution() throws Exception {
        ModelNode result = controller.execute(getOperation("bad", "attr1", 5), null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertEquals("this request is bad", result.get(FAILURE_DESCRIPTION).asString());

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals(SUCCESS, result.get(OUTCOME).asString());
        assertEquals(1, result.get(RESULT).asInt());
    }

    @Test
    public void testModelStageUnhandledFailureExecution() throws Exception {
        ModelNode result = controller.execute(getOperation("evil", "attr1", 5), null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertTrue(result.get(FAILURE_DESCRIPTION).toString().indexOf("this handler is evil") > -1);

        // Confirm runtime state was unchanged
        assertTrue(sharedState.get());

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    @Test
    public void testHandleFailedExecution() throws Exception {
        ModelNode result = controller.execute(getOperation("handleFailed", "attr1", 5, "good", false), null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertEquals("handleFailed", result.get("failure-description").asString());

        // Confirm runtime state was unchanged
        assertTrue(sharedState.get());

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    @Test
    public void testRuntimeStageFailedNoRollback() throws Exception {

        ModelNode op = getOperation("handleFailed", "attr1", 5, "good");
        op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false);
        ModelNode result = controller.execute(op, null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertEquals("handleFailed", result.get("failure-description").asString());

        // Confirm runtime state was changed
        assertFalse(sharedState.get());

        // Confirm model was changed
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(5, result.get("result").asInt());
    }

    @Test
    public void testRuntimeStageUnhandledFailureNoRollback() throws Exception {

        ModelNode op = getOperation("runtimeException", "attr1", 5, "good");
        op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false);
        ModelNode result = controller.execute(op, null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertTrue(result.get("failure-description").toString().indexOf("runtime exception") > - 1);

        // Confirm runtime state was changed
        assertFalse(sharedState.get());

        // Confirm model was changed
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        System.out.println(result);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(5, result.get("result").asInt());
    }

    @Test
    public void testPathologicalRollback() throws Exception {
        ModelNode result = controller.execute(getOperation("bad", "attr1", 5), null, null, null); // don't tell it to call the 'good' op on rollback
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertEquals("this request is bad", result.get("failure-description").asString());

        // Confirm runtime state was unchanged
        assertTrue(sharedState.get());

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    @Test
    public void testGoodService() throws Exception {
        ModelNode result = controller.execute(getOperation("good-service", "attr1", 5), null, null, null);
        System.out.println(result);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());

        ServiceController<?> sc = container.getService(ServiceName.JBOSS.append("good-service"));
        assertNotNull(sc);
        assertEquals(ServiceController.State.UP, sc.getState());

        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(5, result.get("result").asInt());
    }

    @Test
    public void testBadService() throws Exception {
        ModelNode result = controller.execute(getOperation("bad-service", "attr1", 5, "good"), null, null, null);
        System.out.println(result);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertTrue(result.hasDefined(FAILURE_DESCRIPTION));

        ServiceController<?> sc = container.getService(ServiceName.JBOSS.append("bad-service"));
        if (sc != null) {
            assertEquals(ServiceController.Mode.REMOVE, sc.getMode());
        }

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    @Test
    public void testMissingService() throws Exception {
        ModelNode result = controller.execute(getOperation("missing-service", "attr1", 5, "good"), null, null, null);
        System.out.println(result);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertTrue(result.hasDefined(FAILURE_DESCRIPTION));

        ServiceController<?> sc = container.getService(ServiceName.JBOSS.append("missing-service"));
        if (sc != null) {
            assertEquals(ServiceController.Mode.REMOVE, sc.getMode());
        }

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    public static ModelNode getOperation(String opName, String attr, int val) {
        return getOperation(opName, attr, val, null, false);
    }
    public static ModelNode getOperation(String opName, String attr, int val, String rollbackName) {
        return getOperation(opName, attr, val, rollbackName, false);
    }

    public static ModelNode getOperation(String opName, String attr, int val, String rollbackName, boolean async) {
        ModelNode op = new ModelNode();
        op.get(OP).set(opName);
        op.get(OP_ADDR).setEmptyList();
        op.get(NAME).set(attr);
        op.get(VALUE).set(val);
        op.get("rollbackName").set(rollbackName == null ? opName : rollbackName);

        if (async) {
            op.get("async").set(true);
        }
        return op;
    }

    public static class SetupHandler implements NewStepHandler {

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {
            ModelNode model = new ModelNode();

            //Atttributes
            model.get("attr1").set(1);
            model.get("attr2").set(2);

            context.writeModel(PathAddress.EMPTY_ADDRESS, model);

            context.completeStep();
        }
    }

    public static class ModelStageGoodHandler implements NewStepHandler {

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require(NAME).asString();
            ModelNode model = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS);
            ModelNode attr = model.get(name);
            final int current = attr.asInt();
            attr.set(operation.require(VALUE));

            context.getResult().set(current);

            ModelNode compensatingOp = getOperation("good", name, current, operation.get("rollbackName").asString());
            context.getCompensatingOperation().set(compensatingOp);
            context.completeStep();
        }
    }

    public static class ModelStageFailsHandler implements NewStepHandler {

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require(NAME).asString();
            ModelNode model = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS);
            ModelNode attr = model.get(name);
            attr.set(operation.require(VALUE));

            context.getFailureDescription().set("this request is bad");

            context.completeStep();
        }
    }

    public static class ModelStageThrowsExceptionHandler implements NewStepHandler {

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require(NAME).asString();
            ModelNode model = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS);
            ModelNode attr = model.get(name);
            attr.set(operation.require(VALUE));

            throw new RuntimeException("this handler is evil");
        }
    }

    public static class RuntimeStageFailsHandler implements NewStepHandler {

        private final AtomicBoolean state;

        public RuntimeStageFailsHandler(AtomicBoolean state) {
            this.state = state;
        }

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            int current = attr.asInt();
            attr.set(operation.require("value"));

            context.getResult().set(current);

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {
                    toggleRuntimeState(state);
                    context.getFailureDescription().set("handleFailed");
                    if (context.completeStep() == NewOperationContext.ResultAction.ROLLBACK) {
                        toggleRuntimeState(state);
                    }
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation(operation.get("rollbackName").asString(), name, current);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static class RuntimeStageThrowsExceptionHandler implements NewStepHandler {

        private final AtomicBoolean state;

        public RuntimeStageThrowsExceptionHandler(AtomicBoolean state) {
            this.state = state;
        }

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            int current = attr.asInt();
            attr.set(operation.require("value"));

            context.getResult().set(current);

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {
                    toggleRuntimeState(state);
                    throw new RuntimeException("runtime exception");
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation(operation.get("rollbackName").asString(), name, current);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static class GoodServiceHandler implements NewStepHandler {
        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            final int current = attr.asInt();
            attr.set(operation.require("value"));

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {

                    context.getResult().set(current);
                    ServiceName svcName =  ServiceName.JBOSS.append("good-service");
                    ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler();
                    context.getServiceTarget().addService(svcName, Service.NULL)
                            .addListener(verificationHandler)
                            .install();
                    context.addStep(verificationHandler, NewOperationContext.Stage.VERIFY);
                    if (context.completeStep() == NewOperationContext.ResultAction.ROLLBACK) {
                        context.removeService(svcName);
                    }
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation(operation.get("rollbackName").asString(), name, current);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static class MissingServiceHandler implements NewStepHandler {
        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            final int current = attr.asInt();
            attr.set(operation.require("value"));

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {

                    context.getResult().set(current);

                    ServiceName svcName = ServiceName.JBOSS.append("missing-service");
                    ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler();
                    context.getServiceTarget().addService(svcName, Service.NULL)
                            .addDependency(ServiceName.JBOSS.append("missing"))
                            .addListener(verificationHandler)
                            .install();
                    context.addStep(verificationHandler, NewOperationContext.Stage.VERIFY);
                    if (context.completeStep() == NewOperationContext.ResultAction.ROLLBACK) {
                        context.removeService(svcName);
                    }
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation("missing-service", name, current, operation.get("rollbackName").asString(), true);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static class BadServiceHandler implements NewStepHandler {
        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            final int current = attr.asInt();
            attr.set(operation.require("value"));

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {

                    context.getResult().set(current);


                    Service<Void> bad = new Service<Void>() {

                        @Override
                        public Void getValue() throws IllegalStateException, IllegalArgumentException {
                            return null;
                        }

                        @Override
                        public void start(StartContext context) throws StartException {
                            throw new RuntimeException("Bad service!");
                        }

                        @Override
                        public void stop(StopContext context) {
                        }

                    };
                    ServiceName svcName = ServiceName.JBOSS.append("bad-service");
                    ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler();
                    context.getServiceTarget().addService(svcName, bad)
                            .addListener(verificationHandler)
                            .install();
                    context.addStep(verificationHandler, NewOperationContext.Stage.VERIFY);
                    if (context.completeStep() == NewOperationContext.ResultAction.ROLLBACK) {
                        context.removeService(svcName);
                    }
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation("bad-service", name, current, operation.get("rollbackName").asString(), true);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static final DescriptionProvider DESC_PROVIDER = new DescriptionProvider() {
        @Override
        public ModelNode getModelDescription(Locale locale) {
            return new ModelNode();
        }
    };


    private static class NullConfigurationPersister implements ConfigurationPersister{

        @Override<commit_msg>Add tests of caller rolling back successful tx<commit_after>/**
 *
 */
package org.jboss.as.controller;

import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.controller.persistence.ConfigurationPersistenceException;
import org.jboss.as.controller.persistence.ConfigurationPersister;
import org.jboss.as.controller.registry.ModelNodeRegistration;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceContainer;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.OutputStream;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILED;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FAILURE_DESCRIPTION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OPERATION_HEADERS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OUTCOME;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RESULT;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLBACK_ON_RUNTIME_FAILURE;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ROLLED_BACK;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUCCESS;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * Unit tests of {@link NewModelControllerImpl}.
 *
 * @author <NAME> (c) 2011 Red Hat Inc.
 */
public class ModelControllerImplUnitTestCase {

    private ServiceContainer container;
    private NewModelController controller;
    private AtomicBoolean sharedState;

    public static final void toggleRuntimeState(AtomicBoolean state) {
        boolean runtimeVal = false;
        while (!state.compareAndSet(runtimeVal, !runtimeVal)) {
            runtimeVal = !runtimeVal;
        }
    }

    @Before
    public void setupController() throws InterruptedException {
        container = ServiceContainer.Factory.create("test");
        ServiceTarget target = container.subTarget();
        ModelControllerService svc = new ModelControllerService(container);
        ServiceBuilder<NewModelController> builder = target.addService(ServiceName.of("ModelController"), svc);
        builder.install();
        sharedState = svc.state;
        svc.latch.await();
        controller = svc.getValue();
        ModelNode setup = Util.getEmptyOperation("setup", new ModelNode());
        controller.execute(setup, null, null, null);
    }

    @After
    public void shutdownServiceContainer() {
        if (container != null) {
            container.shutdown();
            try {
                container.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                container = null;
            }
        }
    }

    /** TODO make this an AbstractControllerService subclass once we sort setting up the registry */
    public static class ModelControllerService implements Service<NewModelController> {

        final AtomicBoolean state = new AtomicBoolean(true);
        final CountDownLatch latch = new CountDownLatch(1);
        private NewModelController value;
        private final ServiceContainer serviceContainer;

        ModelControllerService(final ServiceContainer serviceContainer) {
            this.serviceContainer = serviceContainer;
        }

        @Override
        public void start(StartContext context) throws StartException {
            ServiceTarget target = serviceContainer.subTarget();
            ServiceController<?> serviceController = context.getController();
            ModelNodeRegistration rootRegistration = ModelNodeRegistration.Factory.create(DESC_PROVIDER);

            rootRegistration.registerOperationHandler("setup", new SetupHandler(), DESC_PROVIDER, false);
//            rootRegistration.registerOperationHandler("composite", new NewCompositeOperationHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("good", new ModelStageGoodHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("bad", new ModelStageFailsHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("evil", new ModelStageThrowsExceptionHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("handleFailed", new RuntimeStageFailsHandler(state), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("runtimeException", new RuntimeStageThrowsExceptionHandler(state), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("good-service", new GoodServiceHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("bad-service", new BadServiceHandler(), DESC_PROVIDER, false);
            rootRegistration.registerOperationHandler("missing-service", new MissingServiceHandler(), DESC_PROVIDER, false);

            value = new NewModelControllerImpl(serviceContainer, target, rootRegistration, new ContainerStateMonitor(serviceContainer, serviceController),
                    new NullConfigurationPersister(), NewOperationContext.Type.SERVER, null);
            latch.countDown();
        }

        @Override
        public void stop(StopContext context) {
            value = null;
        }

        @Override
        public NewModelController getValue() throws IllegalStateException, IllegalArgumentException {
            return value;
        }
    }


    @Test
    public void testGoodModelExecution() throws Exception {
        ModelNode result = controller.execute(getOperation("good", "attr1", 5), null, null, null);
        assertEquals(SUCCESS, result.get(OUTCOME).asString());
        assertEquals(1, result.get("result").asInt());
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals(SUCCESS, result.get(OUTCOME).asString());
        assertEquals(5, result.get(RESULT).asInt());
    }

    /**
     * Test successfully updating the model but then having the caller roll back the transaction.
     * @throws Exception
     */
    @Test
    public void testGoodModelExecutionTxRollback() throws Exception {
        ModelNode result = controller.execute(getOperation("good", "attr1", 5), null, RollbackTransactionControl.INSTANCE, null);
        System.out.println(result);
        // Store response data for later assertions after we check more critical stuff
        String outcome = result.get(OUTCOME).asString();
        boolean rolledback = result.get(ROLLED_BACK).asBoolean();

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals(SUCCESS, result.get(OUTCOME).asString());
        assertEquals(1, result.get(RESULT).asInt());

        // Assert the first response was as expected
        assertEquals(FAILED, outcome);  // TODO success may be valid???
        assertTrue(rolledback);
    }

    @Test
    public void testModelStageFailureExecution() throws Exception {
        ModelNode result = controller.execute(getOperation("bad", "attr1", 5), null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertEquals("this request is bad", result.get(FAILURE_DESCRIPTION).asString());

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals(SUCCESS, result.get(OUTCOME).asString());
        assertEquals(1, result.get(RESULT).asInt());
    }

    @Test
    public void testModelStageUnhandledFailureExecution() throws Exception {
        ModelNode result = controller.execute(getOperation("evil", "attr1", 5), null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertTrue(result.get(FAILURE_DESCRIPTION).toString().indexOf("this handler is evil") > -1);

        // Confirm runtime state was unchanged
        assertTrue(sharedState.get());

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    @Test
    public void testHandleFailedExecution() throws Exception {
        ModelNode result = controller.execute(getOperation("handleFailed", "attr1", 5, "good", false), null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertEquals("handleFailed", result.get("failure-description").asString());

        // Confirm runtime state was unchanged
        assertTrue(sharedState.get());

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    @Test
    public void testRuntimeStageFailedNoRollback() throws Exception {

        ModelNode op = getOperation("handleFailed", "attr1", 5, "good");
        op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false);
        ModelNode result = controller.execute(op, null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertEquals("handleFailed", result.get("failure-description").asString());

        // Confirm runtime state was changed
        assertFalse(sharedState.get());

        // Confirm model was changed
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(5, result.get("result").asInt());
    }

    @Test
    public void testRuntimeStageUnhandledFailureNoRollback() throws Exception {

        ModelNode op = getOperation("runtimeException", "attr1", 5, "good");
        op.get(OPERATION_HEADERS, ROLLBACK_ON_RUNTIME_FAILURE).set(false);
        ModelNode result = controller.execute(op, null, null, null);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertTrue(result.get("failure-description").toString().indexOf("runtime exception") > - 1);

        // Confirm runtime state was changed
        assertFalse(sharedState.get());

        // Confirm model was changed
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        System.out.println(result);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(5, result.get("result").asInt());
    }

    @Test
    public void testPathologicalRollback() throws Exception {
        ModelNode result = controller.execute(getOperation("bad", "attr1", 5), null, null, null); // don't tell it to call the 'good' op on rollback
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertEquals("this request is bad", result.get("failure-description").asString());

        // Confirm runtime state was unchanged
        assertTrue(sharedState.get());

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    @Test
    public void testGoodService() throws Exception {
        ModelNode result = controller.execute(getOperation("good-service", "attr1", 5), null, null, null);
        System.out.println(result);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());

        ServiceController<?> sc = container.getService(ServiceName.JBOSS.append("good-service"));
        assertNotNull(sc);
        assertEquals(ServiceController.State.UP, sc.getState());

        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(5, result.get("result").asInt());
    }

    @Test
    public void testGoodServiceTxRollback() throws Exception {
        ModelNode result = controller.execute(getOperation("good-service", "attr1", 5), null, null, null);
        System.out.println(result);
        // Store response data for later assertions after we check more critical stuff

        ServiceController<?> sc = container.getService(ServiceName.JBOSS.append("good-service"));
        if (sc != null) {
            assertEquals(ServiceController.Mode.REMOVE, sc.getMode());
        }

        // Confirm model was unchanged
        ModelNode result2 = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals(SUCCESS, result2.get(OUTCOME).asString());
        assertEquals(1, result2.get(RESULT).asInt());

        // Assert the first response was as expected
        assertEquals(FAILED, result.get(OUTCOME).asString());   // TODO success may be valid???
        assertTrue(result.get(ROLLED_BACK).asBoolean());
    }

    @Test
    public void testBadService() throws Exception {
        ModelNode result = controller.execute(getOperation("bad-service", "attr1", 5, "good"), null, null, null);
        System.out.println(result);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertTrue(result.hasDefined(FAILURE_DESCRIPTION));

        ServiceController<?> sc = container.getService(ServiceName.JBOSS.append("bad-service"));
        if (sc != null) {
            assertEquals(ServiceController.Mode.REMOVE, sc.getMode());
        }

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    @Test
    public void testMissingService() throws Exception {
        ModelNode result = controller.execute(getOperation("missing-service", "attr1", 5, "good"), null, null, null);
        System.out.println(result);
        assertEquals(FAILED, result.get(OUTCOME).asString());
        assertTrue(result.hasDefined(FAILURE_DESCRIPTION));

        ServiceController<?> sc = container.getService(ServiceName.JBOSS.append("missing-service"));
        if (sc != null) {
            assertEquals(ServiceController.Mode.REMOVE, sc.getMode());
        }

        // Confirm model was unchanged
        result = controller.execute(getOperation("good", "attr1", 1), null, null, null);
        assertEquals("success", result.get("outcome").asString());
        assertEquals(1, result.get("result").asInt());
    }

    public static ModelNode getOperation(String opName, String attr, int val) {
        return getOperation(opName, attr, val, null, false);
    }
    public static ModelNode getOperation(String opName, String attr, int val, String rollbackName) {
        return getOperation(opName, attr, val, rollbackName, false);
    }

    public static ModelNode getOperation(String opName, String attr, int val, String rollbackName, boolean async) {
        ModelNode op = new ModelNode();
        op.get(OP).set(opName);
        op.get(OP_ADDR).setEmptyList();
        op.get(NAME).set(attr);
        op.get(VALUE).set(val);
        op.get("rollbackName").set(rollbackName == null ? opName : rollbackName);

        if (async) {
            op.get("async").set(true);
        }
        return op;
    }

    public static class SetupHandler implements NewStepHandler {

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {
            ModelNode model = new ModelNode();

            //Atttributes
            model.get("attr1").set(1);
            model.get("attr2").set(2);

            context.writeModel(PathAddress.EMPTY_ADDRESS, model);

            context.completeStep();
        }
    }

    public static class ModelStageGoodHandler implements NewStepHandler {

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require(NAME).asString();
            ModelNode model = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS);
            ModelNode attr = model.get(name);
            final int current = attr.asInt();
            attr.set(operation.require(VALUE));

            context.getResult().set(current);

            ModelNode compensatingOp = getOperation("good", name, current, operation.get("rollbackName").asString());
            context.getCompensatingOperation().set(compensatingOp);
            context.completeStep();
        }
    }

    public static class ModelStageFailsHandler implements NewStepHandler {

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require(NAME).asString();
            ModelNode model = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS);
            ModelNode attr = model.get(name);
            attr.set(operation.require(VALUE));

            context.getFailureDescription().set("this request is bad");

            context.completeStep();
        }
    }

    public static class ModelStageThrowsExceptionHandler implements NewStepHandler {

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require(NAME).asString();
            ModelNode model = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS);
            ModelNode attr = model.get(name);
            attr.set(operation.require(VALUE));

            throw new RuntimeException("this handler is evil");
        }
    }

    public static class RuntimeStageFailsHandler implements NewStepHandler {

        private final AtomicBoolean state;

        public RuntimeStageFailsHandler(AtomicBoolean state) {
            this.state = state;
        }

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            int current = attr.asInt();
            attr.set(operation.require("value"));

            context.getResult().set(current);

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {
                    toggleRuntimeState(state);
                    context.getFailureDescription().set("handleFailed");
                    if (context.completeStep() == NewOperationContext.ResultAction.ROLLBACK) {
                        toggleRuntimeState(state);
                    }
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation(operation.get("rollbackName").asString(), name, current);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static class RuntimeStageThrowsExceptionHandler implements NewStepHandler {

        private final AtomicBoolean state;

        public RuntimeStageThrowsExceptionHandler(AtomicBoolean state) {
            this.state = state;
        }

        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            int current = attr.asInt();
            attr.set(operation.require("value"));

            context.getResult().set(current);

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {
                    toggleRuntimeState(state);
                    throw new RuntimeException("runtime exception");
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation(operation.get("rollbackName").asString(), name, current);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static class GoodServiceHandler implements NewStepHandler {
        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            final int current = attr.asInt();
            attr.set(operation.require("value"));

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {

                    context.getResult().set(current);
                    ServiceName svcName =  ServiceName.JBOSS.append("good-service");
                    ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler();
                    context.getServiceTarget().addService(svcName, Service.NULL)
                            .addListener(verificationHandler)
                            .install();
                    context.addStep(verificationHandler, NewOperationContext.Stage.VERIFY);
                    if (context.completeStep() == NewOperationContext.ResultAction.ROLLBACK) {
                        context.removeService(svcName);
                    }
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation(operation.get("rollbackName").asString(), name, current);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static class MissingServiceHandler implements NewStepHandler {
        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            final int current = attr.asInt();
            attr.set(operation.require("value"));

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {

                    context.getResult().set(current);

                    ServiceName svcName = ServiceName.JBOSS.append("missing-service");
                    ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler();
                    context.getServiceTarget().addService(svcName, Service.NULL)
                            .addDependency(ServiceName.JBOSS.append("missing"))
                            .addListener(verificationHandler)
                            .install();
                    context.addStep(verificationHandler, NewOperationContext.Stage.VERIFY);
                    if (context.completeStep() == NewOperationContext.ResultAction.ROLLBACK) {
                        context.removeService(svcName);
                    }
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation("missing-service", name, current, operation.get("rollbackName").asString(), true);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static class BadServiceHandler implements NewStepHandler {
        @Override
        public void execute(NewOperationContext context, ModelNode operation) {

            String name = operation.require("name").asString();
            ModelNode attr = context.readModelForUpdate(PathAddress.EMPTY_ADDRESS).get(name);
            final int current = attr.asInt();
            attr.set(operation.require("value"));

            context.addStep(new NewStepHandler() {

                @Override
                public void execute(NewOperationContext context, ModelNode operation) {

                    context.getResult().set(current);


                    Service<Void> bad = new Service<Void>() {

                        @Override
                        public Void getValue() throws IllegalStateException, IllegalArgumentException {
                            return null;
                        }

                        @Override
                        public void start(StartContext context) throws StartException {
                            throw new RuntimeException("Bad service!");
                        }

                        @Override
                        public void stop(StopContext context) {
                        }

                    };
                    ServiceName svcName = ServiceName.JBOSS.append("bad-service");
                    ServiceVerificationHandler verificationHandler = new ServiceVerificationHandler();
                    context.getServiceTarget().addService(svcName, bad)
                            .addListener(verificationHandler)
                            .install();
                    context.addStep(verificationHandler, NewOperationContext.Stage.VERIFY);
                    if (context.completeStep() == NewOperationContext.ResultAction.ROLLBACK) {
                        context.removeService(svcName);
                    }
                }
            }, NewOperationContext.Stage.RUNTIME);

            ModelNode compOp = getOperation("bad-service", name, current, operation.get("rollbackName").asString(), true);
            context.getCompensatingOperation().set(compOp);
            context.completeStep();
        }
    }

    public static final DescriptionProvider DESC_PROVIDER = new DescriptionProvider() {
        @Override
        public ModelNode getModelDescription(Locale locale) {
            return new ModelNode();
        }
    };

    private static class RollbackTransactionControl implements NewModelController.OperationTransactionControl {

        static final RollbackTransactionControl INSTANCE = new RollbackTransactionControl();

        @Override
        public void operationPrepared(NewModelController.OperationTransaction transaction, ModelNode result) {
            transaction.rollback();
        }
    }


    private static class NullConfigurationPersister implements ConfigurationPersister{

        @Override
{'fraction_non_alphanumeric': 0.10505273578799071, 'fraction_numerical': 0.002684384876061379, 'mean_word_length': 2.8118287373004356, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1698695', 'n_tokens_mistral': 12936, 'n_tokens_neox': 12502, 'n_words': 2686}