private void testDeployment(final Archive<?> archive) throws IOException {
    final ModelControllerClient client = domainMasterLifecycleUtil.getDomainClient();
    final ModelNode readServerSubsystems =
        Operations.createOperation(
            ClientConstants.READ_CHILDREN_NAMES_OPERATION,
            Operations.createAddress("host", "master", "server", "main-one"));
    readServerSubsystems.get(ClientConstants.CHILD_TYPE).set(ClientConstants.SUBSYSTEM);

    final String name = archive.getName();

    // Deploy the archive
    execute(
        client,
        createDeployAddOperation(archive.as(ZipExporter.class).exportAsInputStream(), name, null));
    Assert.assertTrue("Deployment " + name + "  was not deployed.", hasDeployment(client, name));

    // Validate the subsystem child names on a server
    ModelNode result = execute(client, readServerSubsystems);
    validateSubsystemModel("/host=master/server=main-one", result);

    // Fully replace the deployment, but with the 'enabled' flag set to false, triggering undeploy
    final Operation fullReplaceOp =
        createReplaceAndDisableOperation(
            archive.as(ZipExporter.class).exportAsInputStream(), name, null);
    execute(client, fullReplaceOp);

    // Below validates that WFCORE-1577 is fixed, the model should not be missing on the
    // /host=master/server=main-one or main-two

    // Validate the subsystem child names
    result = execute(client, readServerSubsystems);
    validateSubsystemModel("/host=master/server=main-one", result);
  }
  @Test
  public void testOperations() throws Exception {
    final ManagementClient managementClient = createManagementClient();
    final ModelControllerClient client = managementClient.getControllerClient();
    try {

      // Create the custom formatter
      ModelNode op = Operations.createAddOperation(CUSTOM_FORMATTER_ADDRESS);
      op.get("class").set("org.jboss.logmanager.formatters.PatternFormatter");
      op.get("module").set("org.jboss.logmanager");
      executeOperation(client, op);

      // Write some properties
      final ModelNode properties = new ModelNode().setEmptyList();
      properties.add("pattern", "%s%E%n");
      testWrite(client, CUSTOM_FORMATTER_ADDRESS, "properties", properties);

      // Undefine the properties
      testUndefine(client, CUSTOM_FORMATTER_ADDRESS, "properties");

      // Write a new class attribute, should leave in restart state
      ModelNode result =
          testWrite(client, CUSTOM_FORMATTER_ADDRESS, "class", "java.util.logging.XMLFormatter");
      // Check the state
      Assert.assertTrue(
          result.get("response-headers").get("operation-requires-reload").asBoolean());

      // Undefining the class should fail
      testUndefine(client, CUSTOM_FORMATTER_ADDRESS, "class", true);

      // Restart the server
      restart(managementClient);

      // Change the module which should require a restart
      result = testWrite(client, CUSTOM_FORMATTER_ADDRESS, "module", "sun.jdk");
      // Check the state
      Assert.assertTrue(
          result.get("response-headers").get("operation-requires-reload").asBoolean());

      // Undefining the module should fail
      testUndefine(client, CUSTOM_FORMATTER_ADDRESS, "module", true);

      // Restart the server
      restart(managementClient);

      // Remove the custom formatter
      op = Operations.createRemoveOperation(CUSTOM_FORMATTER_ADDRESS);
      executeOperation(client, op);

      // Verify it's been removed
      verifyRemoved(client, CUSTOM_FORMATTER_ADDRESS);

    } finally {
      safeClose(managementClient);
      safeClose(client);
    }
  }
 protected ModelNode testWrite(
     final ModelNode address, final String attribute, final ModelNode value) throws IOException {
   final CompositeOperationBuilder builder = CompositeOperationBuilder.create();
   builder.addStep(Operations.createWriteAttributeOperation(address, attribute, value));
   // Create the read operation
   builder.addStep(Operations.createReadAttributeOperation(address, attribute));
   final ModelNode result = executeOperation(builder.build());
   assertEquals(value, Operations.readResult(Operations.readResult(result).get("step-2")));
   return result;
 }
  @Test
  @RunAsClient
  public void testClient() throws Exception {

    ModelControllerClient client =
        ModelControllerClient.Factory.create(
            "localhost", 9990, new AuthCallbackHandler("bob", "tacos!"));

    ModelNode response = client.execute(Operations.createOperation("whoami"));

    assertThat(response.get("outcome").asString()).isEqualTo("success");

    ModelNode result = response.get("result");

    assertThat(result).isNotNull();
    assertThat(result.isDefined()).isTrue();

    ModelNode identity = result.get("identity");

    assertThat(identity).isNotNull();
    assertThat(identity.isDefined()).isTrue();

    assertThat(identity.get("username").asString()).isEqualTo("bob");

    // ===

    response =
        client.execute(
            Operations.createOperation(
                "read-resource",
                PathAddress.pathAddress(PathElement.pathElement("deployment", "*")).toModelNode()));

    assertThat(response.get("outcome").asString()).isEqualTo("success");

    result = response.get("result");

    assertThat(result).isNotNull();
    assertThat(result.isDefined()).isTrue();
    assertThat(result.getType()).isEqualTo(ModelType.LIST);
    assertThat(result.asList()).hasSize(1);

    ModelNode myapp = result.get(0);

    assertThat(myapp).isNotNull();
    assertThat(myapp.isDefined()).isTrue();

    ModelNode myappResult = myapp.get("result");

    assertThat(myappResult).isNotNull();
    assertThat(myappResult.isDefined()).isTrue();

    assertThat(myappResult.get("name").asString()).isEqualTo("myapp.jar");
  }
 static boolean isStandaloneRunning(final ModelControllerClient client) {
   try {
     final ModelNode response =
         client.execute(Operations.createReadAttributeOperation(EMPTY_ADDRESS, "server-state"));
     if (Operations.isSuccessfulOutcome(response)) {
       final String state = Operations.readResult(response).asString();
       return !CONTROLLER_PROCESS_STATE_STARTING.equals(state)
           && !CONTROLLER_PROCESS_STATE_STOPPING.equals(state);
     }
   } catch (RuntimeException | IOException e) {
     LOGGER.debug("Interrupted determining if standalone is running", e);
   }
   return false;
 }
 static File getAbsoluteLogFilePath(final ManagementClient client, final String filename)
     throws IOException, MgmtOperationException {
   final ModelNode address =
       PathAddress.pathAddress(
               PathElement.pathElement(ModelDescriptionConstants.PATH, "jboss.server.log.dir"))
           .toModelNode();
   final ModelNode op =
       Operations.createReadAttributeOperation(address, ModelDescriptionConstants.PATH);
   final ModelNode result = client.getControllerClient().execute(op);
   if (Operations.isSuccessfulOutcome(result)) {
     return new File(Operations.readResult(result).asString(), filename);
   }
   throw new MgmtOperationException("Failed to read the path resource", op, result);
 }
 @Test
 public void testExcludeLegacy() throws Exception {
   ModelControllerClient client = getModelControllerClient();
   final ModelNode add =
       Util.createAddOperation(
           PathAddress.pathAddress(
               PathAddress.pathAddress()
                   .append(PathElement.pathElement(CORE_SERVICE, MANAGEMENT))
                   .append(LegacyConfigurationChangeResourceDefinition.PATH)));
   add.get("max-history").set(MAX_HISTORY_SIZE);
   ModelNode response = client.execute(add);
   Assert.assertFalse(Operations.isSuccessfulOutcome(response));
   assertThat(
       Operations.getFailureDescription(response).asString(), containsString("WFLYCTL0158"));
 }
 private static ModelNode execute(
     final ModelControllerClient client, final Operation op, final boolean expectFailure)
     throws IOException {
   final ModelNode result = client.execute(op);
   if (Operations.isSuccessfulOutcome(result)) {
     return Operations.readResult(result);
   }
   if (!expectFailure) {
     throw new RuntimeException(
         String.format(
             "Failed to execute operation: %s%n%s",
             op.getOperation(), Operations.getFailureDescription(result)));
   }
   return Operations.getFailureDescription(result);
 }
 static void shutdownDomain(
     final DomainClient client, final Map<ServerIdentity, ServerStatus> servers) {
   final ModelNode address = new ModelNode().setEmptyList().add("host", "master");
   try {
     // First shutdown the servers
     ModelNode op = Operations.createOperation("stop-servers");
     ModelNode response = client.execute(op);
     if (Operations.isSuccessfulOutcome(response)) {
       op = Operations.createOperation("shutdown", address);
       response = client.execute(op);
       if (Operations.isSuccessfulOutcome(response)) {
         // Wait until the process has died
         while (true) {
           if (isDomainRunning(client, servers, true)) {
             try {
               TimeUnit.MILLISECONDS.sleep(20L);
             } catch (InterruptedException e) {
               LOGGER.debug("Interrupted during sleep", e);
             }
           } else {
             break;
           }
         }
       } else {
         LOGGER.debugf("Failed to execute %s: %s", op, Operations.getFailureDescription(response));
       }
     } else {
       LOGGER.debugf("Failed to execute %s: %s", op, Operations.getFailureDescription(response));
     }
   } catch (IOException e) {
     LOGGER.debug("Error shutting down domain", e);
   }
 }
  private static Operation createDeployAddOperation(
      final InputStream content, final String name, final String runtimeName) {
    final Operations.CompositeOperationBuilder builder =
        Operations.CompositeOperationBuilder.create(true);
    final ModelNode address = createAddress(DEPLOYMENT, name);
    final ModelNode addOperation = createAddOperation(address);
    if (runtimeName != null) {
      addOperation.get(RUNTIME_NAME).set(runtimeName);
    }
    addContent(builder, addOperation, content);
    builder.addStep(addOperation);

    final ModelNode sgAddress =
        Operations.createAddress(SERVER_GROUP, "main-server-group", DEPLOYMENT, name);
    final ModelNode op = Operations.createAddOperation(sgAddress);
    op.get("enabled").set(true);
    if (runtimeName != null) {
      op.get(RUNTIME_NAME).set(runtimeName);
    }
    builder.addStep(op);
    return builder.build();
  }
 static void shutdownStandalone(final ModelControllerClient client) {
   try {
     final ModelNode op = Operations.createOperation("shutdown");
     final ModelNode response = client.execute(op);
     if (Operations.isSuccessfulOutcome(response)) {
       while (true) {
         if (isStandaloneRunning(client)) {
           try {
             TimeUnit.MILLISECONDS.sleep(20L);
           } catch (InterruptedException e) {
             LOGGER.debug("Interrupted during sleep", e);
           }
         } else {
           break;
         }
       }
     } else {
       LOGGER.debugf("Failed to execute %s: %s", op, Operations.getFailureDescription(response));
     }
   } catch (IOException e) {
     LOGGER.debug("Interrupted shutting down standalone", e);
   }
 }
 private static boolean hasDeployment(final ModelControllerClient client, final String name)
     throws IOException {
   final ModelNode op = Operations.createOperation(ClientConstants.READ_CHILDREN_NAMES_OPERATION);
   op.get(CHILD_TYPE).set(DEPLOYMENT);
   final ModelNode listDeploymentsResult;
   try {
     listDeploymentsResult = client.execute(op);
     // Check to make sure there is an outcome
     if (Operations.isSuccessfulOutcome(listDeploymentsResult)) {
       final List<ModelNode> deployments = Operations.readResult(listDeploymentsResult).asList();
       for (ModelNode deployment : deployments) {
         if (name.equals(deployment.asString())) {
           return true;
         }
       }
     } else {
       throw new IllegalStateException(
           Operations.getFailureDescription(listDeploymentsResult).asString());
     }
   } catch (IOException e) {
     throw new IllegalStateException(String.format("Could not execute operation '%s'", op), e);
   }
   return false;
 }
 protected ModelNode testUndefine(
     final ModelNode address, final String attribute, final boolean expectFailure)
     throws IOException {
   final CompositeOperationBuilder builder = CompositeOperationBuilder.create();
   builder.addStep(Operations.createUndefineAttributeOperation(address, attribute));
   // Create the read operation
   final ModelNode readOp = Operations.createReadAttributeOperation(address, attribute);
   readOp.get("include-defaults").set(false);
   builder.addStep(readOp);
   final ModelNode result = client.getControllerClient().execute(builder.build());
   if (expectFailure) {
     assertFalse(
         "Undefining attribute " + attribute + " should have failed.",
         Operations.isSuccessfulOutcome(result));
   } else {
     if (!Operations.isSuccessfulOutcome(result)) {
       Assert.fail(Operations.getFailureDescription(result).toString());
     }
     assertFalse(
         "Attribute '" + attribute + "' was not undefined.",
         Operations.readResult(Operations.readResult(result).get("step-2")).isDefined());
   }
   return result;
 }
 protected void verifyRemoved(final ModelNode address) throws IOException {
   final ModelNode op = Operations.createReadResourceOperation(address);
   final ModelNode result = client.getControllerClient().execute(op);
   assertFalse("Resource not removed: " + address, Operations.isSuccessfulOutcome(result));
 }
  @Test
  public void testUsage(@ArquillianResource URL url) throws Exception {
    final ManagementClient managementClient = createManagementClient();
    final ModelControllerClient client = managementClient.getControllerClient();
    try {

      // Create the custom formatter
      ModelNode op = Operations.createAddOperation(CUSTOM_FORMATTER_ADDRESS);
      op.get("class").set("java.util.logging.XMLFormatter");
      // the module doesn't really matter since it's a JDK, so we'll just use the jboss-logmanager.
      op.get("module").set("org.jboss.logmanager");
      executeOperation(client, op);

      // Create the handler
      op = Operations.createAddOperation(HANDLER_ADDRESS);
      final ModelNode file = op.get("file");
      file.get("relative-to").set("jboss.server.log.dir");
      file.get("path").set(FILE_NAME);
      op.get("append").set(false);
      op.get("autoflush").set(true);
      op.get("named-formatter").set(CUSTOM_FORMATTER_NAME);
      executeOperation(client, op);

      // Add the handler to the root logger
      op = Operations.createOperation("add-handler", ROOT_LOGGER_ADDRESS);
      op.get(ModelDescriptionConstants.NAME).set(HANDLER_NAME);
      executeOperation(client, op);

      // Get the log file
      op = Operations.createOperation("resolve-path", HANDLER_ADDRESS);
      ModelNode result = executeOperation(client, op);
      final Path logFile = Paths.get(readResultAsString(result));

      // The file should exist
      Assert.assertTrue("The log file was not created.", Files.exists(logFile));

      // Log 5 records
      doLog(url, "Test message: ", 5);

      // Read the log file
      try (BufferedReader reader = Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) {
        final Pattern pattern = Pattern.compile("^(<message>)+(Test message: \\d)+(</message>)$");
        final List<String> messages = new ArrayList<>(5);
        String line;
        while ((line = reader.readLine()) != null) {
          final String trimmedLine = line.trim();
          final Matcher m = pattern.matcher(trimmedLine);
          // Very simple xml parsing
          if (m.matches()) {
            messages.add(m.group(2));
          }
        }

        // Should be 5 messages
        Assert.assertEquals(5, messages.size());
        // Check each message
        int count = 0;
        for (String msg : messages) {
          Assert.assertEquals("Test message: " + count++, msg);
        }
      }

      // Remove the handler from the root-logger
      op = Operations.createOperation("remove-handler", ROOT_LOGGER_ADDRESS);
      op.get(ModelDescriptionConstants.NAME).set(HANDLER_NAME);
      executeOperation(client, op);

      // Remove the custom formatter
      op = Operations.createRemoveOperation(CUSTOM_FORMATTER_ADDRESS);
      executeOperation(client, op);

      // Remove the handler
      op = Operations.createRemoveOperation(HANDLER_ADDRESS);
      executeOperation(client, op);

      // So we don't pollute other, verify the formatter and handler have been removed
      op = Operations.createReadAttributeOperation(ROOT_LOGGER_ADDRESS, "handlers");
      result = executeOperation(client, op);
      // Should be a list type
      final List<ModelNode> handlers = Operations.readResult(result).asList();
      for (ModelNode handler : handlers) {
        Assert.assertNotEquals(CUSTOM_FORMATTER_NAME, handler.asString());
      }
      verifyRemoved(client, CUSTOM_FORMATTER_ADDRESS);
      verifyRemoved(client, HANDLER_ADDRESS);

      // Delete the log file
      Files.delete(logFile);
      // Ensure it's been deleted
      Assert.assertFalse(Files.exists(logFile));
    } finally {
      safeClose(managementClient);
      safeClose(client);
    }
  }
 void executeOperation(final ModelNode op) throws IOException {
   ModelNode result = getManagementClient().getControllerClient().execute(op);
   if (!Operations.isSuccessfulOutcome(result)) {
     Assert.assertTrue(Operations.getFailureDescription(result).toString(), false);
   }
 }