@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);
  }
Example #2
0
    @Override
    public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context)
        throws XMLStreamException {
      context.startSubsystemElement(Namespace.CURRENT.getUriString(), false);
      ModelNode node = context.getModelNode();

      if (has(node, ACTIVATION)) {
        writeAttribute(writer, Attribute.ACTIVATION, node.get(ACTIVATION));
      }

      if (has(node, CONFIGURATION)) {
        ModelNode configuration = node.get(CONFIGURATION);
        writer.writeStartElement(Element.CONFIGURATION.getLocalName());
        writeAttribute(writer, Attribute.PID, configuration.require(PID));
        if (has(configuration, CONFIGURATION_PROPERTIES)) {
          ModelNode configurationProperties = configuration.get(CONFIGURATION_PROPERTIES);
          Set<String> keys = configurationProperties.keys();
          for (String current : keys) {
            String value = configurationProperties.get(current).asString();
            writer.writeStartElement(Element.PROPERTY.getLocalName());
            writer.writeAttribute(Attribute.NAME.getLocalName(), current);
            writer.writeCharacters(value);
            writer.writeEndElement();
          }
        }
        writer.writeEndElement();
      }

      if (has(node, PROPERTIES)) {
        ModelNode properties = node.get(PROPERTIES);
        writer.writeStartElement(Element.PROPERTIES.getLocalName());
        Set<String> keys = properties.keys();
        for (String current : keys) {
          String value = properties.get(current).asString();
          writer.writeStartElement(Element.PROPERTY.getLocalName());
          writer.writeAttribute(Attribute.NAME.getLocalName(), current);
          writer.writeCharacters(value);
          writer.writeEndElement();
        }
        writer.writeEndElement();
      }

      if (has(node, MODULES)) {
        ModelNode modules = node.get(MODULES);
        writer.writeStartElement(Element.MODULES.getLocalName());
        Set<String> keys = modules.keys();
        for (String current : keys) {
          ModelNode currentModule = modules.get(current);
          writer.writeEmptyElement(Element.MODULE.getLocalName());
          writer.writeAttribute(Attribute.IDENTIFIER.getLocalName(), current);
          if (has(currentModule, START)) {
            writeAttribute(writer, Attribute.START, currentModule.require(START));
          }
        }
        writer.writeEndElement();
      }
      writer.writeEndElement();
    }
  /**
   * Compares two models to make sure that they are the same
   *
   * @param node1 the first model
   * @param node2 the second model
   * @throws AssertionFailedError if the models were not the same
   */
  protected void compare(ModelNode node1, ModelNode node2) {
    Assert.assertEquals(getCompareStackAsString() + " types", node1.getType(), node2.getType());
    if (node1.getType() == ModelType.OBJECT) {
      final Set<String> keys1 = node1.keys();
      final Set<String> keys2 = node2.keys();
      Assert.assertEquals(node1 + "\n" + node2, keys1.size(), keys2.size());

      for (String key : keys1) {
        final ModelNode child1 = node1.get(key);
        Assert.assertTrue("Missing: " + key + "\n" + node1 + "\n" + node2, node2.has(key));
        final ModelNode child2 = node2.get(key);
        if (child1.isDefined()) {
          Assert.assertTrue(child1.toString(), child2.isDefined());
          stack.get().push(key + "/");
          compare(child1, child2);
          stack.get().pop();
        } else {
          Assert.assertFalse(child2.asString(), child2.isDefined());
        }
      }
    } else if (node1.getType() == ModelType.LIST) {
      List<ModelNode> list1 = node1.asList();
      List<ModelNode> list2 = node2.asList();
      Assert.assertEquals(list1 + "\n" + list2, list1.size(), list2.size());

      for (int i = 0; i < list1.size(); i++) {
        stack.get().push(i + "/");
        compare(list1.get(i), list2.get(i));
        stack.get().pop();
      }

    } else if (node1.getType() == ModelType.PROPERTY) {
      Property prop1 = node1.asProperty();
      Property prop2 = node2.asProperty();
      Assert.assertEquals(prop1 + "\n" + prop2, prop1.getName(), prop2.getName());
      stack.get().push(prop1.getName() + "/");
      compare(prop1.getValue(), prop2.getValue());
      stack.get().pop();

    } else {
      try {
        Assert.assertEquals(
            getCompareStackAsString()
                + "\n\""
                + node1.asString()
                + "\"\n\""
                + node2.asString()
                + "\"\n-----",
            node2.asString().trim(),
            node1.asString().trim());
      } catch (AssertionFailedError error) {
        throw error;
      }
    }
  }
  private void addManagementSecurityRealms(List<ModelNode> updates) {
    if (hostModel.get(CORE_SERVICE, MANAGEMENT, SECURITY_REALM).isDefined()) {
      ModelNode securityRealms = hostModel.get(CORE_SERVICE, MANAGEMENT, SECURITY_REALM);
      Set<String> keys = securityRealms.keys();
      for (String current : keys) {
        ModelNode addOp = new ModelNode();
        ModelNode realmAddress = new ModelNode();
        realmAddress.add(CORE_SERVICE, MANAGEMENT).add(SECURITY_REALM, current);
        addOp.get(OP).set(ADD);
        addOp.get(OP_ADDR).set(realmAddress);
        updates.add(addOp);

        ModelNode currentRealm = securityRealms.get(current);
        if (currentRealm.hasDefined(SERVER_IDENTITY)) {
          addManagementComponentComponent(currentRealm, realmAddress, SERVER_IDENTITY, updates);
        }
        if (currentRealm.hasDefined(AUTHENTICATION)) {
          addManagementComponentComponent(currentRealm, realmAddress, AUTHENTICATION, updates);
        }
        if (currentRealm.hasDefined(AUTHORIZATION)) {
          addManagementComponentComponent(currentRealm, realmAddress, AUTHORIZATION, updates);
        }
      }
    }
  }
 protected StringBuilder formatResponse(
     CommandContext ctx, ModelNode opResponse, boolean composite, StringBuilder buf) {
   if (!opResponse.hasDefined(Util.RESULT)) {
     return null;
   }
   final ModelNode result = opResponse.get(Util.RESULT);
   if (composite) {
     final Set<String> keys;
     try {
       keys = result.keys();
     } catch (Exception e) {
       ctx.printLine(
           "Failed to get step results from a composite operation response " + opResponse);
       e.printStackTrace();
       return null;
     }
     for (String key : keys) {
       final ModelNode stepResponse = result.get(key);
       buf =
           formatResponse(
               ctx, stepResponse, false, buf); // TODO nested composite ops aren't expected for now
     }
   } else {
     final ModelNodeFormatter formatter = ModelNodeFormatter.Factory.forType(result.getType());
     if (buf == null) {
       buf = new StringBuilder();
     }
     formatter.format(buf, 0, result);
   }
   return buf;
 }
  /** {@inheritDoc} */
  @Override
  public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context)
      throws XMLStreamException {
    context.startSubsystemElement(Namespace.CURRENT.getUriString(), false);
    final ModelNode model = context.getModelNode();

    writeWorkerThreadPoolIfAttributesSet(writer, model);

    if (model.hasDefined(CONNECTOR)) {
      final ModelNode connector = model.get(CONNECTOR);
      for (String name : connector.keys()) {
        writeConnector(writer, connector.require(name), name);
      }
    }
    if (model.hasDefined(OUTBOUND_CONNECTION)
        || model.hasDefined(REMOTE_OUTBOUND_CONNECTION)
        || model.hasDefined(LOCAL_OUTBOUND_CONNECTION)) {
      // write <outbound-connections> element
      writer.writeStartElement(Element.OUTBOUND_CONNECTIONS.getLocalName());

      if (model.hasDefined(OUTBOUND_CONNECTION)) {
        final List<Property> outboundConnections = model.get(OUTBOUND_CONNECTION).asPropertyList();
        for (Property property : outboundConnections) {
          final String connectionName = property.getName();
          // get the specific outbound-connection
          final ModelNode genericOutboundConnectionModel = property.getValue();
          // process and write outbound connection
          this.writeOutboundConnection(writer, connectionName, genericOutboundConnectionModel);
        }
      }
      if (model.hasDefined(REMOTE_OUTBOUND_CONNECTION)) {
        final List<Property> remoteOutboundConnections =
            model.get(REMOTE_OUTBOUND_CONNECTION).asPropertyList();
        for (Property property : remoteOutboundConnections) {
          final String connectionName = property.getName();
          // get the specific remote outbound connection
          final ModelNode remoteOutboundConnectionModel = property.getValue();
          // process and write remote outbound connection
          this.writeRemoteOutboundConnection(writer, connectionName, remoteOutboundConnectionModel);
        }
      }
      if (model.hasDefined(LOCAL_OUTBOUND_CONNECTION)) {
        final List<Property> localOutboundConnections =
            model.get(LOCAL_OUTBOUND_CONNECTION).asPropertyList();
        for (Property property : localOutboundConnections) {
          final String connectionName = property.getName();
          // get the specific local outbound connection
          final ModelNode localOutboundConnectionModel = property.getValue();
          // process and write local outbound connection
          this.writeLocalOutboundConnection(writer, connectionName, localOutboundConnectionModel);
        }
      }
      // </outbound-connections>
      writer.writeEndElement();
    }

    writer.writeEndElement();
  }
  private void writeBinaryStorage(XMLExtendedStreamWriter writer, ModelNode repository)
      throws XMLStreamException {
    if (has(repository, ModelKeys.CONFIGURATION, ModelKeys.BINARY_STORAGE)) {
      ModelNode configuration = repository.get(ModelKeys.CONFIGURATION);
      ModelNode binaryStorage = configuration.get(ModelKeys.BINARY_STORAGE);

      ModelNode binaryStorageType = binaryStorage.get(ModelKeys.STORAGE_TYPE);
      String storageType =
          binaryStorageType.isDefined() && binaryStorageType.keys().size() == 1
              ? (String) binaryStorageType.keys().toArray()[0]
              : null;
      ModelNode storage =
          storageType != null
              ? binaryStorageType.get((String) binaryStorageType.keys().toArray()[0])
              : new ModelNode();
      writeBinaryStorageModel(writer, storageType, storage);
    }
  }
 private void extractEnterpriseArchiveContexts(HTTPContext context, ModelNode deploymentNode) {
   if (deploymentNode.hasDefined(SUBDEPLOYMENT)) {
     for (ModelNode subdeployment : deploymentNode.get(SUBDEPLOYMENT).asList()) {
       String deploymentName = subdeployment.keys().iterator().next();
       if (isWebArchive(deploymentName)) {
         extractWebArchiveContexts(context, deploymentName, subdeployment.get(deploymentName));
       }
     }
   }
 }
Example #9
0
 /**
  * @deprecated Horrible idea, as it promotes copying random stuff from an operation into the
  *     model.
  */
 @Deprecated
 public static void copyParamsToModel(final ModelNode operation, final ModelNode model) {
   Set<String> keys = new HashSet<String>(operation.keys());
   // Remove general operation params
   keys.remove(OP);
   keys.remove(OP_ADDR);
   keys.remove(OPERATION_HEADERS);
   for (String key : keys) {
     model.get(key).set(operation.get(key));
   }
 }
Example #10
0
 public static ModelNode getOperation(
     final String operationName, final PathAddress address, final ModelNode params) {
   ModelNode op = createEmptyOperation(operationName, address);
   Set<String> keys = params.keys();
   keys.remove(OP);
   keys.remove(OP_ADDR);
   for (String key : keys) {
     op.get(key).set(params.get(key));
   }
   return op;
 }
 private String findAttributeName(ModelNode attributes, String attributeName)
     throws AttributeNotFoundException {
   if (attributes.hasDefined(attributeName)) {
     return attributeName;
   }
   for (String key : attributes.keys()) {
     if (NameConverter.convertToCamelCase(key).equals(attributeName)) {
       return key;
     }
   }
   throw MESSAGES.attributeNotFound(attributeName);
 }
  private void writeNestedStoresOfType(
      ModelNode storage, String nestedStorageType, String storeType, XMLExtendedStreamWriter writer)
      throws XMLStreamException {
    if (has(storage, nestedStorageType)) {
      List<ModelNode> nestedCacheStores = storage.get(nestedStorageType).asList();

      for (ModelNode nestedStore : nestedCacheStores) {
        String storeName = (String) nestedStore.keys().toArray()[0];
        writeBinaryStorageModel(writer, storeType, nestedStore.get(storeName));
      }
    }
  }
 protected void displayResponseHeaders(CommandContext ctx, ModelNode response) {
   if (response.has(Util.RESPONSE_HEADERS)) {
     final ModelNode headers = response.get(Util.RESPONSE_HEADERS);
     final Set<String> keys = headers.keys();
     final SimpleTable table = new SimpleTable(2);
     for (String key : keys) {
       table.addLine(new String[] {key + ':', headers.get(key).asString()});
     }
     final StringBuilder buf = new StringBuilder();
     table.append(buf, true);
     ctx.printLine(buf.toString());
   }
 }
Example #14
0
 public static void validateInSeriesServerGroup(ModelNode serverGroup)
     throws OperationFailedException {
   if (serverGroup.isDefined()) {
     try {
       final Set<String> specKeys = serverGroup.keys();
       if (!ALLOWED_SERVER_GROUP_CHILDREN.containsAll(specKeys)) {
         throw new OperationFailedException(
             MESSAGES.unrecognizedChildren(
                 SERVER_GROUP, ALLOWED_SERVER_GROUP_CHILDREN.toString(), specKeys.toString()));
       }
     } catch (IllegalArgumentException e) { // ignore?
     }
   }
 }
  public static Map<String, String> readConfiguration(ModelControllerClient client, String pid)
      throws IOException, MgmtOperationException {
    ModelNode op =
        ModelUtil.createOpNode(
            "subsystem=configadmin/configuration=" + pid,
            ModelDescriptionConstants.READ_RESOURCE_OPERATION);
    ModelNode result = executeOperation(client, op, true);
    ModelNode entries = result.get("entries");

    Map<String, String> map = new HashMap<String, String>();
    for (String key : entries.keys()) {
      map.put(key, entries.get(key).asString());
    }
    return map;
  }
    @Override
    protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model)
        throws OperationFailedException {
      ServiceTarget serviceTarget = context.getServiceTarget();
      RuntimeCapability<Void> runtimeCapability =
          REALM_MAPPER_RUNTIME_CAPABILITY.fromBaseCapability(context.getCurrentAddressValue());
      ServiceName realmMapperName = runtimeCapability.getCapabilityServiceName(RealmMapper.class);

      final String pattern = PATTERN.resolveModelAttribute(context, model).asString();

      ModelNode realmMapList = REALM_REALM_MAP.resolveModelAttribute(context, model);
      Set<String> names = realmMapList.keys();
      final Map<String, String> realmRealmMap = new HashMap<String, String>(names.size());
      names.forEach((String s) -> realmRealmMap.put(s, realmMapList.require(s).asString()));

      String delegateRealmMapper = asStringIfDefined(context, DELEGATE_REALM_MAPPER, model);

      final InjectedValue<RealmMapper> delegateRealmMapperInjector =
          new InjectedValue<RealmMapper>();

      TrivialService<RealmMapper> realmMapperService =
          new TrivialService<RealmMapper>(
              () -> {
                RealmMapper delegate = delegateRealmMapperInjector.getOptionalValue();
                Pattern compiledPattern = Pattern.compile(pattern);
                if (delegate == null) {
                  return new MappedRegexRealmMapper(compiledPattern, realmRealmMap);
                } else {
                  return new MappedRegexRealmMapper(compiledPattern, delegate, realmRealmMap);
                }
              });

      ServiceBuilder<RealmMapper> realmMapperBuilder =
          serviceTarget.addService(realmMapperName, realmMapperService);

      if (delegateRealmMapper != null) {
        String delegateCapabilityName =
            RuntimeCapability.buildDynamicCapabilityName(
                REALM_MAPPER_CAPABILITY, delegateRealmMapper);
        ServiceName delegateServiceName =
            context.getCapabilityServiceName(delegateCapabilityName, RealmMapper.class);

        realmMapperBuilder.addDependency(
            delegateServiceName, RealmMapper.class, delegateRealmMapperInjector);
      }

      commonDependencies(realmMapperBuilder).setInitialMode(Mode.LAZY).install();
    }
  private void removeSubsystems(ModelNode description) {
    // TODO should remove all subsystems since they are tested in unit tests
    // but for now leave threads and remoting in since unit tests could not be created
    // for them due to circular maven dependencies

    ModelNode subsystemDescriptions = description.get(CHILDREN, SUBSYSTEM, MODEL_DESCRIPTION);
    Set<String> removes = new HashSet<String>();
    for (String key : subsystemDescriptions.keys()) {
      if (!key.equals(RemotingExtension.SUBSYSTEM_NAME)
          && !key.equals(ThreadsExtension.SUBSYSTEM_NAME)) {
        removes.add(key);
      }
    }

    for (String remove : removes) {
      subsystemDescriptions.remove(remove);
    }
  }
 @Override
 protected void populateModel(final ModelNode operation, final Resource resource)
     throws OperationFailedException {
   if (operation.hasDefined(CommonAttributes.MOD_CLUSTER_CONFIG)) {
     ModelNode configuration;
     if (operation
         .get(CommonAttributes.MOD_CLUSTER_CONFIG)
         .hasDefined(CommonAttributes.CONFIGURATION)) {
       configuration =
           operation.get(CommonAttributes.MOD_CLUSTER_CONFIG).get(CommonAttributes.CONFIGURATION);
     } else {
       configuration = operation.get(CommonAttributes.MOD_CLUSTER_CONFIG);
     }
     resource.registerChild(ModClusterExtension.configurationPath, Resource.Factory.create());
     final Resource conf = resource.getChild(ModClusterExtension.configurationPath);
     final ModelNode confModel = conf.getModel();
     for (final String attribute : configuration.keys()) {
       if (attribute.equals(CommonAttributes.SSL)) {
         conf.registerChild(ModClusterExtension.sslConfigurationPath, Resource.Factory.create());
         final Resource ssl = conf.getChild(ModClusterExtension.sslConfigurationPath);
         ModelNode sslnode;
         if (configuration.get(attribute).hasDefined(CommonAttributes.CONFIGURATION)) {
           sslnode = configuration.get(attribute).get(CommonAttributes.CONFIGURATION);
         } else {
           sslnode = configuration.get(attribute);
         }
         final ModelNode sslModel = ssl.getModel();
         for (AttributeDefinition sslAttr : ModClusterSSLResourceDefinition.ATTRIBUTES) {
           sslAttr.validateAndSet(sslnode, sslModel);
         }
       } else if (attribute.equals(CommonAttributes.DYNAMIC_LOAD_PROVIDER)
           || attribute.equals(CommonAttributes.SIMPLE_LOAD_PROVIDER)) {
         // TODO AS7-4050 properly handle these
         confModel.get(attribute).set(configuration.get(attribute));
       } else {
         AttributeDefinition ad =
             ModClusterConfigResourceDefinition.ATTRIBUTES_BY_NAME.get(attribute);
         if (ad != null) {
           ad.validateAndSet(configuration, confModel);
         } // else ignore unknown params
       }
     }
   }
 }
  private void addManagementConnections(List<ModelNode> updates) {
    if (hostModel.get(CORE_SERVICE, MANAGEMENT, LDAP_CONNECTION).isDefined()) {
      ModelNode baseAddress = new ModelNode();
      baseAddress.add(CORE_SERVICE, MANAGEMENT);

      ModelNode connections = hostModel.get(CORE_SERVICE, MANAGEMENT, LDAP_CONNECTION);
      for (String connectionName : connections.keys()) {
        ModelNode addConnection = new ModelNode();
        // First take the properties to pass over.
        addConnection.set(connections.get(connectionName));

        // Now convert it to an operation by adding a name and address.
        ModelNode identityAddress = baseAddress.clone().add(LDAP_CONNECTION, connectionName);
        addConnection.get(OP).set(ADD);
        addConnection.get(OP_ADDR).set(identityAddress);

        updates.add(addConnection);
      }
    }
  }
Example #20
0
  private void writeDomainDeployments(
      final XMLExtendedStreamWriter writer, final ModelNode modelNode) throws XMLStreamException {

    final Set<String> deploymentNames = modelNode.keys();
    if (deploymentNames.size() > 0) {
      writer.writeStartElement(Element.DEPLOYMENTS.getLocalName());
      for (String uniqueName : deploymentNames) {
        final ModelNode deployment = modelNode.get(uniqueName);
        final String runtimeName = deployment.get(RUNTIME_NAME).asString();
        writer.writeStartElement(Element.DEPLOYMENT.getLocalName());
        writeAttribute(writer, Attribute.NAME, uniqueName);
        writeAttribute(writer, Attribute.RUNTIME_NAME, runtimeName);
        final List<ModelNode> contentItems = deployment.require(CONTENT).asList();
        for (ModelNode contentItem : contentItems) {
          writeContentItem(writer, contentItem);
        }
        writer.writeEndElement();
      }
      writer.writeEndElement();
    }
  }
Example #21
0
  private static void writePooledConnectionFactories(
      final XMLExtendedStreamWriter writer, final ModelNode node) throws XMLStreamException {
    if (!node.isDefined() || node.keys().size() == 0) {
      return;
    }
    List<Property> properties = node.asPropertyList();
    if (!properties.isEmpty()) {
      for (Property prop : properties) {
        final String name = prop.getName();
        final ModelNode factory = prop.getValue();
        if (factory.isDefined()) {
          writer.writeStartElement(Element.POOLED_CONNECTION_FACTORY.getLocalName());

          writer.writeAttribute(Attribute.NAME.getLocalName(), name);

          // write inbound config attributes first...
          if (hasDefinedInboundConfigAttributes(factory)) {
            writer.writeStartElement(Element.INBOUND_CONFIG.getLocalName());
            for (ConnectionFactoryAttribute attribute :
                PooledConnectionFactoryDefinition.ATTRIBUTES) {
              if (attribute.isInboundConfig()) {
                attribute.getDefinition().marshallAsElement(factory, writer);
              }
            }
            writer.writeEndElement();
          }

          // ... then the attributes that are not part of the inbound config
          for (ConnectionFactoryAttribute attribute :
              PooledConnectionFactoryDefinition.ATTRIBUTES) {
            if (!attribute.isInboundConfig()) {
              attribute.getDefinition().marshallAsElement(factory, writer);
            }
          }

          writer.writeEndElement();
        }
      }
    }
  }
Example #22
0
  private void writeServerGroupDeployments(
      final XMLExtendedStreamWriter writer, final ModelNode modelNode) throws XMLStreamException {

    final Set<String> deploymentNames = modelNode.keys();
    if (deploymentNames.size() > 0) {
      writer.writeStartElement(Element.DEPLOYMENTS.getLocalName());
      for (String uniqueName : deploymentNames) {
        final ModelNode deployment = modelNode.get(uniqueName);
        final String runtimeName = deployment.get(RUNTIME_NAME).asString();
        final boolean enabled =
            !deployment.hasDefined(ENABLED) || deployment.get(ENABLED).asBoolean();
        writer.writeStartElement(Element.DEPLOYMENT.getLocalName());
        writeAttribute(writer, Attribute.NAME, uniqueName);
        writeAttribute(writer, Attribute.RUNTIME_NAME, runtimeName);
        if (!enabled) {
          writeAttribute(writer, Attribute.ENABLED, Boolean.FALSE.toString());
        }
        writer.writeEndElement();
      }
      writer.writeEndElement();
    }
  }
Example #23
0
  private static void writeConnectionFactories(
      final XMLExtendedStreamWriter writer, final ModelNode node) throws XMLStreamException {
    if (!node.isDefined() || node.keys().size() == 0) {
      return;
    }
    List<Property> properties = node.asPropertyList();
    if (!properties.isEmpty()) {
      for (Property prop : properties) {
        final String name = prop.getName();
        final ModelNode factory = prop.getValue();
        if (factory.isDefined()) {
          writer.writeStartElement(Element.CONNECTION_FACTORY.getLocalName());
          writer.writeAttribute(Attribute.NAME.getLocalName(), name);

          for (AttributeDefinition attribute : ConnectionFactoryDefinition.ATTRIBUTES) {
            attribute.marshallAsElement(factory, writer);
          }

          writer.writeEndElement();
        }
      }
    }
  }
Example #24
0
  private static void writeTopics(final XMLExtendedStreamWriter writer, final ModelNode node)
      throws XMLStreamException {
    if (!node.isDefined() || node.keys().size() == 0) {
      return;
    }
    List<Property> properties = node.asPropertyList();
    if (!properties.isEmpty()) {
      for (Property prop : properties) {
        final String name = prop.getName();
        final ModelNode topic = prop.getValue();
        if (topic.isDefined()) {
          writer.writeStartElement(Element.JMS_TOPIC.getLocalName());
          writer.writeAttribute(Attribute.NAME.getLocalName(), name);

          for (AttributeDefinition attribute : JMSTopicDefinition.ATTRIBUTES) {
            attribute.marshallAsElement(topic, writer);
          }

          writer.writeEndElement();
        }
      }
    }
  }
 private void extractWebArchiveContexts(
     HTTPContext context, String deploymentName, ModelNode deploymentNode) {
   if (deploymentNode.hasDefined(SUBSYSTEM)) {
     ModelNode subsystem = deploymentNode.get(SUBSYSTEM);
     if (subsystem.hasDefined(UNDERTOW)) {
       ModelNode webSubSystem = subsystem.get(UNDERTOW);
       if (webSubSystem.isDefined() && webSubSystem.hasDefined("context-root")) {
         final String contextName = webSubSystem.get("context-root").asString();
         if (webSubSystem.hasDefined(SERVLET)) {
           for (final ModelNode servletNode : webSubSystem.get(SERVLET).asList()) {
             for (final String servletName : servletNode.keys()) {
               context.add(new Servlet(servletName, toContextName(contextName)));
             }
           }
         }
         /*
          * This is a WebApp, it has some form of webcontext whether it has a
          * Servlet or not. AS7 does not expose jsp / default servlet in mgm api
          */
         context.add(new Servlet("default", toContextName(contextName)));
       }
     }
   }
 }
Example #26
0
 private String getAddedRule(ModelNode rewritenode) {
   for (final String attribute : rewritenode.keys()) {
     if (attribute.startsWith("rule-")) return attribute;
   }
   return "rule-0";
 }
Example #27
0
 private String getAddedConditionName(ModelNode conditionnode) {
   for (final String attribute : conditionnode.keys()) {
     if (attribute.startsWith("condition-")) return attribute;
   }
   return "condition-0";
 }
  private Object invoke(
      final OperationEntry entry, final String operationName, PathAddress address, Object[] params)
      throws InstanceNotFoundException, MBeanException, ReflectionException {
    if (!standalone && !entry.getFlags().contains(OperationEntry.Flag.READ_ONLY)) {
      throw MESSAGES.noOperationCalled(operationName);
    }

    ResourceAccessControl accessControl;
    if (operationName.equals("add")) {
      accessControl = accessControlUtil.getResourceAccess(address, true);
    } else {
      ObjectName objectName = ObjectNameAddressUtil.createObjectName(operationName, address);
      accessControl =
          accessControlUtil.getResourceAccessWithInstanceNotFoundExceptionIfNotAccessible(
              objectName, address, true);
    }

    if (!accessControl.isExecutableOperation(operationName)) {
      throw MESSAGES.notAuthorizedToExecuteOperation(operationName);
    }

    final ModelNode description = entry.getDescriptionProvider().getModelDescription(null);
    ModelNode op = new ModelNode();
    op.get(OP).set(operationName);
    op.get(OP_ADDR).set(address.toModelNode());
    if (params.length > 0) {
      ModelNode requestProperties = description.require(REQUEST_PROPERTIES);
      Set<String> keys = requestProperties.keys();
      if (keys.size() != params.length) {
        throw MESSAGES.differentLengths("params", "description");
      }
      Iterator<String> it = requestProperties.keys().iterator();
      for (int i = 0; i < params.length; i++) {
        String attributeName = it.next();
        ModelNode paramDescription = requestProperties.get(attributeName);
        op.get(attributeName).set(converters.toModelNode(paramDescription, params[i]));
      }
    }

    ModelNode result = execute(op);
    String error = getFailureDescription(result);
    if (error != null) {
      if (error.contains(AUTHORIZED_ERROR)) {
        for (Object param : params) {
          // Since read-resource-description does not know the parameters of the operation, i.e. if
          // a vault expression is used or not,
          // check the error code
          // TODO add a separate authorize step where we check ourselves that the operation will
          // pass authorization?
          if (isVaultExpression(param)) {
            throw MESSAGES.notAuthorizedToExecuteOperation(operationName);
          }
        }
      }
      throw new ReflectionException(null, error);
    }

    if (!description.hasDefined(REPLY_PROPERTIES)) {
      return null;
    }
    // TODO we could have more than one reply property
    return converters.fromModelNode(description.get(REPLY_PROPERTIES), result.get(RESULT));
  }
Example #29
0
    @Override
    public void validateParameter(String parameterName, ModelNode plan)
        throws OperationFailedException {
      if (plan == null) {
        throw new OperationFailedException(MESSAGES.nullVar("plan").getLocalizedMessage());
      }
      if (!plan.hasDefined(ROLLOUT_PLAN)) {
        throw new OperationFailedException(
            MESSAGES.requiredChildIsMissing(ROLLOUT_PLAN, ROLLOUT_PLAN, plan.toString()));
      }
      ModelNode rolloutPlan1 = plan.get(ROLLOUT_PLAN);

      final Set<String> keys;
      try {
        keys = rolloutPlan1.keys();
      } catch (IllegalArgumentException e) {
        throw new OperationFailedException(
            MESSAGES.requiredChildIsMissing(ROLLOUT_PLAN, IN_SERIES, plan.toString()));
      }
      if (!keys.contains(IN_SERIES)) {
        throw new OperationFailedException(
            MESSAGES.requiredChildIsMissing(ROLLOUT_PLAN, IN_SERIES, plan.toString()));
      }
      if (keys.size() > 2 || keys.size() == 2 && !keys.contains(ROLLBACK_ACROSS_GROUPS)) {
        throw new OperationFailedException(
            MESSAGES.unrecognizedChildren(
                ROLLOUT_PLAN, IN_SERIES + ", " + ROLLBACK_ACROSS_GROUPS, plan.toString()));
      }

      final ModelNode inSeries = rolloutPlan1.get(IN_SERIES);
      if (!inSeries.isDefined()) {
        throw new OperationFailedException(
            MESSAGES.requiredChildIsMissing(ROLLOUT_PLAN, IN_SERIES, plan.toString()));
      }

      final List<ModelNode> groups = inSeries.asList();
      if (groups.isEmpty()) {
        throw new OperationFailedException(MESSAGES.inSeriesIsMissingGroups(plan.toString()));
      }

      for (ModelNode group : groups) {
        if (group.hasDefined(SERVER_GROUP)) {
          final ModelNode serverGroup = group.get(SERVER_GROUP);
          final Set<String> groupKeys;
          try {
            groupKeys = serverGroup.keys();
          } catch (IllegalArgumentException e) {
            throw new OperationFailedException(
                MESSAGES.serverGroupExpectsSingleChild(plan.toString()));
          }
          if (groupKeys.size() != 1) {
            throw new OperationFailedException(
                MESSAGES.serverGroupExpectsSingleChild(plan.toString()));
          }
          validateInSeriesServerGroup(serverGroup.asProperty().getValue());
        } else if (group.hasDefined(CONCURRENT_GROUPS)) {
          final ModelNode concurrent = group.get(CONCURRENT_GROUPS);
          for (ModelNode child : concurrent.asList()) {
            validateInSeriesServerGroup(child.asProperty().getValue());
          }
        } else {
          throw new OperationFailedException(MESSAGES.unexpectedInSeriesGroup(plan.toString()));
        }
      }
    }
 private void addExtensions(Set<String> extensionNames, ModelNode extensions) {
   if (extensions.isDefined()) {
     extensionNames.addAll(extensions.keys());
   }
 }