@Test
  public void testOneOffAndCP() throws Exception {
    Module module =
        new Module.Builder("module-test")
            .miscFile(
                new ResourceItem(
                    "resource-test", ("module resource").getBytes(StandardCharsets.UTF_8)))
            .build();
    File moduleDir = module.writeToDisk(new File(MODULES_PATH));

    byte[] targetHash = HashUtils.hashFile(moduleDir);
    targetHash = applyOneOff("oneoff1", targetHash);
    targetHash = applyCP("cp1", targetHash);

    final ModelNode response = showHistory();

    assertTrue(response.has("outcome"));
    assertEquals("success", response.get("outcome").asString());
    assertTrue(response.has("result"));
    final List<ModelNode> list = response.get("result").asList();
    assertEquals(2, list.size());
    ModelNode entry = list.get(0);
    assertEquals("cp1", entry.get("patch-id").asString());
    assertEquals("cumulative", entry.get("type").asString());
    entry = list.get(1);
    assertEquals("oneoff1", entry.get("patch-id").asString());
    assertEquals("one-off", entry.get("type").asString());
  }
Example #2
0
    @Override
    public OperationResult execute(
        OperationContext context, ModelNode operation, ResultHandler resultHandler) {
      final ModelNode model = context.getSubModel();

      PathAddress rootAddress =
          PathAddress.pathAddress(
              PathAddress.pathAddress(operation.require(OP_ADDR)).getLastElement());
      final ModelNode result = new ModelNode();

      final ModelNode subsystem = new ModelNode();
      subsystem.get(OP).set(ADD);
      subsystem.get(OP_ADDR).set(rootAddress.toModelNode());
      if (model.has(ACTIVATION)) {
        subsystem.get(ACTIVATION).set(model.get(ACTIVATION));
      }
      if (model.has(CONFIGURATION)) {
        subsystem.get(CONFIGURATION).set(model.get(CONFIGURATION));
      }
      if (model.has(PROPERTIES)) {
        subsystem.get(PROPERTIES).set(model.get(PROPERTIES));
      }
      if (model.has(MODULES)) {
        subsystem.get(MODULES).set(model.get(MODULES));
      }
      result.add(subsystem);

      resultHandler.handleResultFragment(Util.NO_LOCATION, result);
      resultHandler.handleResultComplete();
      return new BasicOperationResult();
    }
 private void parseAuthenticator(final XMLExtendedStreamReader reader, final ModelNode repository)
     throws XMLStreamException {
   if (reader.getAttributeCount() > 0) {
     ModelNode authenticator = new ModelNode();
     for (int i = 0; i < reader.getAttributeCount(); i++) {
       String attrName = reader.getAttributeLocalName(i);
       String attrValue = reader.getAttributeValue(i);
       Attribute attribute = Attribute.forName(attrName);
       switch (attribute) {
           // Set these as properties on the repository ModelNode ...
         case NAME:
           ModelAttributes.NAME.parseAndSetParameter(attrValue, authenticator, reader);
           break;
         case CLASSNAME:
           ModelAttributes.CLASSNAME.parseAndSetParameter(attrValue, authenticator, reader);
           if (!authenticator.has(ModelKeys.NAME)) {
             ModelAttributes.NAME.parseAndSetParameter(attrValue, authenticator, reader);
           }
           break;
         case MODULE:
           ModelAttributes.MODULE.parseAndSetParameter(attrValue, authenticator, reader);
           break;
         default:
           authenticator.get(attrName).set(attrValue);
           break;
       }
     }
     if (authenticator.has(ModelKeys.NAME))
       repository.get(ModelKeys.AUTHENTICATORS).add(authenticator);
   }
   requireNoElements(reader);
 }
  public void addDeploymentOverlays(final List<ModelNode> updates) {
    if (domainModel.hasDefined(DEPLOYMENT_OVERLAY)) {

      HostFileRepository remoteRepository = null;
      if (!domainController.getLocalHostInfo().isMasterDomainController()) {
        remoteRepository = domainController.getRemoteFileRepository();
      }

      for (Property deploymentOverlay : domainModel.get(DEPLOYMENT_OVERLAY).asPropertyList()) {
        String name = deploymentOverlay.getName();
        ModelNode details = deploymentOverlay.getValue();

        PathAddress addr =
            PathAddress.pathAddress(PathElement.pathElement(DEPLOYMENT_OVERLAY, name));
        ModelNode addOp = Util.getEmptyOperation(ADD, addr.toModelNode());
        updates.add(addOp);

        if (details.hasDefined(CONTENT)) {

          for (Property content : details.get(CONTENT).asPropertyList()) {
            final String contentName = content.getName();
            final ModelNode contentDetails = content.getValue();
            byte[] hash = contentDetails.require(CONTENT).asBytes();
            File[] files = domainController.getLocalFileRepository().getDeploymentFiles(hash);
            if (files == null || files.length == 0) {
              if (remoteRepository != null) {
                remoteRepository.getDeploymentFiles(hash);
              }
            }
            addr =
                PathAddress.pathAddress(
                    PathElement.pathElement(DEPLOYMENT_OVERLAY, name),
                    PathElement.pathElement(CONTENT, contentName));
            addOp = Util.getEmptyOperation(ADD, addr.toModelNode());
            addOp.get(CONTENT).get(HASH).set(contentDetails.get(CONTENT));
            updates.add(addOp);
          }
        }
        if (serverGroup.hasDefined(DEPLOYMENT_OVERLAY)) {
          final ModelNode groupOverlay = serverGroup.get(DEPLOYMENT_OVERLAY).asObject();
          if (groupOverlay.has(name)) {
            ModelNode deploymentsNode = groupOverlay.get(name);
            if (deploymentsNode.has(DEPLOYMENT)) {
              for (Property content : deploymentsNode.get(DEPLOYMENT).asPropertyList()) {
                final String deploymentName = content.getName();
                final ModelNode deploymentDetails = content.getValue();
                addr =
                    PathAddress.pathAddress(
                        PathElement.pathElement(DEPLOYMENT_OVERLAY, name),
                        PathElement.pathElement(DEPLOYMENT, deploymentName));
                addOp = Util.getEmptyOperation(ADD, addr.toModelNode());
                updates.add(addOp);
              }
            }
          }
        }
      }
    }
  }
  @Test
  public void testUnpatched() throws Exception {
    final ModelNode response = showHistory();

    assertTrue(response.has("outcome"));
    assertEquals("success", response.get("outcome").asString());
    assertTrue(response.has("result"));
    final List<ModelNode> list = response.get("result").asList();
    assertTrue(list.isEmpty());
  }
 private boolean has(ModelNode node, String... names) {
   for (String name : names) {
     if (!node.isDefined() || !node.has(name)) return false;
     node = node.get(name);
   }
   return true;
 }
  @Override
  AttributeAccess getAttributeAccess(
      final ListIterator<PathElement> iterator, final String attributeName) {

    if (iterator.hasNext()) {
      final PathElement next = iterator.next();
      final NodeSubregistry subregistry = children.get(next.getKey());
      if (subregistry == null) {
        return null;
      }
      return subregistry.getAttributeAccess(iterator, next.getValue(), attributeName);
    } else {
      final Map<String, AttributeAccess> snapshot = attributesUpdater.get(this);
      AttributeAccess access = snapshot.get(attributeName);
      if (access == null) {
        // If there is metadata for an attribute but no AttributeAccess, assume RO. Can't
        // be writable without a registered handler. This opens the possibility that out-of-date
        // metadata
        // for attribute "foo" can lead to a read of non-existent-in-model "foo" with
        // an unexpected undefined value returned. But it removes the possibility of a
        // dev forgetting to call registry.registerReadOnlyAttribute("foo", null) resulting
        // in the valid attribute "foo" not being readable
        final ModelNode desc = descriptionProvider.getModelDescription(null);
        if (desc.has(ATTRIBUTES) && desc.get(ATTRIBUTES).keys().contains(attributeName)) {
          access =
              new AttributeAccess(AccessType.READ_ONLY, Storage.CONFIGURATION, null, null, null);
        }
      }
      return access;
    }
  }
Example #8
0
    ModelNode parseModulesElement(XMLExtendedStreamReader reader) throws XMLStreamException {

      // Handle attributes
      requireNoAttributes(reader);

      ModelNode modules = new ModelNode();

      // Handle elements
      while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
        switch (Namespace.forUri(reader.getNamespaceURI())) {
          case OSGI_1_0:
            {
              final Element element = Element.forName(reader.getLocalName());
              if (element == Element.MODULE) {
                String identifier = null;
                String start = null;
                final int count = reader.getAttributeCount();
                for (int i = 0; i < count; i++) {
                  requireNoNamespaceAttribute(reader, i);
                  final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
                  switch (attribute) {
                    case IDENTIFIER:
                      {
                        identifier = reader.getAttributeValue(i);
                        break;
                      }
                    case START:
                      {
                        start = reader.getAttributeValue(i);
                        break;
                      }
                    default:
                      throw unexpectedAttribute(reader, i);
                  }
                }
                if (identifier == null)
                  throw missingRequired(reader, Collections.singleton(Attribute.IDENTIFIER));
                if (modules.has(identifier))
                  throw new XMLStreamException(
                      element.getLocalName() + " already declared", reader.getLocation());

                ModelNode module = new ModelNode();
                if (start != null) {
                  module.get(START).set(start);
                }
                modules.get(identifier).set(module);

                requireNoContent(reader);
              } else {
                throw unexpectedElement(reader);
              }
              break;
            }
          default:
            throw unexpectedElement(reader);
        }
      }

      return modules;
    }
  // TODO move this kind of logic into AttributeDefinition itself
  private static ModelNode validateResolvedModel(
      final AttributeDefinition definition,
      final OperationContext context,
      final ModelNode subModel)
      throws OperationFailedException {
    final String attributeName = definition.getName();
    final boolean has = subModel.has(attributeName);
    if (!has && definition.isRequired(subModel)) {
      throw ServerMessages.MESSAGES.attributeIsRequired(attributeName);
    }
    ModelNode result;
    if (has) {
      if (!definition.isAllowed(subModel)) {
        if (subModel.hasDefined(attributeName)) {
          throw ServerMessages.MESSAGES.attributeNotAllowedWhenAlternativeIsPresent(
              attributeName, Arrays.asList(definition.getAlternatives()));
        } else {
          // create the undefined node
          result = new ModelNode();
        }
      } else {
        result = definition.resolveModelAttribute(context, subModel);
      }
    } else {
      // create the undefined node
      result = new ModelNode();
    }

    return result;
  }
 protected static void executeWithFailure(ModelControllerClient client, ModelNode operation)
     throws IOException {
   ModelNode result = client.execute(operation);
   assertEquals(result.toJSONString(true), FAILED, result.get(OUTCOME).asString());
   assertTrue(
       result.toJSONString(true),
       result.get(FAILURE_DESCRIPTION).asString().contains("WFLYMSGAMQ0066"));
   assertFalse(result.has(RESULT));
 }
Example #11
0
    ModelNode parsePropertiesElement(XMLExtendedStreamReader reader) throws XMLStreamException {

      // Handle attributes
      requireNoAttributes(reader);

      ModelNode properties = new ModelNode();

      // Handle elements
      while (reader.hasNext() && reader.nextTag() != END_ELEMENT) {
        switch (Namespace.forUri(reader.getNamespaceURI())) {
          case OSGI_1_0:
            {
              final Element element = Element.forName(reader.getLocalName());
              if (element == Element.PROPERTY) {
                // Handle attributes
                String name = null;
                String value = null;
                int count = reader.getAttributeCount();
                for (int i = 0; i < count; i++) {
                  requireNoNamespaceAttribute(reader, i);
                  final String attrValue = reader.getAttributeValue(i);
                  final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i));
                  switch (attribute) {
                    case NAME:
                      {
                        name = attrValue;
                        if (properties.has(name)) {
                          throw new XMLStreamException(
                              "Property " + name + " already exists", reader.getLocation());
                        }
                        break;
                      }
                    default:
                      throw unexpectedAttribute(reader, i);
                  }
                }
                if (name == null) {
                  throw missingRequired(reader, Collections.singleton(Attribute.NAME));
                }
                value = reader.getElementText().trim();
                if (value == null || value.length() == 0) {
                  throw new XMLStreamException(
                      "Value for property " + name + " is null", reader.getLocation());
                }
                properties.get(name).set(value);
                break;
              } else {
                throw unexpectedElement(reader);
              }
            }
          default:
            throw unexpectedElement(reader);
        }
      }

      return properties;
    }
Example #12
0
 private Activation getActivationMode(ModelNode operation) {
   Activation activation = SubsystemState.DEFAULT_ACTIVATION;
   if (operation.has(ModelConstants.ACTIVATION)) {
     activation =
         Activation.valueOf(
             operation.get(ModelConstants.ACTIVATION).asString().toUpperCase(Locale.ENGLISH));
   }
   return activation;
 }
Example #13
0
 public boolean hasAlternative(final ModelNode operationObject) {
   if (alternatives != null) {
     for (final String alternative : alternatives) {
       if (operationObject.has(alternative)) {
         return true;
       }
     }
   }
   return false;
 }
  /**
   * 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;
      }
    }
  }
 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 #16
0
  /**
   * Finds a value in the given {@code operationObject} whose key matches this attribute's {@link
   * #getName() name}, resolves it and validates it using this attribute's {@link #getValidator()
   * validator}. If the value is undefined and a {@link #getDefaultValue() default value} is
   * available, the default value is used.
   *
   * @param operationObject model node of type {@link ModelType#OBJECT}, typically representing an
   *     operation request
   * @return the resolved value, possibly the default value if the operation does not have a defined
   *     value matching this attribute's name
   * @throws OperationFailedException if the value is not valid
   */
  public ModelNode validateResolvedOperation(final ModelNode operationObject)
      throws OperationFailedException {
    final ModelNode node = new ModelNode();
    if (operationObject.has(name)) {
      node.set(operationObject.get(name));
    }
    if (!node.isDefined() && defaultValue.isDefined()) {
      node.set(defaultValue);
    }
    final ModelNode resolved = node.resolve();
    validator.validateParameter(name, resolved);

    return resolved;
  }
  @Test
  public void testMain() throws Exception {

    // create a module
    Module module =
        new Module.Builder("module-test")
            .miscFile(
                new ResourceItem(
                    "resource-test", ("module resource").getBytes(StandardCharsets.UTF_8)))
            .build();
    File moduleDir = module.writeToDisk(new File(MODULES_PATH));

    byte[] targetHash = HashUtils.hashFile(moduleDir);
    for (int i = 0; i < patchIds.length; ++i) {
      if (patchTypes[i]) {
        targetHash = applyCP(patchIds[i], targetHash);
      } else {
        targetHash = applyOneOff(patchIds[i], targetHash);
      }
    }

    final ModelNode response = showHistory();

    assertTrue(response.has("outcome"));
    assertEquals("success", response.get("outcome").asString());
    assertTrue(response.has("result"));
    final List<ModelNode> list = response.get("result").asList();
    assertEquals(patchIds.length, list.size());
    for (int i = 0; i < patchIds.length; ++i) {
      final ModelNode info = list.get(i);
      assertEquals(patchIds[patchIds.length - 1 - i], info.get("patch-id").asString());
      assertTrue(info.has("type"));
      final String type = patchTypes[patchTypes.length - 1 - i] ? "cumulative" : "one-off";
      assertEquals(type, info.get("type").asString());
      assertTrue(info.has("applied-at"));
    }
  }
 @Override
 protected void writeBinaryStorageConfiguration(
     String repositoryName, OperationContext context, ModelNode model, EditableDocument binaries)
     throws OperationFailedException {
   super.writeCommonBinaryStorageConfiguration(repositoryName, context, model, binaries);
   binaries.set(FieldName.TYPE, FieldValue.BINARY_STORAGE_TYPE_FILE);
   String defaultPath = "modeshape/" + repositoryName + "/binaries";
   ModelNode pathNode = ModelAttributes.PATH.resolveModelAttribute(context, model);
   String path = pathNode.isDefined() ? pathNode.asString() : defaultPath;
   String relativeTo =
       ModelAttributes.RELATIVE_TO.resolveModelAttribute(context, model).asString();
   if (model.has(ModelKeys.RELATIVE_TO)
       && model.get(ModelKeys.RELATIVE_TO).asString().contains(DATA_DIR_VARIABLE)) {
     binaryStoragePathInDataDirectory = path;
   }
   path = relativeTo + path;
   binaries.set(FieldName.DIRECTORY, path);
 }
 // TODO move this kind of logic into AttributeDefinition itself
 private static void validateAndSet(
     final AttributeDefinition definition, final ModelNode operation, final ModelNode subModel)
     throws OperationFailedException {
   final String attributeName = definition.getName();
   final boolean has = operation.has(attributeName);
   if (!has && definition.isRequired(operation)) {
     throw ServerMessages.MESSAGES.attributeIsRequired(attributeName);
   }
   if (has) {
     if (!definition.isAllowed(operation)) {
       throw ServerMessages.MESSAGES.attributeIsInvalid(attributeName);
     }
     definition.validateAndSet(operation, subModel);
   } else {
     // create the undefined node
     subModel.get(definition.getName());
   }
 }
Example #20
0
  /**
   * Finds a value in the given {@code operationObject} whose key matches this attribute's {@link
   * #getName() name} and validates it using this attribute's {@link #getValidator() validator}.
   *
   * @param operationObject model node of type {@link ModelType#OBJECT}, typically representing an
   *     operation request
   * @return the value
   * @throws OperationFailedException if the value is not valid
   */
  public ModelNode validateOperation(final ModelNode operationObject)
      throws OperationFailedException {

    ModelNode node = new ModelNode();
    if (operationObject.has(name)) {
      node.set(operationObject.get(name));
    }
    if (isAllowExpression() && node.getType() == ModelType.STRING) {
      node = ParseUtils.parsePossibleExpression(node.asString());
    }
    if (!node.isDefined() && defaultValue.isDefined()) {
      validator.validateParameter(name, defaultValue);
    } else {
      validator.validateParameter(name, node);
    }

    return node;
  }
  private static void validateLegacyFilter(
      final KernelServices kernelServices,
      final ModelVersion modelVersion,
      final ModelNode address,
      final String filterExpression)
      throws OperationFailedException {
    ModelNode op = Operations.createReadResourceOperation(address);
    ModelNode result = executeTransformOperation(kernelServices, modelVersion, op);
    // No filter-spec should be there
    Assert.assertFalse(
        "filter-spec found at: " + address.asString(),
        result.has(CommonAttributes.FILTER_SPEC.getName()));

    op = Operations.createReadAttributeOperation(address, CommonAttributes.FILTER);
    result = executeTransformOperation(kernelServices, modelVersion, op);
    Assert.assertEquals(
        "Transformed spec does not match filter expression.",
        Filters.filterToFilterSpec(Operations.readResult(result)),
        filterExpression);
  }
 private void mergeBindingGroups(
     List<ModelNode> updates,
     Map<String, ModelNode> groups,
     final String groupName,
     ModelNode group,
     Set<String> processed) {
   addSocketBindings(updates, group, groupName, group.get(DEFAULT_INTERFACE));
   if (group.has(INCLUDES) && group.get(INCLUDES).isDefined()) {
     for (final ModelNode include : group.get(INCLUDES).asList()) {
       final String ref = include.asString();
       if (processed.add(ref)) {
         final ModelNode includedGroup = groups.get(ref);
         if (includedGroup == null) {
           throw MESSAGES.undefinedSocketBindingGroup(ref);
         }
         mergeBindingGroups(updates, groups, groupName, includedGroup, processed);
       }
     }
   }
 }
  @Override
  AttributeAccess getAttributeAccess(
      final ListIterator<PathElement> iterator, final String attributeName) {

    if (iterator.hasNext()) {
      final PathElement next = iterator.next();
      final NodeSubregistry subregistry = children.get(next.getKey());
      if (subregistry == null) {
        return null;
      }
      return subregistry.getAttributeAccess(iterator, next.getValue(), attributeName);
    } else {
      checkPermission();
      final Map<String, AttributeAccess> snapshot = attributesUpdater.get(this);
      AttributeAccess access = snapshot.get(attributeName);
      if (access == null && hasNoAlternativeWildcardRegistration()) {
        // If there is metadata for an attribute but no AttributeAccess, assume RO. Can't
        // be writable without a registered handler. This opens the possibility that out-of-date
        // metadata
        // for attribute "foo" can lead to a read of non-existent-in-model "foo" with
        // an unexpected undefined value returned. But it removes the possibility of a
        // dev forgetting to call registry.registerReadOnlyAttribute("foo", null) resulting
        // in the valid attribute "foo" not being readable
        DescriptionProvider provider = resourceDefinition.getDescriptionProvider(this);
        if (provider instanceof DefaultResourceDescriptionProvider) {
          return null; // attribute was not registered so it does not exist. no need to read
                       // resource description as we wont find anything and cause SO
        }
        // todo get rid of this fallback loop as with code cleanup we wont need it anymore.
        final ModelNode desc =
            resourceDefinition.getDescriptionProvider(this).getModelDescription(null);
        if (desc.has(ATTRIBUTES) && desc.get(ATTRIBUTES).keys().contains(attributeName)) {
          access =
              new AttributeAccess(
                  AccessType.READ_ONLY, Storage.CONFIGURATION, null, null, null, null);
        }
      }
      return access;
    }
  }
Example #24
0
    /** {@inheritDoc} */
    @Override
    public void writeContent(
        final XMLExtendedStreamWriter writer, final SubsystemMarshallingContext context)
        throws XMLStreamException {

      ModelNode node = context.getModelNode();
      if (node.has(CommonAttributes.DEFAULT_DATASOURCE)) {
        context.startSubsystemElement(Namespace.CURRENT.getUriString(), false);
        writer.writeStartElement(Element.JPA.getLocalName());
        writer.writeAttribute(
            Attribute.DEFAULT_DATASOURCE_NAME.getLocalName(),
            node.get(CommonAttributes.DEFAULT_DATASOURCE).asString());
        writer.writeEndElement();
        writer.writeEndElement();
      } else {
        // TODO seems to be a problem with empty elements cleaning up the queue in
        // FormattingXMLStreamWriter.runAttrQueue
        // context.startSubsystemElement(NewNamingExtension.NAMESPACE, true);
        context.startSubsystemElement(Namespace.CURRENT.getUriString(), false);
        writer.writeEndElement();
      }
    }
  private ModelNode convertGetRequest(URI request) {
    ArrayList<String> pathSegments = decodePath(request.getRawPath());
    Map<String, String> queryParameters = decodeQuery(request.getRawQuery());

    GetOperation operation = null;
    ModelNode dmr = new ModelNode();
    for (Entry<String, String> entry : queryParameters.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();
      if ("operation".equals(key)) {
        try {
          operation = GetOperation.valueOf(value.toUpperCase().replace('-', '_'));
          value = operation.realOperation();
        } catch (Exception e) {
          throw MESSAGES.invalidOperation(e, value);
        }
      }

      dmr.get(entry.getKey()).set(value);
    }

    // This will now only occur if no operation at all was specified on the incoming request.
    if (operation == null) {
      operation = GetOperation.RESOURCE;
      dmr.get("operation").set(operation.realOperation);
    }

    if (operation == GetOperation.RESOURCE && !dmr.has("recursive"))
      dmr.get("recursive").set(false);

    ModelNode list = dmr.get("address").setEmptyList();
    for (int i = 1; i < pathSegments.size() - 1; i += 2) {
      list.add(pathSegments.get(i), pathSegments.get(i + 1));
    }
    return dmr;
  }
Example #26
0
  /** {@inheritDoc} */
  @Override
  public void writeContent(XMLExtendedStreamWriter writer, SubsystemMarshallingContext context)
      throws XMLStreamException {

    context.startSubsystemElement(Namespace.CURRENT.getUriString(), false);

    ModelNode node = context.getModelNode();

    writeAttribute(writer, Attribute.NATIVE.getLocalName(), node);
    writeAttribute(writer, Attribute.DEFAULT_VIRTUAL_SERVER.getLocalName(), node);
    writeAttribute(writer, Attribute.INSTANCE_ID.getLocalName(), node);
    if (node.hasDefined(CONTAINER_CONFIG)) {
      writeContainerConfig(writer, node.get(CONTAINER_CONFIG));
    }
    if (node.hasDefined(CONNECTOR)) {
      for (final Property connector : node.get(CONNECTOR).asPropertyList()) {
        final ModelNode config = connector.getValue();
        writer.writeStartElement(Element.CONNECTOR.getLocalName());
        writer.writeAttribute(NAME, connector.getName());
        writeAttribute(writer, Attribute.PROTOCOL.getLocalName(), config);
        writeAttribute(writer, Attribute.SOCKET_BINDING.getLocalName(), config);
        writeAttribute(writer, Attribute.SCHEME.getLocalName(), config);
        writeAttribute(writer, Attribute.ENABLED.getLocalName(), config);
        writeAttribute(writer, Attribute.ENABLE_LOOKUPS.getLocalName(), config);
        writeAttribute(writer, Attribute.PROXY_NAME.getLocalName(), config);
        writeAttribute(writer, Attribute.PROXY_PORT.getLocalName(), config);
        writeAttribute(writer, Attribute.SECURE.getLocalName(), config);
        writeAttribute(writer, Attribute.EXECUTOR.getLocalName(), config);
        writeAttribute(writer, Attribute.MAX_POST_SIZE.getLocalName(), config);
        writeAttribute(writer, Attribute.MAX_SAVE_POST_SIZE.getLocalName(), config);
        writeAttribute(writer, Attribute.MAX_CONNECTIONS.getLocalName(), config);
        writeAttribute(writer, Attribute.REDIRECT_PORT.getLocalName(), config);

        if (config.get(SSL).isDefined() && config.get(SSL).has("configuration")) {
          ModelNode sslConfig = config.get(SSL).get("configuration");
          writer.writeStartElement(Element.SSL.getLocalName());
          writeAttribute(writer, Attribute.NAME.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.KEY_ALIAS.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.PASSWORD.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.CERTIFICATE_KEY_FILE.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.CIPHER_SUITE.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.PROTOCOL.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.VERIFY_CLIENT.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.VERIFY_DEPTH.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.CERTIFICATE_FILE.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.CA_CERTIFICATE_FILE.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.CA_REVOCATION_URL.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.SESSION_CACHE_SIZE.getLocalName(), sslConfig);
          writeAttribute(writer, Attribute.SESSION_TIMEOUT.getLocalName(), sslConfig);
          writer.writeEndElement();
        }
        if (config.hasDefined(VIRTUAL_SERVER)) {
          for (final ModelNode virtualServer : config.get(VIRTUAL_SERVER).asList()) {
            writer.writeEmptyElement(VIRTUAL_SERVER);
            writer.writeAttribute(NAME, virtualServer.asString());
          }
        }

        writer.writeEndElement();
      }
    }
    if (node.hasDefined(VIRTUAL_SERVER)) {
      for (final Property host : node.get(VIRTUAL_SERVER).asPropertyList()) {
        final ModelNode config = host.getValue();
        writer.writeStartElement(Element.VIRTUAL_SERVER.getLocalName());
        writer.writeAttribute(NAME, host.getName());
        writeAttribute(writer, Attribute.DEFAULT_WEB_MODULE.getLocalName(), config);
        if (config.hasDefined(ENABLE_WELCOME_ROOT) && config.get(ENABLE_WELCOME_ROOT).asBoolean())
          writer.writeAttribute(ENABLE_WELCOME_ROOT, "true");

        if (config.hasDefined(ALIAS)) {
          for (final ModelNode alias : config.get(ALIAS).asList()) {
            writer.writeEmptyElement(ALIAS);
            writer.writeAttribute(NAME, alias.asString());
          }
        }

        if (config.get(ACCESS_LOG).isDefined() && config.get(ACCESS_LOG).has("configuration")) {
          ModelNode accessLog = config.get(ACCESS_LOG).get("configuration");
          writer.writeStartElement(Element.ACCESS_LOG.getLocalName());
          writeAttribute(writer, Attribute.PATTERN.getLocalName(), accessLog);
          writeAttribute(writer, Attribute.RESOLVE_HOSTS.getLocalName(), accessLog);
          writeAttribute(writer, Attribute.EXTENDED.getLocalName(), accessLog);
          writeAttribute(writer, Attribute.PREFIX.getLocalName(), accessLog);
          writeAttribute(writer, Attribute.ROTATE.getLocalName(), accessLog);

          if (accessLog.has(DIRECTORY) && accessLog.get(DIRECTORY).has("configuration")) {
            ModelNode directory = accessLog.get(DIRECTORY).get("configuration");
            String name = Element.DIRECTORY.getLocalName();
            boolean startwritten = false;
            startwritten =
                writeAttribute(
                    writer, Attribute.PATH.getLocalName(), directory, startwritten, name);
            startwritten =
                writeAttribute(
                    writer, Attribute.RELATIVE_TO.getLocalName(), directory, startwritten, name);
            if (startwritten) writer.writeEndElement();
          }
          writer.writeEndElement();
        }

        if (config.hasDefined(REWRITE)) {
          for (final ModelNode rewritenode : config.get(REWRITE).asList()) {
            String name = getAddedRule(rewritenode);
            ModelNode rewrite;
            if (rewritenode.hasDefined(name)) rewrite = rewritenode.get(name);
            else rewrite = rewritenode;
            writer.writeStartElement(REWRITE);
            writeAttribute(writer, Attribute.PATTERN.getLocalName(), rewrite);
            writeAttribute(writer, Attribute.SUBSTITUTION.getLocalName(), rewrite);
            writeAttribute(writer, Attribute.FLAGS.getLocalName(), rewrite);

            if (rewrite.hasDefined(CONDITION)) {
              for (final ModelNode conditionnode : rewrite.get(CONDITION).asList()) {
                String condname = getAddedConditionName(conditionnode);
                ModelNode condition;
                if (conditionnode.hasDefined(condname)) condition = conditionnode.get(condname);
                else condition = conditionnode;
                writer.writeStartElement(CONDITION);
                writeAttribute(writer, Attribute.TEST.getLocalName(), condition);
                writeAttribute(writer, Attribute.PATTERN.getLocalName(), condition);
                writeAttribute(writer, Attribute.FLAGS.getLocalName(), condition);
                writer.writeEndElement();
              }
            }
            writer.writeEndElement();
          }
        }

        if (config.hasDefined(SSO) && config.get(SSO).has("configuration")) {
          final ModelNode sso;
          sso = config.get(SSO).get("configuration");
          writer.writeStartElement(SSO);
          writeAttribute(writer, Attribute.CACHE_CONTAINER.getLocalName(), sso);
          writeAttribute(writer, Attribute.CACHE_NAME.getLocalName(), sso);
          writeAttribute(writer, Attribute.DOMAIN.getLocalName(), sso);
          writeAttribute(writer, Attribute.REAUTHENTICATE.getLocalName(), sso);
          writer.writeEndElement();
        }

        // End of the VIRTUAL_SERVER
        writer.writeEndElement();
      }
    }
    writer.writeEndElement();
  }
  public OperationResult execute(
      final OperationContext context, final ModelNode operation, final ResultHandler resultHandler)
      throws OperationFailedException {
    final ModelNode opAddr = operation.require(OP_ADDR);
    final String jndiName = PathAddress.pathAddress(opAddr).getLastElement().getValue();

    // Compensating is add
    final ModelNode model = context.getSubModel();
    final ModelNode compensating = Util.getEmptyOperation(ADD, opAddr);

    if (model.has(CONNECTION_PROPERTIES)) {
      for (ModelNode property : model.get(CONNECTION_PROPERTIES).asList()) {
        compensating
            .get(CONNECTION_PROPERTIES, property.asProperty().getName())
            .set(property.asString());
      }
    }
    for (final AttributeDefinition attribute : getModelProperties()) {
      if (model.get(attribute.getName()).isDefined()) {
        compensating.get(attribute.getName()).set(model.get(attribute.getName()));
      }
    }

    if (context.getRuntimeContext() != null) {
      context
          .getRuntimeContext()
          .setRuntimeTask(
              new RuntimeTask() {
                public void execute(RuntimeTaskContext context) throws OperationFailedException {
                  final ServiceRegistry registry = context.getServiceRegistry();

                  final ServiceName binderServiceName =
                      ContextNames.JAVA_CONTEXT_SERVICE_NAME.append(jndiName);
                  final ServiceController<?> binderController =
                      registry.getService(binderServiceName);
                  if (binderController != null) {
                    binderController.setMode(ServiceController.Mode.REMOVE);
                  }

                  final ServiceName referenceFactoryServiceName =
                      DataSourceReferenceFactoryService.SERVICE_NAME_BASE.append(jndiName);
                  final ServiceController<?> referenceFactoryController =
                      registry.getService(referenceFactoryServiceName);
                  if (referenceFactoryController != null) {
                    referenceFactoryController.setMode(ServiceController.Mode.REMOVE);
                  }

                  final ServiceName dataSourceServiceName =
                      AbstractDataSourceService.SERVICE_NAME_BASE.append(jndiName);
                  final ServiceController<?> dataSourceController =
                      registry.getService(dataSourceServiceName);
                  if (dataSourceController != null) {
                    dataSourceController.setMode(ServiceController.Mode.REMOVE);
                  }
                  resultHandler.handleResultComplete();
                }
              });
    } else {
      resultHandler.handleResultComplete();
    }

    return new BasicOperationResult(compensating);
  }
  protected void printProperties(CommandContext ctx, List<Property> props) {
    final Map<String, StringBuilder> requiredProps = new LinkedHashMap<String, StringBuilder>();
    requiredProps.put(
        this.name.getFullName(),
        new StringBuilder()
            .append(
                "Required argument in commands which identifies the instance to execute the command against."));
    final Map<String, StringBuilder> optionalProps = new LinkedHashMap<String, StringBuilder>();

    String accessType = null;
    for (Property attr : props) {
      final ModelNode value = attr.getValue();

      // filter metrics
      if (value.has("access-type")) {
        accessType = value.get("access-type").asString();
        //                if("metric".equals(accessType)) {
        //                    continue;
        //                }
      }

      final boolean required =
          value.hasDefined("required") ? value.get("required").asBoolean() : false;
      final StringBuilder descr = new StringBuilder();

      final String type = value.has("type") ? value.get("type").asString() : "no type info";
      if (value.hasDefined("description")) {
        descr.append('(');
        descr.append(type);
        if (accessType != null) {
          descr.append(',').append(accessType);
        }
        descr.append(") ");
        descr.append(value.get("description").asString());
      } else if (descr.length() == 0) {
        descr.append("no description.");
      }

      if (required) {
        if (idProperty != null && idProperty.equals(attr.getName())) {
          if (descr.charAt(descr.length() - 1) != '.') {
            descr.append('.');
          }
          requiredProps.get(this.name.getFullName()).insert(0, ' ').insert(0, descr.toString());
        } else {
          requiredProps.put("--" + attr.getName(), descr);
        }
      } else {
        optionalProps.put("--" + attr.getName(), descr);
      }
    }

    ctx.printLine("\n");
    if (accessType == null) {
      ctx.printLine("REQUIRED ARGUMENTS:\n");
    }
    for (String argName : requiredProps.keySet()) {
      final StringBuilder prop = new StringBuilder();
      prop.append(' ').append(argName);
      int spaces = 28 - prop.length();
      do {
        prop.append(' ');
        --spaces;
      } while (spaces >= 0);
      prop.append("- ").append(requiredProps.get(argName));
      ctx.printLine(prop.toString());
    }

    if (!optionalProps.isEmpty()) {
      if (accessType == null) {
        ctx.printLine("\n\nOPTIONAL ARGUMENTS:\n");
      }
      for (String argName : optionalProps.keySet()) {
        final StringBuilder prop = new StringBuilder();
        prop.append(' ').append(argName);
        int spaces = 28 - prop.length();
        do {
          prop.append(' ');
          --spaces;
        } while (spaces >= 0);
        prop.append("- ").append(optionalProps.get(argName));
        ctx.printLine(prop.toString());
      }
    }
  }
  private Map<String, CommandArgument> loadArguments(CommandContext ctx, String op) {
    if (op == null) {
      // list node properties
      if (nodeProps == null) {
        final List<Property> propList = getNodeProperties(ctx);
        final Map<String, CommandArgument> argMap =
            new HashMap<String, CommandArgument>(propList.size());
        for (int i = 0; i < propList.size(); ++i) {
          final Property prop = propList.get(i);
          final ModelNode propDescr = prop.getValue();
          if (propDescr.has("access-type")
              && "read-write".equals(propDescr.get("access-type").asString())) {
            ModelType type = null;
            CommandLineCompleter valueCompleter = null;
            ArgumentValueConverter valueConverter = ArgumentValueConverter.DEFAULT;
            if (propDescr.has("type")) {
              type = propDescr.get("type").asType();
              if (ModelType.BOOLEAN == type) {
                valueCompleter = SimpleTabCompleter.BOOLEAN;
                // TODO } else if(ModelType.PROPERTY == type) {
              } else if (prop.getName().endsWith("properties")) {
                valueConverter = ArgumentValueConverter.PROPERTIES;
              } else if (ModelType.LIST == type) {
                valueConverter = ArgumentValueConverter.LIST;
              }
            }
            final CommandArgument arg =
                new ArgumentWithValue(
                    GenericTypeOperationHandler.this,
                    valueCompleter,
                    valueConverter,
                    "--" + prop.getName());
            argMap.put(arg.getFullName(), arg);
          }
        }
        nodeProps = argMap;
      }
      return nodeProps;
    } else {
      // list operation properties
      if (propsByOp == null) {
        propsByOp = new HashMap<String, Map<String, CommandArgument>>();
      }
      Map<String, CommandArgument> opProps = propsByOp.get(op);
      if (opProps == null) {
        final ModelNode descr;
        try {
          descr = getOperationDescription(ctx, op);
        } catch (IOException e1) {
          return Collections.emptyMap();
        }

        if (descr == null || !descr.has("request-properties")) {
          opProps = Collections.emptyMap();
        } else {
          final List<Property> propList = descr.get("request-properties").asPropertyList();
          opProps = new HashMap<String, CommandArgument>(propList.size());
          for (Property prop : propList) {
            final ModelNode propDescr = prop.getValue();
            ModelType type = null;
            CommandLineCompleter valueCompleter = null;
            ArgumentValueConverter valueConverter = ArgumentValueConverter.DEFAULT;
            if (propDescr.has("type")) {
              type = propDescr.get("type").asType();
              if (ModelType.BOOLEAN == type) {
                valueCompleter = SimpleTabCompleter.BOOLEAN;
                // TODO } else if(ModelType.PROPERTY == type) {
              } else if (prop.getName().endsWith("properties")) {
                valueConverter = ArgumentValueConverter.PROPERTIES;
              } else if (ModelType.LIST == type) {
                valueConverter = ArgumentValueConverter.LIST;
              }
            }
            final CommandArgument arg =
                new ArgumentWithValue(
                    GenericTypeOperationHandler.this,
                    valueCompleter,
                    valueConverter,
                    "--" + prop.getName());
            opProps.put(arg.getFullName(), arg);
          }
        }
        propsByOp.put(op, opProps);
      }
      return opProps;
    }
  }
Example #30
0
 protected void populateModel(final ModelNode operation, final ModelNode model) {
   if (operation.has(ModelConstants.ACTIVATION)) {
     model.get(ModelConstants.ACTIVATION).set(operation.get(ModelConstants.ACTIVATION));
   }
 }