@Test
  public void testServerGroupsTransformer() throws Exception {

    boolean is71x = modelVersion.getMajor() == 1 && modelVersion.getMinor() < 4;
    KernelServicesBuilder builder =
        createKernelServicesBuilder(TestModelType.DOMAIN)
            .setModelInitializer(
                StandardServerGroupInitializers.XML_MODEL_INITIALIZER,
                StandardServerGroupInitializers.XML_MODEL_WRITE_SANITIZER)
            .createContentRepositoryContent("12345678901234567890")
            .createContentRepositoryContent("09876543210987654321")
            .setXmlResource(is71x ? "servergroup_1_3.xml" : "servergroup-with-expressions.xml");

    LegacyKernelServicesInitializer legacyInitializer =
        StandardServerGroupInitializers.addServerGroupInitializers(
            builder.createLegacyKernelServicesBuilder(modelVersion, testControllerVersion));
    if (is71x) {
      // The 7.1.x descriptions are inaccurate so we can't validate the add ops against them
      legacyInitializer.setDontValidateOperations();
    }

    KernelServices mainServices = builder.build();
    Assert.assertTrue(mainServices.isSuccessfulBoot());

    KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
    Assert.assertTrue(legacyServices.isSuccessfulBoot());

    checkCoreModelTransformation(mainServices, modelVersion, MODEL_FIXER, MODEL_FIXER);
  }
 @Override
 public void initialize(ExtensionContext context) {
   SubsystemRegistration registration =
       context.registerSubsystem(SUBSYSTEM_NAME, ModelVersion.create(1));
   registration.registerSubsystemModel(new CliExtCommandsSubsystemResourceDescription());
   registration.registerXMLElementWriter(new CliExtCommandsParser());
 }
Example #3
0
  private void registerTransformers(SubsystemRegistration subsystem) {
    ResourceTransformationDescriptionBuilder builder =
        TransformationDescriptionBuilder.Factory.createSubsystemInstance();

    GlobalModulesRejecterConverter globalModulesRejecterConverter =
        new GlobalModulesRejecterConverter();

    builder
        .getAttributeBuilder()
        // Deal with https://issues.jboss.org/browse/AS7-4892 on 7.1.2
        .addRejectCheck(
            new JBossDescriptorPropertyReplacementRejectChecker(),
            EeSubsystemRootResource.JBOSS_DESCRIPTOR_PROPERTY_REPLACEMENT)
        // Deal with new attributes added to global-modules elements
        .addRejectCheck(globalModulesRejecterConverter, GlobalModulesDefinition.INSTANCE)
        .setValueConverter(globalModulesRejecterConverter, GlobalModulesDefinition.INSTANCE)
        // Deal with new attribute annotation-property-replacement
        .setDiscard(
            new DiscardAttributeChecker.DiscardAttributeValueChecker(new ModelNode(false)),
            EeSubsystemRootResource.ANNOTATION_PROPERTY_REPLACEMENT)
        .addRejectCheck(
            RejectAttributeChecker.DEFINED,
            EeSubsystemRootResource.ANNOTATION_PROPERTY_REPLACEMENT);
    builder.rejectChildResource(PathElement.pathElement(EESubsystemModel.CONTEXT_SERVICE));
    builder.rejectChildResource(PathElement.pathElement(EESubsystemModel.MANAGED_THREAD_FACTORY));
    builder.rejectChildResource(PathElement.pathElement(EESubsystemModel.MANAGED_EXECUTOR_SERVICE));
    builder.rejectChildResource(
        PathElement.pathElement(EESubsystemModel.MANAGED_SCHEDULED_EXECUTOR_SERVICE));
    builder.discardChildResource(EESubsystemModel.DEFAULT_BINDINGS_PATH);

    TransformationDescription.Tools.register(
        builder.build(), subsystem, ModelVersion.create(1, 0, 0));
  }
  @Test
  public void testTransformers() throws Exception {
    ModelVersion oldVersion = ModelVersion.create(1, 0, 0);
    KernelServicesBuilder builder =
        createKernelServicesBuilder(null).setSubsystemXml(getSubsystemXml());
    builder
        .createLegacyKernelServicesBuilder(null, oldVersion)
        .setExtensionClassName(VersionedExtension1.class.getName())
        .addSimpleResourceURL("target/legacy-archive.jar");
    KernelServices mainServices = builder.build();
    KernelServices legacyServices = mainServices.getLegacyServices(oldVersion);
    Assert.assertNotNull(legacyServices);

    ModelNode mainModel = mainServices.readWholeModel();
    ModelNode mainSubsystem = mainModel.get(SUBSYSTEM, "test-subsystem");
    Assert.assertEquals(3, mainSubsystem.keys().size());
    Assert.assertEquals("This is only a test", mainSubsystem.get("test-attribute").asString());
    Assert.assertTrue(mainSubsystem.hasDefined("new-element"));
    Assert.assertTrue(mainSubsystem.get("new-element").hasDefined("test"));
    Assert.assertTrue(mainSubsystem.hasDefined("renamed"));
    Assert.assertTrue(mainSubsystem.get("renamed").hasDefined("element"));

    ModelNode legacyModel = legacyServices.readWholeModel();
    ModelNode legacySubsystem = legacyModel.get(SUBSYSTEM, "test-subsystem");
    Assert.assertEquals(2, legacySubsystem.keys().size());
    Assert.assertEquals("This is only a test", legacySubsystem.get("test-attribute").asString());
    Assert.assertTrue(legacySubsystem.hasDefined("element"));
    Assert.assertTrue(legacySubsystem.get("element").hasDefined("renamed"));

    generateLegacySubsystemResourceRegistrationDmr(mainServices, oldVersion);
    checkSubsystemTransformer(mainServices, oldVersion);
  }
  private void testTransformers(ModelTestControllerVersion controllerVersion) throws Exception {
    ModelVersion modelVersion = ModelVersion.create(1, 0, 0);
    KernelServicesBuilder builder = createKernelServicesBuilder(createAdditionalInitialization());

    builder
        .createLegacyKernelServicesBuilder(
            createAdditionalInitialization(), controllerVersion, modelVersion)
        .addMavenResourceURL("org.jboss.as:jboss-as-cmp:" + controllerVersion.getMavenGavVersion())
        .configureReverseControllerCheck(createAdditionalInitialization(), null);

    KernelServices mainServices = builder.build();
    Assert.assertTrue(mainServices.isSuccessfulBoot());
    Assert.assertTrue(mainServices.getLegacyServices(modelVersion).isSuccessfulBoot());

    ModelTestUtils.checkFailedTransformedBootOperations(
        mainServices,
        modelVersion,
        parse(getSubsystemXml()),
        new FailedOperationTransformationConfig()
            .addFailedAttribute(
                SUBSYSTEM_PATH.append(CmpSubsystemModel.UUID_KEY_GENERATOR_PATH),
                new FailedOperationTransformationConfig.NewAttributesConfig(
                    CMPSubsystemRootResourceDefinition.JNDI_NAME))
            .addFailedAttribute(
                SUBSYSTEM_PATH.append(CmpSubsystemModel.HILO_KEY_GENERATOR_PATH),
                new FailedOperationTransformationConfig.NewAttributesConfig(
                    CMPSubsystemRootResourceDefinition.JNDI_NAME)));
  }
 private ManagedServer createManagedServer(final String serverName, final byte[] authKey) {
   final String hostControllerName = domainController.getLocalHostInfo().getLocalHostName();
   // final ManagedServerBootConfiguration configuration = combiner.createConfiguration();
   final Map<PathAddress, ModelVersion> subsystems =
       TransformerRegistry.resolveVersions(extensionRegistry);
   final ModelVersion modelVersion =
       ModelVersion.create(
           Version.MANAGEMENT_MAJOR_VERSION,
           Version.MANAGEMENT_MINOR_VERSION,
           Version.MANAGEMENT_MICRO_VERSION);
   // We don't need any transformation between host and server
   final TransformationTarget target =
       TransformationTargetImpl.create(
           extensionRegistry.getTransformerRegistry(),
           modelVersion,
           subsystems,
           null,
           TransformationTarget.TransformationTargetType.SERVER,
           null);
   return new ManagedServer(
       hostControllerName,
       serverName,
       authKey,
       processControllerClient,
       managementAddress,
       target);
 }
/** @author <a href="*****@*****.**">Kabir Khan</a> */
public class JSR77ManagementExtension implements Extension {

  public static final String NAMESPACE = "urn:jboss:domain:jsr77:1.0";
  public static final String SUBSYSTEM_NAME = "jsr77";
  private static final J2EEManagementSubsystemParser parser = new J2EEManagementSubsystemParser();
  private static final String RESOURCE_NAME =
      JSR77ManagementExtension.class.getPackage().getName() + ".LocalDescriptions";

  private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 0, 0);

  static ResourceDescriptionResolver getResourceDescriptionResolver(final String keyPrefix) {
    return new StandardResourceDescriptionResolver(
        keyPrefix, RESOURCE_NAME, JSR77ManagementExtension.class.getClassLoader(), true, true);
  }

  /** {@inheritDoc} */
  @Override
  public void initialize(ExtensionContext context) {
    final SubsystemRegistration subsystem =
        context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);

    // Register the root subsystem resource.
    final ManagementResourceRegistration rootResource =
        subsystem.registerSubsystemModel(
            new JSR77ManagementRootResource(
                context.getProcessType() == ProcessType.APPLICATION_CLIENT));

    // Mandatory describe operation
    rootResource.registerOperationHandler(
        GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);

    subsystem.registerXMLElementWriter(parser);
  }

  /** {@inheritDoc} */
  @Override
  public void initializeParsers(ExtensionParsingContext context) {
    context.setSubsystemXmlMapping(SUBSYSTEM_NAME, NAMESPACE, parser);
  }

  static class J2EEManagementSubsystemParser extends PersistentResourceXMLParser {

    private static PersistentResourceXMLDescription xmlDescription;

    static {
      xmlDescription =
          PersistentResourceXMLDescription.builder(
                  new JSR77ManagementRootResource(false), JSR77ManagementExtension.NAMESPACE)
              .build();
    }

    @Override
    public PersistentResourceXMLDescription getParserDescription() {
      return xmlDescription;
    }
  }
}
  @Test
  public void testDeploymentOverlaysIgnoredOnOlderVersionGetIgnoredButFailDueToServerGroupEntry()
      throws Exception {
    if (modelVersion.getMajor() > 1 || modelVersion.getMinor() >= 4) {
      return;
    }

    KernelServicesBuilder builder =
        createKernelServicesBuilder(TestModelType.DOMAIN)
            .setModelInitializer(
                StandardServerGroupInitializers.XML_MODEL_INITIALIZER,
                StandardServerGroupInitializers.XML_MODEL_WRITE_SANITIZER)
            .createContentRepositoryContent("12345678901234567890")
            .setXmlResource("domain.xml");

    // Start up an empty legacy controller
    StandardServerGroupInitializers.addServerGroupInitializers(
            builder.createLegacyKernelServicesBuilder(modelVersion, testControllerVersion))
        .setDontUseBootOperations()
        // Since the legacy controller does not know about deployment overlays, there will be not
        // boot ops for the reverse check
        .skipReverseControllerCheck();

    KernelServices mainServices = builder.build();
    Assert.assertTrue(mainServices.isSuccessfulBoot());
    KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
    Assert.assertTrue(legacyServices.isSuccessfulBoot());

    // Since the server group deployment deployment-overlay is there we should fail
    try {
      mainServices.applyMasterDomainModel(modelVersion, null);
      Assert.fail(
          "Should have failed to apply model since server group still has a deployment overlay");
    } catch (Exception e) {
      Assert.assertTrue(
          e.getMessage(),
          e.getMessage().contains("WFLYCTL0147")
              || e.getMessage()
                  .contains(
                      "JBAS014738")); // WFLYCTL0147 comes from
                                      // ControllerMessages.noChildType(String)
    }
  }
  @Test
  public void testDeploymentOverlaysTransformer() throws Exception {
    KernelServicesBuilder builder =
        createKernelServicesBuilder(TestModelType.DOMAIN)
            .setModelInitializer(
                StandardServerGroupInitializers.XML_MODEL_INITIALIZER,
                StandardServerGroupInitializers.XML_MODEL_WRITE_SANITIZER)
            .createContentRepositoryContent("12345678901234567890")
            .setXmlResource("domain.xml");

    LegacyKernelServicesInitializer legacyInitializer =
        StandardServerGroupInitializers.addServerGroupInitializers(
            builder.createLegacyKernelServicesBuilder(modelVersion, testControllerVersion));

    if (modelVersion.getMajor() == 1 && modelVersion.getMinor() < 4) {
      testDeploymentOverlaysTransformer_7_1_x(modelVersion, builder, legacyInitializer);
    } else {
      testDeploymentOverlaysTransformerMaster(modelVersion, builder, legacyInitializer);
    }
  }
 public LdapAuthenticationResourceDefinition() {
   super(
       PathElement.pathElement(
           ModelDescriptionConstants.AUTHENTICATION, ModelDescriptionConstants.LDAP),
       ControllerResolver.getDeprecatedResolver(
           SecurityRealmResourceDefinition.DEPRECATED_PARENT_CATEGORY,
           "core.management.security-realm.authentication.ldap"),
       new LdapAuthenticationAddHandler(),
       new SecurityRealmChildRemoveHandler(true),
       OperationEntry.Flag.RESTART_RESOURCE_SERVICES,
       OperationEntry.Flag.RESTART_RESOURCE_SERVICES);
   setDeprecated(ModelVersion.create(1, 7));
 }
  @Test
  public void testRejectTransformers71x() 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
    LegacyKernelServicesInitializer legacyInitializer =
        StandardServerGroupInitializers.addServerGroupInitializers(
                builder.createLegacyKernelServicesBuilder(modelVersion, testControllerVersion))
            // The reverse stuff is tested in the other test
            .skipReverseControllerCheck();
    // The 7.1.x descriptions are inaccurate so we can't validate the add ops against them
    legacyInitializer.setDontValidateOperations();

    KernelServices mainServices = builder.build();

    List<ModelNode> ops = builder.parseXmlResource("servergroup_1_3-with-expressions.xml");
    ModelTestUtils.checkFailedTransformedBootOperations(
        mainServices,
        modelVersion,
        ops,
        new FailedOperationTransformationConfig()
            .addFailedAttribute(
                PathAddress.pathAddress(PathElement.pathElement(SERVER_GROUP)),
                new FailedOperationTransformationConfig.RejectExpressionsConfig(
                        ServerGroupResourceDefinition.MANAGEMENT_SUBSYSTEM_ENDPOINT,
                        ServerGroupResourceDefinition.SOCKET_BINDING_PORT_OFFSET)
                    .setReadOnly(ServerGroupResourceDefinition.MANAGEMENT_SUBSYSTEM_ENDPOINT)));
  }
Example #12
0
 @Override
 protected boolean rejectAttribute(
     PathAddress address,
     String attributeName,
     ModelNode attributeValue,
     TransformationContext context) {
   if (attributeValue.isDefined()) {
     ModelVersion version = context.getTarget().getVersion();
     if (version.getMajor() == 1 && version.getMinor() == 2) {
       // 7.1.2 has model version 1.2.0 and should have this transformation
       // 7.1.3 has model version 1.3.0 and should not have this transformation
       if (attributeValue.getType() == ModelType.BOOLEAN) {
         return !attributeValue.asBoolean();
       } else {
         if (!Boolean.parseBoolean(attributeValue.asString())) {
           return true;
         }
       }
     }
   }
   return false;
 }
    boolean continuteWithCheck() {
      if (!isVersionLevel()) {
        return true;
      }
      ModelVersion currentVersion = getModelVersion(currentDefinition);
      ModelVersion legacyVersion = getModelVersion(legacyDefinition);
      System.out.println(
          "====== Resource root address: "
              + formatAddressOneLine(pathAddress)
              + " - Current version: "
              + currentVersion
              + "; legacy version: "
              + legacyVersion
              + " =======");

      if (!legacyVersion.equals(currentVersion) && compareDifferentVersions) {
        return true;
      } else if (legacyVersion.equals(currentVersion)) {
        return true;
      } else {
        System.out.println("Skipping check of resource and children");
        return false;
      }
    }
  /**
   * Register the transformers for transforming from 1.4.0 to 1.3.0 management api versions, in
   * which: - attributes INDEXING_PROPERTIES, SEGMENTS were added in 1.4 - attribute VIRTUAL_NODES
   * was deprecated in 1.4 - expression support was added to most attributes in 1.4, except for
   * CLUSTER, DEFAULT_CACHE and MODE for which it was already enabled in 1.3
   *
   * <p>Chaining of transformers is used in cases where two transformers are required for the same
   * operation.
   *
   * @param subsystem the subsystems registration
   */
  private static void registerTransformers(final SubsystemRegistration subsystem) {

    // define the resource and operation transformers
    final InfinispanOperationTransformer_1_3 removeSelectedCacheAttributes =
        new InfinispanOperationTransformer_1_3();

    final RejectExpressionValuesTransformer cacheContainerReject =
        new RejectExpressionValuesTransformer(
            InfinispanRejectedExpressions_1_3.REJECT_CONTAINER_ATTRIBUTES);
    final RejectExpressionValuesTransformer transportReject =
        new RejectExpressionValuesTransformer(
            InfinispanRejectedExpressions_1_3.REJECT_TRANSPORT_ATTRIBUTES);
    final RejectExpressionValuesTransformer cacheReject =
        new RejectExpressionValuesTransformer(
            InfinispanRejectedExpressions_1_3.REJECT_CACHE_ATTRIBUTES);
    final ChainedOperationTransformer chained =
        new ChainedOperationTransformer(removeSelectedCacheAttributes, cacheReject);

    // Register the model transformers
    TransformersSubRegistration registration =
        subsystem.registerModelTransformers(
            ModelVersion.create(1, 3), new InfinispanSubsystemTransformer_1_3());
    TransformersSubRegistration containerRegistration =
        registration.registerSubResource(
            CacheContainerResource.CONTAINER_PATH, (OperationTransformer) cacheContainerReject);
    containerRegistration.registerSubResource(
        TransportResource.TRANSPORT_PATH, (OperationTransformer) transportReject);

    PathElement[] cachePaths = {
      LocalCacheResource.LOCAL_CACHE_PATH,
      InvalidationCacheResource.INVALIDATION_CACHE_PATH,
      ReplicatedCacheResource.REPLICATED_CACHE_PATH,
      DistributedCacheResource.DISTRIBUTED_CACHE_PATH
    };
    for (int i = 0; i < cachePaths.length; i++) {
      // register chained operation transformers for cache ADD operations where we need to remove
      // and reject
      TransformersSubRegistration cacheRegistration =
          containerRegistration.registerSubResource(cachePaths[i], (OperationTransformer) chained);
      registerCacheChildrenTransformers(cacheRegistration);
    }
  }
Example #15
0
/**
 * The implementation of the Remoting extension.
 *
 * @author <a href="mailto:[email protected]">David M. Lloyd</a>
 * @author Emanuel Muckenhuber
 */
public class RemotingExtension implements Extension {

  public static final String SUBSYSTEM_NAME = "remoting";

  private static final String RESOURCE_NAME =
      RemotingExtension.class.getPackage().getName() + ".LocalDescriptions";

  static final String NODE_NAME_PROPERTY = "jboss.node.name";

  static ResourceDescriptionResolver getResourceDescriptionResolver(final String keyPrefix) {
    return new StandardResourceDescriptionResolver(
        keyPrefix, RESOURCE_NAME, RemotingExtension.class.getClassLoader(), true, false);
  }

  static final SensitivityClassification REMOTING_SECURITY =
      new SensitivityClassification(SUBSYSTEM_NAME, "remoting-security", false, true, true);

  static final SensitiveTargetAccessConstraintDefinition REMOTING_SECURITY_DEF =
      new SensitiveTargetAccessConstraintDefinition(REMOTING_SECURITY);

  private static final int MANAGEMENT_API_MAJOR_VERSION = 2;
  private static final int MANAGEMENT_API_MINOR_VERSION = 0;
  private static final int MANAGEMENT_API_MICRO_VERSION = 0;

  private static final ModelVersion VERSION_1_1 = ModelVersion.create(1, 1);
  private static final ModelVersion VERSION_1_2 = ModelVersion.create(1, 2);
  private static final ModelVersion VERSION_1_3 = ModelVersion.create(1, 3);

  @Override
  public void initialize(ExtensionContext context) {

    // Register the remoting subsystem
    final SubsystemRegistration registration =
        context.registerSubsystem(
            SUBSYSTEM_NAME,
            MANAGEMENT_API_MAJOR_VERSION,
            MANAGEMENT_API_MINOR_VERSION,
            MANAGEMENT_API_MICRO_VERSION);
    registration.registerXMLElementWriter(RemotingSubsystemXMLPersister.INSTANCE);

    final ManagementResourceRegistration subsystem =
        registration.registerSubsystemModel(
            new RemotingSubsystemRootResource(context.getProcessType()));
    subsystem.registerOperationHandler(
        GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);

    final ManagementResourceRegistration connector =
        subsystem.registerSubModel(ConnectorResource.INSTANCE);
    connector.registerSubModel(PropertyResource.INSTANCE_CONNECTOR);
    final ManagementResourceRegistration sasl = connector.registerSubModel(SaslResource.INSTANCE);
    sasl.registerSubModel(SaslPolicyResource.INSTANCE);
    sasl.registerSubModel(PropertyResource.INSTANCE_CONNECTOR);

    final ManagementResourceRegistration httpConnector =
        subsystem.registerSubModel(HttpConnectorResource.INSTANCE);
    httpConnector.registerSubModel(PropertyResource.INSTANCE_HTTP_CONNECTOR);
    final ManagementResourceRegistration httpSasl =
        httpConnector.registerSubModel(SaslResource.INSTANCE);
    httpSasl.registerSubModel(SaslPolicyResource.INSTANCE);
    httpSasl.registerSubModel(PropertyResource.INSTANCE_HTTP_CONNECTOR);

    // remote outbound connection
    subsystem.registerSubModel(RemoteOutboundConnectionResourceDefinition.INSTANCE);
    // local outbound connection
    subsystem.registerSubModel(LocalOutboundConnectionResourceDefinition.INSTANCE);
    // (generic) outbound connection
    subsystem.registerSubModel(GenericOutboundConnectionResourceDefinition.INSTANCE);

    if (context.isRegisterTransformers()) {
      registerTransformers_1_1(registration);
      registerTransformers_1_2(registration);
      registerTransformers_1_3(registration);
    }
  }

  private void registerTransformers_1_1(SubsystemRegistration registration) {

    ResourceTransformationDescriptionBuilder builder =
        ResourceTransformationDescriptionBuilder.Factory.createSubsystemInstance();
    builder
        .getAttributeBuilder()
        .addRejectCheck(
            RejectAttributeChecker.SIMPLE_EXPRESSIONS, RemotingSubsystemRootResource.ATTRIBUTES);

    builder.rejectChildResource(HttpConnectorResource.PATH);

    ResourceTransformationDescriptionBuilder connector =
        builder.addChildResource(ConnectorResource.PATH);
    connector
        .addChildResource(PropertyResource.PATH)
        .getAttributeBuilder()
        .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, PropertyResource.VALUE);

    ResourceTransformationDescriptionBuilder sasl =
        connector.addChildResource(SaslResource.SASL_CONFIG_PATH);
    sasl.getAttributeBuilder()
        .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, SaslResource.ATTRIBUTES);
    sasl.addChildResource(SaslPolicyResource.INSTANCE)
        .getAttributeBuilder()
        .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, SaslPolicyResource.ATTRIBUTES);
    sasl.addChildResource(PropertyResource.PATH)
        .getAttributeBuilder()
        .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, PropertyResource.VALUE);

    protocolTransform(
            builder
                .addChildResource(RemoteOutboundConnectionResourceDefinition.ADDRESS)
                .getAttributeBuilder())
        .addRejectCheck(
            RejectAttributeChecker.SIMPLE_EXPRESSIONS,
            RemoteOutboundConnectionResourceDefinition.USERNAME)
        .end()
        .addChildResource(PropertyResource.PATH)
        .getAttributeBuilder()
        .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, PropertyResource.VALUE)
        .end();

    builder
        .addChildResource(LocalOutboundConnectionResourceDefinition.ADDRESS)
        .addChildResource(PropertyResource.PATH)
        .getAttributeBuilder()
        .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, PropertyResource.VALUE)
        .end();

    builder
        .addChildResource(GenericOutboundConnectionResourceDefinition.ADDRESS)
        .addChildResource(PropertyResource.PATH)
        .getAttributeBuilder()
        .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, PropertyResource.VALUE)
        .end();

    TransformationDescription.Tools.register(builder.build(), registration, VERSION_1_1);
  }

  private void registerTransformers_1_2(SubsystemRegistration registration) {
    TransformationDescription.Tools.register(
        get1_2_0_1_3_0Description(), registration, VERSION_1_2);
  }

  private void registerTransformers_1_3(SubsystemRegistration registration) {
    TransformationDescription.Tools.register(
        get1_2_0_1_3_0Description(), registration, VERSION_1_3);
  }

  private static TransformationDescription get1_2_0_1_3_0Description() {
    ResourceTransformationDescriptionBuilder builder =
        ResourceTransformationDescriptionBuilder.Factory.createSubsystemInstance();
    builder.rejectChildResource(HttpConnectorResource.PATH);
    protocolTransform(
        builder
            .addChildResource(RemoteOutboundConnectionResourceDefinition.ADDRESS)
            .getAttributeBuilder());
    return builder.build();
  }

  private static AttributeTransformationDescriptionBuilder protocolTransform(
      AttributeTransformationDescriptionBuilder builder) {
    builder
        .addRejectCheck(
            new RejectAttributeChecker.DefaultRejectAttributeChecker() {

              @Override
              protected boolean rejectAttribute(
                  final PathAddress address,
                  final String attributeName,
                  final ModelNode attributeValue,
                  final TransformationContext context) {
                return !attributeValue.isDefined()
                    || !attributeValue.asString().equals(Protocols.REMOTE);
              }

              @Override
              public String getRejectionLogMessage(final Map<String, ModelNode> attributes) {
                return RemotingMessages.MESSAGES.protocolMustBeRemote();
              }
            },
            RemoteOutboundConnectionResourceDefinition.PROTOCOL)
        .setDiscard(
            new DiscardAttributeChecker.DefaultDiscardAttributeChecker() {
              @Override
              protected boolean isValueDiscardable(
                  final PathAddress address,
                  final String attributeName,
                  final ModelNode attributeValue,
                  final TransformationContext context) {
                return attributeValue.isDefined()
                    && attributeValue.asString().equals(Protocols.REMOTE);
              }
            },
            RemoteOutboundConnectionResourceDefinition.PROTOCOL);
    return builder;
  }

  /** {@inheritDoc} */
  @Override
  public void initializeParsers(ExtensionParsingContext context) {
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME, Namespace.REMOTING_1_0.getUriString(), RemotingSubsystem10Parser.INSTANCE);
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME, Namespace.REMOTING_1_1.getUriString(), RemotingSubsystem11Parser.INSTANCE);
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME, Namespace.REMOTING_2_0.getUriString(), RemotingSubsystem20Parser.INSTANCE);
  }
}
Example #16
0
 /**
  * Indicates whether this model is more recent than the specified version and thus requires
  * transformation
  *
  * @param version a model version
  * @return true this this model is more recent than the specified version, false otherwise
  */
 public boolean requiresTransformation(ModelVersion version) {
   return ModelVersion.compare(this.version, version) < 0;
 }
Example #17
0
 private JGroupsModel(int major, int minor, int micro) {
   this.version = ModelVersion.create(major, minor, micro);
 }
/**
 * {@link org.jboss.as.controller.ResourceDefinition} for the HTTP management interface resource.
 *
 * @author Brian Stansberry (c) 2011 Red Hat Inc.
 */
public class HttpManagementResourceDefinition extends SimpleResourceDefinition {

  private static final PathElement RESOURCE_PATH =
      PathElement.pathElement(MANAGEMENT_INTERFACE, HTTP_INTERFACE);

  public static final SimpleAttributeDefinition SECURITY_REALM =
      new SimpleAttributeDefinitionBuilder(
              ModelDescriptionConstants.SECURITY_REALM, ModelType.STRING, true)
          .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, false))
          .addAccessConstraint(
              new SensitiveTargetAccessConstraintDefinition(
                  SensitivityClassification.SECURITY_REALM))
          .build();

  public static final SimpleAttributeDefinition INTERFACE =
      new SimpleAttributeDefinitionBuilder(
              ModelDescriptionConstants.INTERFACE, ModelType.STRING, false)
          .setAllowExpression(true)
          .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, false, true))
          .setAlternatives(
              ModelDescriptionConstants.SOCKET_BINDING,
              ModelDescriptionConstants.SECURE_SOCKET_BINDING)
          .addAccessConstraint(
              new SensitiveTargetAccessConstraintDefinition(
                  SensitivityClassification.SOCKET_CONFIG))
          .setDeprecated(ModelVersion.create(1, 4))
          .build();

  public static final SimpleAttributeDefinition HTTP_PORT =
      new SimpleAttributeDefinitionBuilder(ModelDescriptionConstants.PORT, ModelType.INT, true)
          .setAllowExpression(true)
          .setValidator(new IntRangeValidator(0, 65535, true, true))
          .setAlternatives(
              ModelDescriptionConstants.SOCKET_BINDING,
              ModelDescriptionConstants.SECURE_SOCKET_BINDING)
          .setRequires(ModelDescriptionConstants.INTERFACE)
          .addAccessConstraint(
              new SensitiveTargetAccessConstraintDefinition(
                  SensitivityClassification.SOCKET_CONFIG))
          .setDeprecated(ModelVersion.create(1, 4))
          .build();

  public static final SimpleAttributeDefinition HTTPS_PORT =
      new SimpleAttributeDefinitionBuilder(
              ModelDescriptionConstants.SECURE_PORT, ModelType.INT, true)
          .setAllowExpression(true)
          .setValidator(new IntRangeValidator(0, 65535, true, true))
          .setAlternatives(
              ModelDescriptionConstants.SOCKET_BINDING,
              ModelDescriptionConstants.SECURE_SOCKET_BINDING)
          .setRequires(ModelDescriptionConstants.INTERFACE)
          .addAccessConstraint(
              new SensitiveTargetAccessConstraintDefinition(
                  SensitivityClassification.SOCKET_CONFIG))
          .setDeprecated(ModelVersion.create(1, 4))
          .build();

  public static final SimpleAttributeDefinition SOCKET_BINDING =
      new SimpleAttributeDefinitionBuilder(
              ModelDescriptionConstants.SOCKET_BINDING, ModelType.STRING, true)
          .setXmlName(Attribute.HTTP.getLocalName())
          .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, false))
          .setAlternatives(ModelDescriptionConstants.INTERFACE)
          .addAccessConstraint(
              new SensitiveTargetAccessConstraintDefinition(
                  SensitivityClassification.SOCKET_CONFIG))
          .build();

  public static final SimpleAttributeDefinition SECURE_SOCKET_BINDING =
      new SimpleAttributeDefinitionBuilder(
              ModelDescriptionConstants.SECURE_SOCKET_BINDING, ModelType.STRING, true)
          .setXmlName(Attribute.HTTPS.getLocalName())
          .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, false))
          .setAlternatives(ModelDescriptionConstants.INTERFACE)
          .addAccessConstraint(
              new SensitiveTargetAccessConstraintDefinition(
                  SensitivityClassification.SOCKET_CONFIG))
          .build();

  public static final SimpleAttributeDefinition CONSOLE_ENABLED =
      new SimpleAttributeDefinitionBuilder(
              ModelDescriptionConstants.CONSOLE_ENABLED, ModelType.BOOLEAN, true)
          .setXmlName(Attribute.CONSOLE_ENABLED.getLocalName())
          .setDefaultValue(new ModelNode(true))
          .build();

  public static final SimpleAttributeDefinition HTTP_UPGRADE_ENABLED =
      new SimpleAttributeDefinitionBuilder(
              ModelDescriptionConstants.HTTP_UPGRADE_ENABLED, ModelType.BOOLEAN, true)
          .setXmlName(Attribute.HTTP_UPGRADE_ENABLED.getLocalName())
          .setDefaultValue(new ModelNode(false))
          .build();
  public static final AttributeDefinition[] ATTRIBUTE_DEFINITIONS =
      new AttributeDefinition[] {
        INTERFACE,
        HTTP_PORT,
        HTTPS_PORT,
        SECURITY_REALM,
        SOCKET_BINDING,
        SECURE_SOCKET_BINDING,
        CONSOLE_ENABLED,
        HTTP_UPGRADE_ENABLED
      };

  public static final HttpManagementResourceDefinition INSTANCE =
      new HttpManagementResourceDefinition();

  private HttpManagementResourceDefinition() {
    super(
        RESOURCE_PATH,
        ServerDescriptions.getResourceDescriptionResolver("core.management.http-interface"),
        HttpManagementAddHandler.INSTANCE,
        HttpManagementRemoveHandler.INSTANCE,
        OperationEntry.Flag.RESTART_NONE,
        OperationEntry.Flag.RESTART_NONE);
  }

  @Override
  public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
    for (AttributeDefinition attr : ATTRIBUTE_DEFINITIONS) {
      resourceRegistration.registerReadWriteAttribute(
          attr, null, HttpManagementWriteAttributeHandler.INSTANCE);
    }
  }
}
/**
 * Domain extension that integrates Apache ActiveMQ 6.
 *
 * <dl>
 *   <dt><strong>Current</strong> - WildFly 10
 *   <dd>
 *       <ul>
 *         <li>XML namespace: urn:jboss:domain:messaging-activemq:1.0
 *         <li>Management model: 1.0.0
 *       </ul>
 * </dl>
 *
 * @author Emanuel Muckenhuber
 * @author <a href="mailto:[email protected]">Andy Taylor</a>
 * @author Brian Stansberry (c) 2011 Red Hat Inc.
 */
public class MessagingExtension implements Extension {

  public static final String SUBSYSTEM_NAME = "messaging-activemq";

  static final PathElement SUBSYSTEM_PATH = pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
  static final PathElement SERVER_PATH = pathElement(SERVER);
  public static final PathElement LIVE_ONLY_PATH = pathElement(HA_POLICY, LIVE_ONLY);
  public static final PathElement REPLICATION_MASTER_PATH =
      pathElement(HA_POLICY, REPLICATION_MASTER);
  public static final PathElement REPLICATION_SLAVE_PATH =
      pathElement(HA_POLICY, REPLICATION_SLAVE);
  public static final PathElement SHARED_STORE_MASTER_PATH =
      pathElement(HA_POLICY, SHARED_STORE_MASTER);
  public static final PathElement SHARED_STORE_SLAVE_PATH =
      pathElement(HA_POLICY, SHARED_STORE_SLAVE);
  public static final PathElement CONFIGURATION_MASTER_PATH = pathElement(CONFIGURATION, MASTER);
  public static final PathElement CONFIGURATION_SLAVE_PATH = pathElement(CONFIGURATION, SLAVE);
  static final PathElement BINDINGS_DIRECTORY_PATH = pathElement(PATH, BINDINGS_DIRECTORY);
  static final PathElement JOURNAL_DIRECTORY_PATH = pathElement(PATH, JOURNAL_DIRECTORY);
  static final PathElement PAGING_DIRECTORY_PATH = pathElement(PATH, PAGING_DIRECTORY);
  static final PathElement LARGE_MESSAGES_DIRECTORY_PATH =
      pathElement(PATH, LARGE_MESSAGES_DIRECTORY);
  static final PathElement CONNECTOR_SERVICE_PATH = pathElement(CONNECTOR_SERVICE);
  static final PathElement QUEUE_PATH = pathElement(QUEUE);
  static final PathElement RUNTIME_QUEUE_PATH = pathElement(RUNTIME_QUEUE);
  static final PathElement GROUPING_HANDLER_PATH = pathElement(GROUPING_HANDLER);
  static final PathElement HTTP_ACCEPTOR_PATH = pathElement(HTTP_ACCEPTOR);
  static final PathElement BROADCAST_GROUP_PATH = pathElement(BROADCAST_GROUP);
  static final PathElement CLUSTER_CONNECTION_PATH = pathElement(CLUSTER_CONNECTION);
  static final PathElement BRIDGE_PATH = pathElement(BRIDGE);
  static final PathElement ADDRESS_SETTING_PATH = pathElement(ADDRESS_SETTING);
  static final PathElement ROLE_PATH = pathElement(ROLE);
  static final PathElement SECURITY_SETTING_PATH = pathElement(SECURITY_SETTING);
  public static final PathElement JMS_QUEUE_PATH = pathElement(JMS_QUEUE);
  public static final PathElement JMS_TOPIC_PATH = pathElement(JMS_TOPIC);
  public static final PathElement POOLED_CONNECTION_FACTORY_PATH =
      pathElement(CommonAttributes.POOLED_CONNECTION_FACTORY);
  public static final PathElement CONNECTION_FACTORY_PATH =
      pathElement(CommonAttributes.CONNECTION_FACTORY);
  public static final PathElement JMS_BRIDGE_PATH = pathElement(CommonAttributes.JMS_BRIDGE);

  public static final SensitiveTargetAccessConstraintDefinition
      MESSAGING_SECURITY_SENSITIVE_TARGET =
          new SensitiveTargetAccessConstraintDefinition(
              new SensitivityClassification(
                  SUBSYSTEM_NAME, "messaging-security", false, false, true));
  public static final SensitiveTargetAccessConstraintDefinition
      MESSAGING_MANAGEMENT_SENSITIVE_TARGET =
          new SensitiveTargetAccessConstraintDefinition(
              new SensitivityClassification(
                  SUBSYSTEM_NAME, "messaging-management", false, false, true));

  static final AccessConstraintDefinition SECURITY_SETTING_ACCESS_CONSTRAINT =
      new ApplicationTypeAccessConstraintDefinition(
          new ApplicationTypeConfig(SUBSYSTEM_NAME, SECURITY_SETTING));
  static final AccessConstraintDefinition QUEUE_ACCESS_CONSTRAINT =
      new ApplicationTypeAccessConstraintDefinition(
          new ApplicationTypeConfig(SUBSYSTEM_NAME, QUEUE));
  public static final AccessConstraintDefinition JMS_QUEUE_ACCESS_CONSTRAINT =
      new ApplicationTypeAccessConstraintDefinition(
          new ApplicationTypeConfig(SUBSYSTEM_NAME, CommonAttributes.JMS_QUEUE));
  public static final AccessConstraintDefinition JMS_TOPIC_ACCESS_CONSTRAINT =
      new ApplicationTypeAccessConstraintDefinition(
          new ApplicationTypeConfig(SUBSYSTEM_NAME, CommonAttributes.JMS_TOPIC));

  static final String RESOURCE_NAME =
      MessagingExtension.class.getPackage().getName() + ".LocalDescriptions";

  private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(1, 0, 0);

  public static ResourceDescriptionResolver getResourceDescriptionResolver(
      final String... keyPrefix) {
    return getResourceDescriptionResolver(true, keyPrefix);
  }

  public static ResourceDescriptionResolver getResourceDescriptionResolver(
      final boolean useUnprefixedChildTypes, final String... keyPrefix) {
    StringBuilder prefix = new StringBuilder();
    for (String kp : keyPrefix) {
      if (prefix.length() > 0) {
        prefix.append('.');
      }
      prefix.append(kp);
    }
    return new StandardResourceDescriptionResolver(
        prefix.toString(),
        RESOURCE_NAME,
        MessagingExtension.class.getClassLoader(),
        true,
        useUnprefixedChildTypes);
  }

  public void initialize(ExtensionContext context) {
    final SubsystemRegistration subsystemRegistration =
        context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
    subsystemRegistration.registerXMLElementWriter(MessagingSubsystemParser_1_0.INSTANCE);

    boolean registerRuntimeOnly = context.isRuntimeOnlyRegistrationValid();

    // Root resource
    final ManagementResourceRegistration subsystem =
        subsystemRegistration.registerSubsystemModel(
            MessagingSubsystemRootResourceDefinition.INSTANCE);
    subsystem.registerOperationHandler(
        GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE);

    // ActiveMQ Servers
    final ManagementResourceRegistration server =
        subsystem.registerSubModel(new ServerDefinition(registerRuntimeOnly));

    for (PathDefinition path :
        new PathDefinition[] {
          PathDefinition.JOURNAL_INSTANCE,
          PathDefinition.BINDINGS_INSTANCE,
          PathDefinition.LARGE_MESSAGES_INSTANCE,
          PathDefinition.PAGING_INSTANCE
        }) {
      ManagementResourceRegistration pathRegistry = server.registerSubModel(path);
      PathDefinition.registerResolveOperationHandler(context, pathRegistry);
    }

    subsystem.registerSubModel(JMSBridgeDefinition.INSTANCE);

    if (registerRuntimeOnly) {
      final ManagementResourceRegistration deployment =
          subsystemRegistration.registerDeploymentModel(
              new SimpleResourceDefinition(
                  SUBSYSTEM_PATH, getResourceDescriptionResolver("deployed")));
      final ManagementResourceRegistration deployedServer =
          deployment.registerSubModel(
              new SimpleResourceDefinition(SERVER_PATH, getResourceDescriptionResolver(SERVER)));
      deployedServer.registerSubModel(JMSQueueDefinition.DEPLOYMENT_INSTANCE);
      deployedServer.registerSubModel(JMSTopicDefinition.DEPLOYMENT_INSTANCE);
      deployedServer.registerSubModel(PooledConnectionFactoryDefinition.DEPLOYMENT_INSTANCE);
    }
  }

  public void initializeParsers(ExtensionParsingContext context) {
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME,
        MessagingSubsystemParser_1_0.NAMESPACE,
        MessagingSubsystemParser_1_0.INSTANCE);
  }
}
Example #20
0
 /**
  * Indicates whether this model is more recent than the specified version and thus requires
  * transformation
  *
  * @param version a model version
  * @return true this this model is more recent than the specified version, false otherwise
  */
 default boolean requiresTransformation(ModelVersion version) {
   return ModelVersion.compare(this.getVersion(), version) < 0;
 }
Example #21
0
/** @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. */
public class UndertowExtension implements Extension {

  public static final String SUBSYSTEM_NAME = "undertow";
  public static final PathElement PATH_HANDLERS =
      PathElement.pathElement(Constants.CONFIGURATION, Constants.HANDLER);
  public static final PathElement PATH_FILTERS =
      PathElement.pathElement(Constants.CONFIGURATION, Constants.FILTER);
  protected static final PathElement PATH_JSP =
      PathElement.pathElement(Constants.SETTING, Constants.JSP);
  protected static final PathElement PATH_SESSION_COOKIE =
      PathElement.pathElement(Constants.SETTING, Constants.SESSION_COOKIE);
  protected static final PathElement PATH_PERSISTENT_SESSIONS =
      PathElement.pathElement(Constants.SETTING, Constants.PERSISTENT_SESSIONS);
  protected static final PathElement PATH_WEBSOCKETS =
      PathElement.pathElement(Constants.SETTING, Constants.WEBSOCKETS);
  protected static final PathElement PATH_MIME_MAPPING =
      PathElement.pathElement(Constants.MIME_MAPPING);
  protected static final PathElement PATH_WELCOME_FILE =
      PathElement.pathElement(Constants.WELCOME_FILE);
  protected static final PathElement SUBSYSTEM_PATH =
      PathElement.pathElement(SUBSYSTEM, SUBSYSTEM_NAME);
  protected static final PathElement AJP_LISTENER_PATH =
      PathElement.pathElement(Constants.AJP_LISTENER);
  protected static final PathElement HOST_PATH = PathElement.pathElement(Constants.HOST);
  protected static final PathElement HTTP_LISTENER_PATH =
      PathElement.pathElement(Constants.HTTP_LISTENER);
  protected static final PathElement HTTPS_LISTENER_PATH =
      PathElement.pathElement(Constants.HTTPS_LISTENER);
  protected static final PathElement PATH_SERVLET_CONTAINER =
      PathElement.pathElement(Constants.SERVLET_CONTAINER);
  protected static final PathElement PATH_BUFFER_CACHE =
      PathElement.pathElement(Constants.BUFFER_CACHE);
  protected static final PathElement PATH_LOCATION = PathElement.pathElement(Constants.LOCATION);
  protected static final PathElement SERVER_PATH = PathElement.pathElement(Constants.SERVER);
  protected static final PathElement PATH_ACCESS_LOG =
      PathElement.pathElement(Constants.SETTING, Constants.ACCESS_LOG);
  protected static final PathElement PATH_SSO =
      PathElement.pathElement(Constants.SETTING, Constants.SINGLE_SIGN_ON);
  public static final PathElement BALANCER = PathElement.pathElement(Constants.BALANCER);
  public static final PathElement CONTEXT = PathElement.pathElement(Constants.CONTEXT);
  public static final PathElement NODE = PathElement.pathElement(Constants.NODE);
  public static final PathElement PATH_FILTER_REF = PathElement.pathElement(Constants.FILTER_REF);
  private static final String RESOURCE_NAME =
      UndertowExtension.class.getPackage().getName() + ".LocalDescriptions";
  static final AccessConstraintDefinition LISTENER_CONSTRAINT =
      new SensitiveTargetAccessConstraintDefinition(
          new SensitivityClassification(SUBSYSTEM_NAME, "web-connector", false, false, false));

  private static final ModelVersion CURRENT_MODEL_VERSION = ModelVersion.create(3, 0, 0);

  public static StandardResourceDescriptionResolver getResolver(final String... keyPrefix) {
    StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);
    for (String kp : keyPrefix) {
      prefix.append('.').append(kp);
    }
    return new StandardResourceDescriptionResolver(
        prefix.toString(), RESOURCE_NAME, UndertowExtension.class.getClassLoader(), true, false);
  }

  @Override
  public void initializeParsers(ExtensionParsingContext context) {
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME,
        Namespace.UNDERTOW_1_0.getUriString(),
        UndertowSubsystemParser_1_0.INSTANCE);
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME,
        Namespace.UNDERTOW_1_1.getUriString(),
        UndertowSubsystemParser_1_1.INSTANCE);
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME,
        Namespace.UNDERTOW_1_2.getUriString(),
        UndertowSubsystemParser_1_2.INSTANCE);
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME,
        Namespace.UNDERTOW_2_0.getUriString(),
        UndertowSubsystemParser_2_0.INSTANCE);
    context.setSubsystemXmlMapping(
        SUBSYSTEM_NAME,
        Namespace.UNDERTOW_3_0.getUriString(),
        UndertowSubsystemParser_3_0.INSTANCE);
  }

  @Override
  public void initialize(ExtensionContext context) {
    final SubsystemRegistration subsystem =
        context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION);
    final ManagementResourceRegistration registration =
        subsystem.registerSubsystemModel(UndertowRootDefinition.INSTANCE);
    registration.registerOperationHandler(
        GenericSubsystemDescribeHandler.DEFINITION,
        GenericSubsystemDescribeHandler.INSTANCE,
        false);

    final ManagementResourceRegistration deployments =
        subsystem.registerDeploymentModel(DeploymentDefinition.INSTANCE);
    deployments.registerSubModel(DeploymentServletDefinition.INSTANCE);

    subsystem.registerXMLElementWriter(UndertowSubsystemParser_3_0.INSTANCE);
  }
}
  @Test
  public void testTransformers_1_1() throws Exception {
    final String subsystemXml = getSubsystemXml();
    final ModelVersion modelVersion = ModelVersion.create(1, 1, 0);
    final KernelServicesBuilder builder =
        createKernelServicesBuilder(LoggingTestEnvironment.getManagementInstance())
            .setSubsystemXml(subsystemXml);

    // which is why we need to include the jboss-as-controller artifact.
    builder
        .createLegacyKernelServicesBuilder(
            LoggingTestEnvironment.getManagementInstance(), modelVersion)
        .addMavenResourceURL("org.jboss.as:jboss-as-logging:7.1.2.Final")
        .addMavenResourceURL("org.jboss.as:jboss-as-controller:7.1.2.Final")
        .addParentFirstClassPattern("org.jboss.as.controller.*");

    KernelServices mainServices = builder.build();
    Assert.assertTrue(mainServices.isSuccessfulBoot());
    Assert.assertTrue(mainServices.getLegacyServices(modelVersion).isSuccessfulBoot());

    final ModelNode legacyModel = checkSubsystemModelTransformation(mainServices, modelVersion);

    final PathAddress consoleAddress =
        PathAddress.pathAddress(
            LoggingTestEnvironment.SUBSYSTEM_PATH,
            PathElement.pathElement(CommonAttributes.CONSOLE_HANDLER, "CONSOLE"));
    // Get all the console handler
    final ModelNode consoleHandler =
        legacyModel.get(
            consoleAddress.getElement(0).getKey(),
            consoleAddress.getElement(0).getValue(),
            consoleAddress.getElement(1).getKey(),
            consoleAddress.getElement(1).getValue());
    String formatPattern = consoleHandler.get(CommonAttributes.FORMATTER.getName()).asString();
    Assert.assertFalse(
        "Pattern ("
            + formatPattern
            + ") contains a color attribute not supported in legacy models.",
        COLOR_PATTERN.matcher(formatPattern).find());

    // Write a pattern with a %K{level} to ensure it gets removed
    ModelNode op =
        Operations.createWriteAttributeOperation(
            consoleAddress.toModelNode(), CommonAttributes.FORMATTER, "%K{level}" + formatPattern);
    executeTransformOperation(mainServices, modelVersion, op);
    validateLegacyFormatter(mainServices, modelVersion, consoleAddress.toModelNode());

    // Test update properties
    op =
        Operations.createOperation(
            AbstractHandlerDefinition.UPDATE_OPERATION_NAME, consoleAddress.toModelNode());
    op.get(CommonAttributes.FORMATTER.getName()).set("%K{level}" + formatPattern);
    executeTransformOperation(mainServices, modelVersion, op);
    validateLegacyFormatter(mainServices, modelVersion, consoleAddress.toModelNode());

    // Write out a filter-spec
    final String filterExpression = "not(match(\"ARJUNA\\\\d\"))";
    op =
        Operations.createWriteAttributeOperation(
            consoleAddress.toModelNode(), CommonAttributes.FILTER_SPEC, filterExpression);
    executeTransformOperation(mainServices, modelVersion, op);
    validateLegacyFilter(
        mainServices, modelVersion, consoleAddress.toModelNode(), filterExpression);

    // update-propertes on a filter spec
    op =
        Operations.createOperation(
            AbstractHandlerDefinition.UPDATE_OPERATION_NAME, consoleAddress.toModelNode());
    op.get(CommonAttributes.FILTER_SPEC.getName()).set(filterExpression);
    executeTransformOperation(mainServices, modelVersion, op);
    validateLegacyFilter(
        mainServices, modelVersion, consoleAddress.toModelNode(), filterExpression);

    final PathAddress loggerAddress =
        PathAddress.pathAddress(
            LoggingTestEnvironment.SUBSYSTEM_PATH,
            PathElement.pathElement(CommonAttributes.LOGGER, "org.jboss.as.logging"));
    // Verify the logger exists, add if it doesn't
    op = Operations.createReadResourceOperation(loggerAddress.toModelNode());
    if (!Operations.successful(mainServices.executeOperation(op))) {
      op = Operations.createAddOperation(loggerAddress.toModelNode());
      executeTransformOperation(mainServices, modelVersion, op);
    }

    // write a filter-spec
    op =
        Operations.createWriteAttributeOperation(
            loggerAddress.toModelNode(), CommonAttributes.FILTER_SPEC, filterExpression);
    executeTransformOperation(mainServices, modelVersion, op);
    validateLegacyFilter(mainServices, modelVersion, loggerAddress.toModelNode(), filterExpression);
  }
  private void registerTransformers(SubsystemRegistration subsystemRegistration) {
    ResourceTransformationDescriptionBuilder builder =
        TransformationDescriptionBuilder.Factory.createSubsystemInstance();
    ResourceTransformationDescriptionBuilder securityDomain =
        builder.addChildResource(SECURITY_DOMAIN_PATH);

    final ModulesToAttributeTransformer loginModule =
        new ModulesToAttributeTransformer(Constants.LOGIN_MODULE, Constants.LOGIN_MODULES);
    ResourceTransformationDescriptionBuilder child =
        securityDomain
            .addChildResource(PATH_CLASSIC_AUTHENTICATION)
            .setCustomResourceTransformer(loginModule)
            .addOperationTransformationOverride(ModelDescriptionConstants.ADD)
            .setCustomOperationTransformer(loginModule)
            .inheritResourceAttributeDefinitions()
            .end();
    child.discardChildResource(PathElement.pathElement(Constants.LOGIN_MODULE));

    final ModulesToAttributeTransformer policyModule =
        new ModulesToAttributeTransformer(Constants.POLICY_MODULE, Constants.POLICY_MODULES);

    child =
        securityDomain
            .addChildResource(PATH_AUTHORIZATION_CLASSIC)
            .setCustomResourceTransformer(policyModule)
            .addOperationTransformationOverride(ModelDescriptionConstants.ADD)
            .setCustomOperationTransformer(policyModule)
            .inheritResourceAttributeDefinitions()
            .end();
    child.discardChildResource(PathElement.pathElement(Constants.POLICY_MODULE));

    final ModulesToAttributeTransformer mappingModule =
        new ModulesToAttributeTransformer(Constants.MAPPING_MODULE, Constants.MAPPING_MODULES);

    child =
        securityDomain
            .addChildResource(PATH_MAPPING_CLASSIC)
            .setCustomResourceTransformer(mappingModule)
            .addOperationTransformationOverride(ModelDescriptionConstants.ADD)
            .setCustomOperationTransformer(mappingModule)
            .inheritResourceAttributeDefinitions()
            .end();
    child.discardChildResource(PathElement.pathElement(Constants.MAPPING_MODULE));

    final ModulesToAttributeTransformer providerModule =
        new ModulesToAttributeTransformer(Constants.PROVIDER_MODULE, Constants.PROVIDER_MODULES);

    child =
        securityDomain
            .addChildResource(PATH_AUDIT_CLASSIC)
            .setCustomResourceTransformer(providerModule)
            .addOperationTransformationOverride(ModelDescriptionConstants.ADD)
            .setCustomOperationTransformer(providerModule)
            .inheritResourceAttributeDefinitions()
            .end();
    child.discardChildResource(PathElement.pathElement(Constants.PROVIDER_MODULE));

    final ModulesToAttributeTransformer authModule =
        new ModulesToAttributeTransformer(Constants.AUTH_MODULE, Constants.AUTH_MODULES);

    ResourceTransformationDescriptionBuilder jaspiReg =
        securityDomain.addChildResource(PATH_JASPI_AUTH);
    jaspiReg
        .setCustomResourceTransformer(authModule)
        .addOperationTransformationOverride(ModelDescriptionConstants.ADD)
        .setCustomOperationTransformer(authModule)
        .inheritResourceAttributeDefinitions()
        .end();
    jaspiReg.discardChildResource(PathElement.pathElement(Constants.AUTH_MODULE));

    child =
        jaspiReg
            .addChildResource(PATH_LOGIN_MODULE_STACK)
            .setCustomResourceTransformer(loginModule)
            .addOperationTransformationOverride(ModelDescriptionConstants.ADD)
            .setCustomOperationTransformer(loginModule)
            .inheritResourceAttributeDefinitions()
            .end();
    child.discardChildResource(PathElement.pathElement(Constants.LOGIN_MODULE));

    // reject expressions
    securityDomain
        .getAttributeBuilder()
        .addRejectCheck(
            RejectAttributeChecker.SIMPLE_EXPRESSIONS, SecurityDomainResourceDefinition.CACHE_TYPE)
        .end();
    builder
        .addChildResource(VAULT_PATH)
        .getAttributeBuilder()
        .addRejectCheck(RejectAttributeChecker.SIMPLE_EXPRESSIONS, VaultResourceDefinition.CODE)
        .addRejectCheck(
            RejectAttributeChecker.SIMPLE_LIST_EXPRESSIONS, VaultResourceDefinition.OPTIONS)
        .end();
    builder
        .addChildResource(JSSE_PATH)
        .getAttributeBuilder()
        .addRejectCheck(
            new RejectAttributeChecker.ObjectFieldsRejectAttributeChecker(
                Collections.singletonMap(
                    JSSEResourceDefinition.ADDITIONAL_PROPERTIES.getName(),
                    RejectAttributeChecker.SIMPLE_EXPRESSIONS)),
            JSSEResourceDefinition.ADDITIONAL_PROPERTIES)
        .end();

    TransformationDescription.Tools.register(
        builder.build(), subsystemRegistration, ModelVersion.create(1, 1, 0));
  }
 @Override
 public void addSubsystemVersion(String subsystemName, int majorVersion, int minorVersion) {
   addSubsystemVersion(subsystemName, ModelVersion.create(majorVersion, minorVersion));
 }
/**
 * {@link org.jboss.as.controller.ResourceDefinition} for the root resource of the transaction
 * subsystem.
 *
 * @author Brian Stansberry (c) 2011 Red Hat Inc.
 */
public class TransactionSubsystemRootResourceDefinition extends SimpleResourceDefinition {

  public static final RuntimeCapability<Void> TRANSACTION_CAPABILITY =
      RuntimeCapability.Builder.of("org.wildfly.transactions").build();

  // recovery environment
  public static final SimpleAttributeDefinition BINDING =
      new SimpleAttributeDefinitionBuilder(CommonAttributes.BINDING, ModelType.STRING, false)
          .setValidator(new StringLengthValidator(1))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .setXmlName(Attribute.BINDING.getLocalName())
          .setAllowExpression(true)
          .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF)
          .build();

  public static final SimpleAttributeDefinition STATUS_BINDING =
      new SimpleAttributeDefinitionBuilder(CommonAttributes.STATUS_BINDING, ModelType.STRING, false)
          .setValidator(new StringLengthValidator(1))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .setXmlName(Attribute.STATUS_BINDING.getLocalName())
          .setAllowExpression(true)
          .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF)
          .build();

  public static final SimpleAttributeDefinition RECOVERY_LISTENER =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.RECOVERY_LISTENER, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode().set(false))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .setXmlName(Attribute.RECOVERY_LISTENER.getLocalName())
          .setAllowExpression(true)
          .build();

  // core environment
  public static final SimpleAttributeDefinition NODE_IDENTIFIER =
      new SimpleAttributeDefinitionBuilder(CommonAttributes.NODE_IDENTIFIER, ModelType.STRING, true)
          .setDefaultValue(new ModelNode().set("1"))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .setAllowExpression(true)
          .setValidator(new StringBytesLengthValidator(0, 23, true, true))
          .build();

  public static final SimpleAttributeDefinition PROCESS_ID_UUID =
      new SimpleAttributeDefinitionBuilder("process-id-uuid", ModelType.BOOLEAN, false)
          .setDefaultValue(new ModelNode().set(false))
          .setAlternatives("process-id-socket-binding")
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .build();

  public static final SimpleAttributeDefinition PROCESS_ID_SOCKET_BINDING =
      new SimpleAttributeDefinitionBuilder("process-id-socket-binding", ModelType.STRING, false)
          .setValidator(new StringLengthValidator(1, true))
          .setAlternatives("process-id-uuid")
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .setXmlName(Attribute.BINDING.getLocalName())
          .setAllowExpression(true)
          .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF)
          .build();

  public static final SimpleAttributeDefinition PROCESS_ID_SOCKET_MAX_PORTS =
      new SimpleAttributeDefinitionBuilder("process-id-socket-max-ports", ModelType.INT, true)
          .setValidator(new IntRangeValidator(1, true))
          .setDefaultValue(new ModelNode().set(10))
          .setRequires("process-id-socket-binding")
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .setXmlName(Attribute.SOCKET_PROCESS_ID_MAX_PORTS.getLocalName())
          .setAllowExpression(true)
          .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_CONFIG)
          .build();

  // coordinator environment
  public static final SimpleAttributeDefinition STATISTICS_ENABLED =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.STATISTICS_ENABLED, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode().set(false))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) // TODO should be runtime-changeable
          .setAllowExpression(true)
          .build();

  public static final SimpleAttributeDefinition ENABLE_STATISTICS =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.ENABLE_STATISTICS, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode().set(false))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) // TODO should be runtime-changeable
          .setXmlName(Attribute.ENABLE_STATISTICS.getLocalName())
          .setDeprecated(ModelVersion.create(2))
          .setAllowExpression(true)
          .build();

  public static final SimpleAttributeDefinition ENABLE_TSM_STATUS =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.ENABLE_TSM_STATUS, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode().set(false))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) // TODO is this runtime-changeable?
          .setXmlName(Attribute.ENABLE_TSM_STATUS.getLocalName())
          .setAllowExpression(true)
          .build();

  public static final SimpleAttributeDefinition DEFAULT_TIMEOUT =
      new SimpleAttributeDefinitionBuilder(CommonAttributes.DEFAULT_TIMEOUT, ModelType.INT, true)
          .setMeasurementUnit(MeasurementUnit.SECONDS)
          .setDefaultValue(new ModelNode().set(300))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) // TODO is this runtime-changeable?
          .setXmlName(Attribute.DEFAULT_TIMEOUT.getLocalName())
          .setAllowExpression(true)
          .build();

  // object store
  public static final SimpleAttributeDefinition OBJECT_STORE_RELATIVE_TO =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.OBJECT_STORE_RELATIVE_TO, ModelType.STRING, true)
          .setDefaultValue(new ModelNode().set("jboss.server.data.dir"))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .setXmlName(Attribute.RELATIVE_TO.getLocalName())
          .setAllowExpression(true)
          .build();
  public static final SimpleAttributeDefinition OBJECT_STORE_PATH =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.OBJECT_STORE_PATH, ModelType.STRING, true)
          .setDefaultValue(new ModelNode().set("tx-object-store"))
          .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
          .setXmlName(Attribute.PATH.getLocalName())
          .setAllowExpression(true)
          .build();

  public static final SimpleAttributeDefinition JTS =
      new SimpleAttributeDefinitionBuilder(CommonAttributes.JTS, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode().set(false))
          .setFlags(
              AttributeAccess.Flag
                  .RESTART_JVM) // I think the use of statics in arjunta will require a JVM restart
          .setAllowExpression(false)
          .build();

  public static final SimpleAttributeDefinition USEHORNETQSTORE =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.USEHORNETQSTORE, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode().set(false))
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setAlternatives(CommonAttributes.USE_JDBC_STORE)
          .setAllowExpression(false)
          .build();
  public static final SimpleAttributeDefinition HORNETQ_STORE_ENABLE_ASYNC_IO =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.HORNETQ_STORE_ENABLE_ASYNC_IO, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode().set(false))
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setXmlName(Attribute.ENABLE_ASYNC_IO.getLocalName())
          .setAllowExpression(true)
          .setRequires(CommonAttributes.USEHORNETQSTORE)
          .build();

  public static final SimpleAttributeDefinition USE_JDBC_STORE =
      new SimpleAttributeDefinitionBuilder(CommonAttributes.USE_JDBC_STORE, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode(false))
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setAlternatives(CommonAttributes.USEHORNETQSTORE)
          .setAllowExpression(false)
          .build();
  public static final SimpleAttributeDefinition JDBC_STORE_DATASOURCE =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.JDBC_STORE_DATASOURCE, ModelType.STRING, true)
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setXmlName(Attribute.DATASOURCE_JNDI_NAME.getLocalName())
          .setAllowExpression(true)
          .setRequires(CommonAttributes.USE_JDBC_STORE)
          .build();
  public static final SimpleAttributeDefinition JDBC_ACTION_STORE_TABLE_PREFIX =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.JDBC_ACTION_STORE_TABLE_PREFIX, ModelType.STRING, true)
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setXmlName(Attribute.TABLE_PREFIX.getLocalName())
          .setAllowExpression(true)
          .setRequires(CommonAttributes.USE_JDBC_STORE)
          .build();
  public static final SimpleAttributeDefinition JDBC_ACTION_STORE_DROP_TABLE =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.JDBC_ACTION_STORE_DROP_TABLE, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode(false))
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setXmlName(Attribute.DROP_TABLE.getLocalName())
          .setAllowExpression(true)
          .setRequires(CommonAttributes.USE_JDBC_STORE)
          .build();
  public static final SimpleAttributeDefinition JDBC_COMMUNICATION_STORE_TABLE_PREFIX =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.JDBC_COMMUNICATION_STORE_TABLE_PREFIX, ModelType.STRING, true)
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setXmlName(Attribute.TABLE_PREFIX.getLocalName())
          .setAllowExpression(true)
          .setRequires(CommonAttributes.USE_JDBC_STORE)
          .build();
  public static final SimpleAttributeDefinition JDBC_COMMUNICATION_STORE_DROP_TABLE =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.JDBC_COMMUNICATION_STORE_DROP_TABLE, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode(false))
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setXmlName(Attribute.DROP_TABLE.getLocalName())
          .setAllowExpression(true)
          .setRequires(CommonAttributes.USE_JDBC_STORE)
          .build();
  public static final SimpleAttributeDefinition JDBC_STATE_STORE_TABLE_PREFIX =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.JDBC_STATE_STORE_TABLE_PREFIX, ModelType.STRING, true)
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setXmlName(Attribute.TABLE_PREFIX.getLocalName())
          .setAllowExpression(true)
          .setRequires(CommonAttributes.USE_JDBC_STORE)
          .build();
  public static final SimpleAttributeDefinition JDBC_STATE_STORE_DROP_TABLE =
      new SimpleAttributeDefinitionBuilder(
              CommonAttributes.JDBC_STATE_STORE_DROP_TABLE, ModelType.BOOLEAN, true)
          .setDefaultValue(new ModelNode(false))
          .setFlags(AttributeAccess.Flag.RESTART_JVM)
          .setXmlName(Attribute.DROP_TABLE.getLocalName())
          .setAllowExpression(true)
          .setRequires(CommonAttributes.USE_JDBC_STORE)
          .build();

  private final boolean registerRuntimeOnly;

  TransactionSubsystemRootResourceDefinition(boolean registerRuntimeOnly) {
    super(
        TransactionExtension.SUBSYSTEM_PATH,
        TransactionExtension.getResourceDescriptionResolver(),
        TransactionSubsystemAdd.INSTANCE,
        TransactionSubsystemRemove.INSTANCE,
        OperationEntry.Flag.RESTART_ALL_SERVICES,
        OperationEntry.Flag.RESTART_ALL_SERVICES);
    this.registerRuntimeOnly = registerRuntimeOnly;
  }

  // all attributes
  static final AttributeDefinition[] attributes =
      new AttributeDefinition[] {
        BINDING,
        STATUS_BINDING,
        RECOVERY_LISTENER,
        NODE_IDENTIFIER,
        PROCESS_ID_UUID,
        PROCESS_ID_SOCKET_BINDING,
        PROCESS_ID_SOCKET_MAX_PORTS,
        STATISTICS_ENABLED,
        ENABLE_TSM_STATUS,
        DEFAULT_TIMEOUT,
        OBJECT_STORE_RELATIVE_TO,
        OBJECT_STORE_PATH,
        JTS,
        USEHORNETQSTORE,
        USE_JDBC_STORE,
        JDBC_STORE_DATASOURCE,
        JDBC_ACTION_STORE_DROP_TABLE,
        JDBC_ACTION_STORE_TABLE_PREFIX,
        JDBC_COMMUNICATION_STORE_DROP_TABLE,
        JDBC_COMMUNICATION_STORE_TABLE_PREFIX,
        JDBC_STATE_STORE_DROP_TABLE,
        JDBC_STATE_STORE_TABLE_PREFIX,
        HORNETQ_STORE_ENABLE_ASYNC_IO
      };

  static final AttributeDefinition[] ATTRIBUTES_WITH_EXPRESSIONS_AFTER_1_1_0 =
      new AttributeDefinition[] {
        DEFAULT_TIMEOUT,
        STATISTICS_ENABLED,
        ENABLE_STATISTICS,
        ENABLE_TSM_STATUS,
        NODE_IDENTIFIER,
        OBJECT_STORE_PATH,
        OBJECT_STORE_RELATIVE_TO,
        PROCESS_ID_SOCKET_BINDING,
        PROCESS_ID_SOCKET_MAX_PORTS,
        RECOVERY_LISTENER,
        BINDING,
        STATUS_BINDING
      };

  static final AttributeDefinition[] ATTRIBUTES_WITH_EXPRESSIONS_AFTER_1_1_1 =
      new AttributeDefinition[] {JTS, USEHORNETQSTORE};

  static final AttributeDefinition[] attributes_1_2 =
      new AttributeDefinition[] {
        USE_JDBC_STORE,
        JDBC_STORE_DATASOURCE,
        JDBC_ACTION_STORE_DROP_TABLE,
        JDBC_ACTION_STORE_TABLE_PREFIX,
        JDBC_COMMUNICATION_STORE_DROP_TABLE,
        JDBC_COMMUNICATION_STORE_TABLE_PREFIX,
        JDBC_STATE_STORE_DROP_TABLE,
        JDBC_STATE_STORE_TABLE_PREFIX
      };

  @Override
  public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
    // Register all attributes except of the mutual ones
    Set<AttributeDefinition> attributesWithoutMutuals = new HashSet<>(Arrays.asList(attributes));
    attributesWithoutMutuals.remove(USEHORNETQSTORE);
    attributesWithoutMutuals.remove(USE_JDBC_STORE);

    attributesWithoutMutuals.remove(PROCESS_ID_UUID);
    attributesWithoutMutuals.remove(PROCESS_ID_SOCKET_BINDING);
    attributesWithoutMutuals.remove(PROCESS_ID_SOCKET_MAX_PORTS);

    OperationStepHandler writeHandler =
        new ReloadRequiredWriteAttributeHandler(attributesWithoutMutuals);
    for (final AttributeDefinition def : attributesWithoutMutuals) {
      resourceRegistration.registerReadWriteAttribute(def, null, writeHandler);
    }

    // Register mutual object store attributes
    OperationStepHandler mutualWriteHandler =
        new ObjectStoreMutualWriteHandler(USEHORNETQSTORE, USE_JDBC_STORE);
    resourceRegistration.registerReadWriteAttribute(USEHORNETQSTORE, null, mutualWriteHandler);
    resourceRegistration.registerReadWriteAttribute(USE_JDBC_STORE, null, mutualWriteHandler);

    // Register mutual object store attributes
    OperationStepHandler mutualProcessIdWriteHandler =
        new ProcessIdWriteHandler(
            PROCESS_ID_UUID, PROCESS_ID_SOCKET_BINDING, PROCESS_ID_SOCKET_MAX_PORTS);
    resourceRegistration.registerReadWriteAttribute(
        PROCESS_ID_UUID, null, mutualProcessIdWriteHandler);
    resourceRegistration.registerReadWriteAttribute(
        PROCESS_ID_SOCKET_BINDING, null, mutualProcessIdWriteHandler);
    resourceRegistration.registerReadWriteAttribute(
        PROCESS_ID_SOCKET_MAX_PORTS, null, mutualProcessIdWriteHandler);

    EnableStatisticsHandler esh = new EnableStatisticsHandler();
    resourceRegistration.registerReadWriteAttribute(ENABLE_STATISTICS, esh, esh);

    if (registerRuntimeOnly) {
      TxStatsHandler.INSTANCE.registerMetrics(resourceRegistration);
    }
  }

  @Override
  public void registerCapabilities(ManagementResourceRegistration resourceRegistration) {
    resourceRegistration.registerCapability(TRANSACTION_CAPABILITY);
  }

  private static class EnableStatisticsHandler implements OperationStepHandler {

    @Override
    public void execute(OperationContext context, ModelNode operation)
        throws OperationFailedException {
      ModelNode aliased = getAliasedOperation(operation);
      context.addStep(
          aliased, getHandlerForOperation(context, operation), OperationContext.Stage.MODEL, true);
      context.stepCompleted();
    }

    private static ModelNode getAliasedOperation(ModelNode operation) {
      ModelNode aliased = operation.clone();
      aliased.get(ModelDescriptionConstants.NAME).set(STATISTICS_ENABLED.getName());
      return aliased;
    }

    private static OperationStepHandler getHandlerForOperation(
        OperationContext context, ModelNode operation) {
      ImmutableManagementResourceRegistration imrr = context.getResourceRegistration();
      return imrr.getOperationHandler(PathAddress.EMPTY_ADDRESS, operation.get(OP).asString());
    }
  }

  private static class ObjectStoreMutualWriteHandler extends ReloadRequiredWriteAttributeHandler {
    public ObjectStoreMutualWriteHandler(final AttributeDefinition... definitions) {
      super(definitions);
    }

    @Override
    protected void finishModelStage(
        final OperationContext context,
        final ModelNode operation,
        String attributeName,
        ModelNode newValue,
        ModelNode oldValue,
        final Resource model)
        throws OperationFailedException {
      super.finishModelStage(context, operation, attributeName, newValue, oldValue, model);

      assert !USEHORNETQSTORE.isAllowExpression() && !USE_JDBC_STORE.isAllowExpression()
          : "rework this before enabling expression";

      if (attributeName.equals(USEHORNETQSTORE.getName())
          || attributeName.equals(USE_JDBC_STORE.getName())) {
        if (newValue.asBoolean() == true) {
          // check the value of the mutual attribute and disable it if it is set to true
          final String mutualAttributeName =
              attributeName.equals(USE_JDBC_STORE.getName())
                  ? USEHORNETQSTORE.getName()
                  : USE_JDBC_STORE.getName();

          ModelNode resourceModel = model.getModel();
          if (resourceModel.hasDefined(mutualAttributeName)
              && resourceModel.get(mutualAttributeName).asBoolean()) {
            resourceModel.get(mutualAttributeName).set(new ModelNode(false));
          }
        }
      }
    }
  }

  private static class ProcessIdWriteHandler extends ReloadRequiredWriteAttributeHandler {
    public ProcessIdWriteHandler(final AttributeDefinition... definitions) {
      super(definitions);
    }

    @Override
    protected void validateUpdatedModel(final OperationContext context, final Resource model)
        throws OperationFailedException {
      context.addStep(
          model.getModel(),
          new OperationStepHandler() {
            @Override
            public void execute(OperationContext operationContext, ModelNode node)
                throws OperationFailedException {
              if (node.hasDefined(
                      TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName())
                  && node.get(TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName())
                      .asBoolean()) {
                if (node.hasDefined(
                    TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING
                        .getName())) {
                  throw TransactionLogger.ROOT_LOGGER.mustBeUndefinedIfTrue(
                      TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING
                          .getName(),
                      TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName());
                } else if (node.hasDefined(
                    TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS
                        .getName())) {
                  throw TransactionLogger.ROOT_LOGGER.mustBeUndefinedIfTrue(
                      TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS
                          .getName(),
                      TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName());
                }
              } else if (node.hasDefined(
                  TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName())) {
                // it's fine do nothing
              } else if (node.hasDefined(
                  TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS
                      .getName())) {
                throw TransactionLogger.ROOT_LOGGER.mustBedefinedIfDefined(
                    TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName(),
                    TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_MAX_PORTS
                        .getName());
              } else {
                // not uuid and also not sockets!
                throw TransactionLogger.ROOT_LOGGER.eitherTrueOrDefined(
                    TransactionSubsystemRootResourceDefinition.PROCESS_ID_UUID.getName(),
                    TransactionSubsystemRootResourceDefinition.PROCESS_ID_SOCKET_BINDING.getName());
              }

              context.stepCompleted();
            }
          },
          OperationContext.Stage.MODEL);
    }

    @Override
    protected void finishModelStage(
        final OperationContext context,
        final ModelNode operation,
        String attributeName,
        ModelNode newValue,
        ModelNode oldValue,
        final Resource model)
        throws OperationFailedException {

      if (attributeName.equals(PROCESS_ID_SOCKET_BINDING.getName())) {
        if (newValue.isDefined()) {

          ModelNode resourceModel = model.getModel();
          if (resourceModel.hasDefined(PROCESS_ID_UUID.getName())
              && resourceModel.get(PROCESS_ID_UUID.getName()).asBoolean()) {
            resourceModel.get(PROCESS_ID_UUID.getName()).set(new ModelNode(false));
          }
        }
      }

      if (attributeName.equals(PROCESS_ID_UUID.getName())) {
        if (newValue.asBoolean(false)) {

          ModelNode resourceModel = model.getModel();
          resourceModel.get(PROCESS_ID_SOCKET_BINDING.getName()).clear();
          resourceModel.get(PROCESS_ID_SOCKET_MAX_PORTS.getName()).clear();
        }
      }

      validateUpdatedModel(context, model);
    }
  }

  @Override
  public void registerChildren(ManagementResourceRegistration resourceRegistration) {
    resourceRegistration.registerSubModel(new CMResourceResourceDefinition());
  }
}
  @Test
  public void testDeploymentOverlaysIgnoredOnOlderVersionGetIgnored() throws Exception {
    if (modelVersion.getMajor() > 1 || modelVersion.getMinor() >= 4) {
      return;
    }

    KernelServicesBuilder builder =
        createKernelServicesBuilder(TestModelType.DOMAIN)
            .setModelInitializer(
                StandardServerGroupInitializers.XML_MODEL_INITIALIZER,
                StandardServerGroupInitializers.XML_MODEL_WRITE_SANITIZER)
            .createContentRepositoryContent("12345678901234567890")
            .setXmlResource("domain-no-servergroup-overlay.xml");

    // Start up an empty legacy controller
    StandardServerGroupInitializers.addServerGroupInitializers(
            builder.createLegacyKernelServicesBuilder(modelVersion, testControllerVersion))
        .setDontUseBootOperations()
        // Since the legacy controller does not know about deployment overlays, there will be not
        // boot ops for the reverse check
        .skipReverseControllerCheck();

    KernelServices mainServices = builder.build();
    Assert.assertTrue(mainServices.isSuccessfulBoot());
    KernelServices legacyServices = mainServices.getLegacyServices(modelVersion);
    Assert.assertTrue(legacyServices.isSuccessfulBoot());

    // This should pass since the deployment-overlay resource is ignored, and there is no use of
    // deployment-overlay in server-group
    mainServices.applyMasterDomainModel(
        modelVersion,
        Collections.singletonList(
            new IgnoreDomainResourceTypeResource(
                ModelDescriptionConstants.DEPLOYMENT_OVERLAY, new ModelNode(), true)));

    // Check deployment overlays exist in the master model but not in the legacy model
    ModelNode masterModel = mainServices.readWholeModel();
    ModelNode legacyModel = legacyServices.readWholeModel();
    Assert.assertTrue(
        masterModel.hasDefined(ModelDescriptionConstants.DEPLOYMENT_OVERLAY)
            && masterModel
                .get(ModelDescriptionConstants.DEPLOYMENT_OVERLAY)
                .hasDefined("test-overlay"));
    Assert.assertFalse(legacyModel.hasDefined(ModelDescriptionConstants.DEPLOYMENT_OVERLAY));

    // Compare the transformed and legacy models
    checkCoreModelTransformation(
        mainServices,
        modelVersion,
        new ModelFixer() {
          @Override
          public ModelNode fixModel(ModelNode modelNode) {
            // This one is just noise due to a different format
            // Perhaps this should go into the model comparison itself?
            ModelNode socketBindingGroup = modelNode.get(SOCKET_BINDING_GROUP, "test-sockets");
            if (socketBindingGroup.isDefined()) {
              Set<String> names = new HashSet<String>();
              for (String key : socketBindingGroup.keys()) {
                if (!socketBindingGroup.get(key).isDefined()) {
                  names.add(key);
                }
              }
              for (String name : names) {
                socketBindingGroup.remove(name);
              }
              if (socketBindingGroup.keys().size() == 0) {
                socketBindingGroup.clear();
              }
            }
            return modelNode;
          }
        },
        new ModelFixer() {
          @Override
          public ModelNode fixModel(ModelNode modelNode) {
            modelNode.remove(ModelDescriptionConstants.DEPLOYMENT_OVERLAY);
            return modelNode;
          }
        });
  }
/**
 * @author <a href="mailto:[email protected]">Tomaz Cerar</a>
 * @author <a href="mailto:[email protected]">James R. Perkins</a>
 */
class AsyncHandlerResourceDefinition extends AbstractHandlerDefinition {

  public static final String ADD_SUBHANDLER_OPERATION_NAME = "assign-subhandler";
  public static final String REMOVE_SUBHANDLER_OPERATION_NAME = "unassign-subhandler";
  public static final String ASYNC_HANDLER = "async-handler";
  static final PathElement ASYNC_HANDLER_PATH = PathElement.pathElement(ASYNC_HANDLER);

  static final SimpleOperationDefinition ADD_HANDLER =
      new SimpleOperationDefinitionBuilder(ADD_HANDLER_OPERATION_NAME, HANDLER_RESOLVER)
          .setParameters(CommonAttributes.HANDLER_NAME)
          .build();

  static final SimpleOperationDefinition REMOVE_HANDLER =
      new SimpleOperationDefinitionBuilder(REMOVE_HANDLER_OPERATION_NAME, HANDLER_RESOLVER)
          .setParameters(CommonAttributes.HANDLER_NAME)
          .build();

  static final SimpleOperationDefinition LEGACY_ADD_HANDLER =
      new SimpleOperationDefinitionBuilder(ADD_SUBHANDLER_OPERATION_NAME, HANDLER_RESOLVER)
          .setDeprecated(ModelVersion.create(1, 2, 0))
          .setParameters(CommonAttributes.HANDLER_NAME)
          .build();

  static final SimpleOperationDefinition LEGACY_REMOVE_HANDLER =
      new SimpleOperationDefinitionBuilder(REMOVE_SUBHANDLER_OPERATION_NAME, HANDLER_RESOLVER)
          .setDeprecated(ModelVersion.create(1, 2, 0))
          .setParameters(CommonAttributes.HANDLER_NAME)
          .build();

  public static final PropertyAttributeDefinition QUEUE_LENGTH =
      PropertyAttributeDefinition.Builder.of("queue-length", ModelType.INT)
          .setAllowExpression(true)
          .setAttributeMarshaller(ElementAttributeMarshaller.VALUE_ATTRIBUTE_MARSHALLER)
          .setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
          .setPropertyName("queueLength")
          .setValidator(new IntRangeValidator(1, false))
          .build();

  public static final PropertyAttributeDefinition OVERFLOW_ACTION =
      PropertyAttributeDefinition.Builder.of("overflow-action", ModelType.STRING)
          .setAllowExpression(true)
          .setAttributeMarshaller(
              new DefaultAttributeMarshaller() {
                @Override
                public void marshallAsElement(
                    final AttributeDefinition attribute,
                    final ModelNode resourceModel,
                    final boolean marshallDefault,
                    final XMLStreamWriter writer)
                    throws XMLStreamException {
                  if (isMarshallable(attribute, resourceModel, marshallDefault)) {
                    writer.writeStartElement(attribute.getXmlName());
                    String content =
                        resourceModel
                            .get(attribute.getName())
                            .asString()
                            .toLowerCase(Locale.ENGLISH);
                    writer.writeAttribute("value", content);
                    writer.writeEndElement();
                  }
                }
              })
          .setDefaultValue(new ModelNode(OverflowAction.BLOCK.name()))
          .setPropertyName("overflowAction")
          .setResolver(OverflowActionResolver.INSTANCE)
          .setValidator(EnumValidator.create(OverflowAction.class, false, false))
          .build();

  public static final LogHandlerListAttributeDefinition SUBHANDLERS =
      LogHandlerListAttributeDefinition.Builder.of("subhandlers")
          .setAllowExpression(false)
          .setAllowNull(true)
          .build();

  static final AttributeDefinition[] ATTRIBUTES =
      Logging.join(DEFAULT_ATTRIBUTES, QUEUE_LENGTH, OVERFLOW_ACTION, SUBHANDLERS);

  public AsyncHandlerResourceDefinition(final boolean includeLegacyAttributes) {
    super(
        ASYNC_HANDLER_PATH,
        AsyncHandler.class,
        (includeLegacyAttributes ? Logging.join(ATTRIBUTES, LEGACY_ATTRIBUTES) : ATTRIBUTES),
        QUEUE_LENGTH);
  }

  @Override
  public void registerOperations(final ManagementResourceRegistration registration) {
    super.registerOperations(registration);

    registration.registerOperationHandler(LEGACY_ADD_HANDLER, HandlerOperations.ADD_SUBHANDLER);
    registration.registerOperationHandler(
        LEGACY_REMOVE_HANDLER, HandlerOperations.REMOVE_SUBHANDLER);
    registration.registerOperationHandler(ADD_HANDLER, HandlerOperations.ADD_SUBHANDLER);
    registration.registerOperationHandler(REMOVE_HANDLER, HandlerOperations.REMOVE_SUBHANDLER);
  }

  /**
   * Add the transformers for the async handler.
   *
   * @param subsystemBuilder the default subsystem builder
   * @param loggingProfileBuilder the logging profile builder
   * @return the builder created for the resource
   */
  static ResourceTransformationDescriptionBuilder addTransformers(
      final ResourceTransformationDescriptionBuilder subsystemBuilder,
      final ResourceTransformationDescriptionBuilder loggingProfileBuilder) {
    // Register the logger resource
    final ResourceTransformationDescriptionBuilder child =
        subsystemBuilder
            .addChildResource(ASYNC_HANDLER_PATH)
            .getAttributeBuilder()
            .addRejectCheck(
                RejectAttributeChecker.SIMPLE_EXPRESSIONS, QUEUE_LENGTH, OVERFLOW_ACTION)
            .end()
            .addOperationTransformationOverride(ADD_HANDLER_OPERATION_NAME)
            .setCustomOperationTransformer(LoggingOperationTransformer.INSTANCE)
            .end()
            .addOperationTransformationOverride(REMOVE_HANDLER_OPERATION_NAME)
            .setCustomOperationTransformer(LoggingOperationTransformer.INSTANCE)
            .end();

    // Reject logging profile resources
    loggingProfileBuilder.rejectChildResource(ASYNC_HANDLER_PATH);

    return registerTransformers(child);
  }
}