protected static void waitForHornetQServerActivation(
      JMSOperations operations, boolean expectedActive) throws IOException {
    long start = System.currentTimeMillis();
    long now;
    do {
      ModelNode operation = new ModelNode();
      operation.get(OP_ADDR).set(operations.getServerAddress());
      operation.get(OP).set(READ_RESOURCE_OPERATION);
      operation.get(INCLUDE_RUNTIME).set(true);
      operation.get(RECURSIVE).set(true);
      try {
        ModelNode result = execute(operations.getControllerClient(), operation);
        boolean started = result.get("started").asBoolean();
        boolean active = result.get("active").asBoolean();
        if (started && expectedActive == active) {
          // leave some time to the hornetq children resources to be installed after the server is
          // activated
          Thread.sleep(TimeoutUtil.adjust(500));

          return;
        }
      } catch (Exception e) {
      }
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
      }
      now = System.currentTimeMillis();
    } while (now - start < ACTIVATION_TIMEOUT);

    fail("Server did not become active in the imparted time.");
  }
 /** Re-tests 2 messages, both of them with the selected format. */
 @Test
 public void retestMessageSelectors() {
   sendTextMessage(
       "Say 1st hello to " + EJB2xMDB.class.getName() + " in 1.1 format",
       queue,
       replyQueueA,
       "Version 1.1");
   final Message replyA = receiveMessage(replyQueueA, TimeoutUtil.adjust(1000));
   Assert.assertNotNull("Missing reply from " + replyQueueA, replyA);
   sendTextMessage(
       "Say 2nd hello to " + EJB2xMDB.class.getName() + " in 1.1 format",
       queue,
       replyQueueB,
       "Version 1.1");
   final Message replyB = receiveMessage(replyQueueB, TimeoutUtil.adjust(1000));
   Assert.assertNotNull("Missing reply from " + replyQueueB, replyB);
 }
/**
 * @author: Ondrej Lukas
 *     <p>Test that fields of Audit log have right content
 */
@RunWith(Arquillian.class)
@RunAsClient
public class AuditLogFieldsOfLogTestCase {

  public static final String CONTAINER = "default-jbossas";
  private static final String FORMATTER = "formatter";
  private static final String JSON_FORMATTER = "json-formatter";
  private static final String SYSLOG_HANDLER_NAME = "audit-test-syslog-handler";
  final int PORT = 9276;

  @ArquillianResource private ContainerController container;

  ManagementClient managementClient;
  private File file;
  private File syslogFile;
  private PathAddress auditLogConfigAddress;
  private PathAddress mgmtRealmConfigAddress;
  private PathAddress syslogHandlerAddress;
  private PathAddress addSyslogHandler;
  private static SyslogServerIF server;
  private static BlockingQueue<String> queue;
  private static final int ADJUSTED_SECOND = TimeoutUtil.adjust(1000);

  @Test
  public void testAuditLoggingFields() throws Exception {
    container.start(CONTAINER);
    if (file.exists()) {
      file.delete();
    }
    Assert.assertTrue(makeOneLog());

    List<ModelNode> logs = readFile(file, 1);
    ModelNode log = logs.get(0);
    Assert.assertEquals("core", log.get("type").asString());
    Assert.assertEquals("false", log.get("r/o").asString());
    Assert.assertEquals("false", log.get("booting").asString());
    Assert.assertTrue(log.get("version").isDefined());
    Assert.assertEquals("IAmAdmin", log.get("user").asString());
    Assert.assertFalse(log.get("domainUUID").isDefined());
    Assert.assertEquals("NATIVE", log.get("access").asString());
    Assert.assertTrue(log.get("remote-address").isDefined());
    Assert.assertEquals("true", log.get("success").asString());
    List<ModelNode> operations = log.get("ops").asList();
    Assert.assertEquals(1, operations.size());

    if (syslogFile.exists()) {
      syslogFile.delete();
      server.getConfig().removeAllEventHandlers();
      server
          .getConfig()
          .addEventHandler(
              new BlockedFileSyslogServerEventHandler(queue, syslogFile.getAbsolutePath(), false));
    }
    Assert.assertTrue(makeOneLog());
    queue.poll(15 * ADJUSTED_SECOND, TimeUnit.MILLISECONDS);
    List<ModelNode> syslogLogs = readFile(syslogFile, 1);
    ModelNode syslogLog = syslogLogs.get(0);
    Assert.assertEquals("core", syslogLog.get("type").asString());
    Assert.assertEquals("false", syslogLog.get("r/o").asString());
    Assert.assertEquals("false", syslogLog.get("booting").asString());
    Assert.assertTrue(log.get("version").isDefined());
    Assert.assertEquals("IAmAdmin", syslogLog.get("user").asString());
    Assert.assertFalse(syslogLog.get("domainUUID").isDefined());
    Assert.assertEquals("NATIVE", syslogLog.get("access").asString());
    Assert.assertTrue(syslogLog.get("remote-address").isDefined());
    Assert.assertEquals("true", syslogLog.get("success").asString());
    List<ModelNode> syslogOperations = syslogLog.get("ops").asList();
    Assert.assertEquals(1, syslogOperations.size());
  }

  private boolean makeOneLog() throws IOException {
    ModelNode op =
        Util.getWriteAttributeOperation(
            auditLogConfigAddress,
            AuditLogLoggerResourceDefinition.LOG_BOOT.getName(),
            new ModelNode(true));
    ModelNode result = managementClient.getControllerClient().execute(op);
    return SUCCESS.equals(result.get(OUTCOME).asString());
  }

  @Before
  public void beforeTest() throws Exception {
    file = new File(System.getProperty("jboss.home"));
    file = new File(file, "standalone");
    file = new File(file, "data");
    file = new File(file, "audit-log.log");
    if (file.exists()) {
      file.delete();
    }

    syslogFile = new File(System.getProperty("jboss.home"));
    syslogFile = new File(syslogFile, "standalone");
    syslogFile = new File(syslogFile, "data");
    syslogFile = new File(syslogFile, "syslog-audit-log.log");
    if (syslogFile.exists()) {
      syslogFile.delete();
    }

    // start and set syslog server
    server = SyslogServer.getInstance("udp");
    server.getConfig().setPort(PORT);
    queue = new LinkedBlockingQueue<String>();
    server
        .getConfig()
        .addEventHandler(
            new BlockedFileSyslogServerEventHandler(queue, syslogFile.getAbsolutePath(), false));
    SyslogServer.getThreadedInstance("udp");

    // Start the server
    container.start(CONTAINER);
    final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
    managementClient =
        new ManagementClient(
            client,
            TestSuiteEnvironment.getServerAddress(),
            TestSuiteEnvironment.getServerPort(),
            "http-remoting");

    ModelNode op;
    ModelNode result;

    mgmtRealmConfigAddress =
        PathAddress.pathAddress(
            PathElement.pathElement(CORE_SERVICE, MANAGEMENT),
            PathElement.pathElement(SECURITY_REALM, "ManagementRealm"),
            PathElement.pathElement(AUTHENTICATION, LOCAL));
    op =
        Util.getWriteAttributeOperation(
            mgmtRealmConfigAddress, "default-user", new ModelNode("IAmAdmin"));
    result = client.execute(op);

    auditLogConfigAddress =
        PathAddress.pathAddress(
            CoreManagementResourceDefinition.PATH_ELEMENT,
            AccessAuditResourceDefinition.PATH_ELEMENT,
            AuditLogLoggerResourceDefinition.PATH_ELEMENT);

    op =
        Util.getWriteAttributeOperation(
            auditLogConfigAddress,
            AuditLogLoggerResourceDefinition.ENABLED.getName(),
            new ModelNode(true));
    result = client.execute(op);
    Assert.assertEquals(
        result.get("failure-description").asString(), SUCCESS, result.get(OUTCOME).asString());

    ModelNode compositeOp = new ModelNode();
    compositeOp.get(OP).set(COMPOSITE);
    compositeOp.get(OP_ADDR).setEmptyList();
    ModelNode steps = compositeOp.get(STEPS);
    syslogHandlerAddress =
        PathAddress.pathAddress(
            PathElement.pathElement(CORE_SERVICE, MANAGEMENT),
            PathElement.pathElement(ACCESS, AUDIT),
            PathElement.pathElement(SYSLOG_HANDLER, SYSLOG_HANDLER_NAME));
    op = Util.createAddOperation(syslogHandlerAddress);
    op.get(FORMATTER).set(JSON_FORMATTER);
    op.get(SYSLOG_FORMAT).set("RFC5424");
    steps.add(op);
    op = new ModelNode();
    PathAddress syslogProtocol =
        PathAddress.pathAddress(syslogHandlerAddress, PathElement.pathElement(PROTOCOL, UDP));
    op = Util.createAddOperation(syslogProtocol);
    op.get("port").set(PORT);
    op.get("host").set("localhost");
    steps.add(op);
    result = client.execute(compositeOp);
    Assert.assertEquals(
        result.get("failure-description").asString(), SUCCESS, result.get(OUTCOME).asString());

    addSyslogHandler =
        PathAddress.pathAddress(
            auditLogConfigAddress, PathElement.pathElement(HANDLER, SYSLOG_HANDLER_NAME));
    op = Util.createAddOperation(addSyslogHandler);
    result = client.execute(op);
    Assert.assertEquals(
        result.get("failure-description").asString(), SUCCESS, result.get(OUTCOME).asString());

    container.stop(CONTAINER);
    Thread.sleep(1000);
    while (managementClient.isServerInRunningState()) {
      Thread.sleep(50);
    }
  }

  @After
  public void afterTest() throws Exception {
    // stop syslog server
    SyslogServer.shutdown();
    server.setThread(null);
    server.getConfig().removeAllEventHandlers();

    final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
    ModelNode op =
        Util.getWriteAttributeOperation(
            auditLogConfigAddress,
            AuditLogLoggerResourceDefinition.ENABLED.getName(),
            new ModelNode(false));
    client.execute(op);
    op =
        Util.getWriteAttributeOperation(
            mgmtRealmConfigAddress, "default-user", new ModelNode("$local"));
    client.execute(op);

    op = Util.getResourceRemoveOperation(addSyslogHandler);
    client.execute(op);
    op = Util.getResourceRemoveOperation(syslogHandlerAddress);
    client.execute(op);

    if (file.exists()) {
      file.delete();
    }
    if (syslogFile.exists()) {
      syslogFile.delete();
    }
    try {
      // Stop the container
      container.stop(CONTAINER);
    } finally {
      IoUtils.safeClose(client);
    }
  }

  private final Pattern DATE_STAMP_PATTERN =
      Pattern.compile("\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d - \\{");

  protected List<ModelNode> readFile(File file, int expectedRecords) throws IOException {
    List<ModelNode> list = new ArrayList<ModelNode>();
    final BufferedReader reader = new BufferedReader(new FileReader(file));
    try {
      StringWriter writer = null;
      String line = reader.readLine();
      while (line != null) {
        if (DATE_STAMP_PATTERN.matcher(line).find()) {
          if (writer != null) {
            list.add(ModelNode.fromJSONString(writer.getBuffer().toString()));
          }
          writer = new StringWriter();
          writer.append("{");
        } else {
          if (writer != null) writer.append("\n" + line);
        }
        line = reader.readLine();
      }
      if (writer != null) {
        list.add(ModelNode.fromJSONString(writer.getBuffer().toString()));
      }
    } finally {
      IoUtils.safeClose(reader);
    }
    Assert.assertEquals(list.toString(), expectedRecords, list.size());
    return list;
  }
}
/**
 * Wrapper for several tests which require a slave to master reconnect, so that we need as few
 * reconnects as possible. It makes some assumptions about the HC/server process states, so don't
 * run this within a suite.
 *
 * @author Kabir Khan
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SlaveReconnectTestCase {

  static final PathAddress SLAVE_ADDR = PathAddress.pathAddress(HOST, "slave");

  private static DomainTestSupport testSupport;
  private static DomainLifecycleUtil domainMasterLifecycleUtil;
  private static DomainLifecycleUtil domainSlaveLifecycleUtil;

  private static final int ADJUSTED_SECOND = TimeoutUtil.adjust(1000);

  @BeforeClass
  public static void setupDomain() throws Exception {
    testSupport = DomainTestSuite.createSupport(SlaveReconnectTestCase.class.getSimpleName());
    domainMasterLifecycleUtil = testSupport.getDomainMasterLifecycleUtil();
    domainSlaveLifecycleUtil = testSupport.getDomainSlaveLifecycleUtil();
  }

  @AfterClass
  public static void tearDownDomain() throws Exception {
    testSupport = null;
    domainMasterLifecycleUtil = null;
    domainSlaveLifecycleUtil = null;
    DomainTestSuite.stopSupport();
  }

  @Test
  public void test01_OrderedExtensionsAndDeployments() throws Exception {
    testReconnect(
        new ReconnectTestScenario[] {
          new UnaffectedScenario(650),
          new OrderedChildResourceScenario(),
          new DeploymentScenario(750)
        });
  }

  @Test
  public void test02_DeploymentOverlays() throws Exception {
    // Since deployment-overlays affect all servers (https://issues.jboss.org/browse/WFCORE-710),
    // this needs to
    // be tested separately, and to come last since the server state gets affected
    testReconnect(
        new ReconnectTestScenario[] {
          new UnaffectedScenario(650), new DeploymentOverlayScenario(750)
        });
  }

  private void testReconnect(ReconnectTestScenario[] scenarios) throws Exception {
    int initialisedScenarios = -1;
    try {
      DomainClient masterClient = domainMasterLifecycleUtil.getDomainClient();
      DomainClient slaveClient = domainSlaveLifecycleUtil.getDomainClient();
      for (int i = 0; i < scenarios.length; i++) {
        initialisedScenarios = i;
        scenarios[i].setUpDomain(testSupport, masterClient, slaveClient);
      }

      for (ReconnectTestScenario scenario : scenarios) {
        scenario.testOnInitialStartup(masterClient, slaveClient);
      }

      // Restart the DC as admin-only
      ModelNode restartAdminOnly =
          Util.createEmptyOperation("reload", PathAddress.pathAddress(HOST, "master"));
      restartAdminOnly.get("admin-only").set(true);
      domainMasterLifecycleUtil.executeAwaitConnectionClosed(restartAdminOnly);
      domainMasterLifecycleUtil.connect();
      domainMasterLifecycleUtil.awaitHostController(System.currentTimeMillis());
      masterClient = domainMasterLifecycleUtil.createDomainClient();

      for (ReconnectTestScenario scenario : scenarios) {
        scenario.testWhileMasterInAdminOnly(masterClient, slaveClient);
      }

      // Restart the DC as normal
      restartAdminOnly.get("admin-only").set(false);
      domainMasterLifecycleUtil.executeAwaitConnectionClosed(restartAdminOnly);
      domainMasterLifecycleUtil.connect();
      domainMasterLifecycleUtil.awaitHostController(System.currentTimeMillis());
      masterClient = domainMasterLifecycleUtil.createDomainClient();

      // Wait for the slave to reconnect, look for the slave in the list of hosts
      long end = System.currentTimeMillis() + 20 * ADJUSTED_SECOND;
      boolean slaveReconnected = false;
      do {
        Thread.sleep(1 * ADJUSTED_SECOND);
        slaveReconnected = checkSlaveReconnected(masterClient);
      } while (!slaveReconnected && System.currentTimeMillis() < end);

      // Wait for master servers to come up
      end = System.currentTimeMillis() + 60 * ADJUSTED_SECOND;
      boolean serversUp = false;
      do {
        Thread.sleep(1 * ADJUSTED_SECOND);
        serversUp = checkHostServersStarted(masterClient, "master");
      } while (!serversUp && System.currentTimeMillis() < end);

      for (ReconnectTestScenario scenario : scenarios) {
        scenario.testAfterReconnect(masterClient, slaveClient);
      }
    } finally {
      for (int i = initialisedScenarios; i >= 0; i--) {
        scenarios[i].tearDownDomain(
            domainMasterLifecycleUtil.getDomainClient(),
            domainSlaveLifecycleUtil.getDomainClient());
      }
    }
  }

  private boolean checkSlaveReconnected(DomainClient masterClient) throws Exception {
    ModelNode op =
        Util.createEmptyOperation(READ_CHILDREN_NAMES_OPERATION, PathAddress.EMPTY_ADDRESS);
    op.get(CHILD_TYPE).set(HOST);
    try {
      ModelNode ret = DomainTestUtils.executeForResult(op, masterClient);
      List<ModelNode> list = ret.asList();
      if (list.size() == 2) {
        for (ModelNode entry : list) {
          if ("slave".equals(entry.asString())) {
            return true;
          }
        }
      }
    } catch (Exception e) {
    }
    return false;
  }

  private boolean checkHostServersStarted(DomainClient masterClient, String host) {
    try {
      ModelNode op =
          Util.createEmptyOperation(
              READ_CHILDREN_NAMES_OPERATION, PathAddress.pathAddress(HOST, host));
      op.get(CHILD_TYPE).set(SERVER);
      ModelNode ret = DomainTestUtils.executeForResult(op, masterClient);
      List<ModelNode> list = ret.asList();
      for (ModelNode entry : list) {
        String server = entry.asString();
        op =
            Util.createEmptyOperation(
                READ_ATTRIBUTE_OPERATION,
                PathAddress.pathAddress(HOST, host).append(SERVER, server));
        op.get(NAME).set("server-state");
        ModelNode state = DomainTestUtils.executeForResult(op, masterClient);
        if (SUCCESS.equals(state.get(OUTCOME).asString())) {
          return "running".equals(state.get(RESULT).asString());
        }
      }
      return false;
    } catch (Exception e) {
      return false;
    }
  }

  static void cloneProfile(DomainClient masterClient, String source, String target)
      throws Exception {
    ModelNode clone = Util.createEmptyOperation("clone", PathAddress.pathAddress(PROFILE, source));
    clone.get("to-profile").set(target);
    DomainTestUtils.executeForResult(clone, masterClient);
  }

  static void createServerGroup(DomainClient masterClient, String name, String profile)
      throws Exception {
    ModelNode add = Util.createAddOperation(PathAddress.pathAddress(SERVER_GROUP, name));
    add.get(PROFILE).set(profile);
    add.get(SOCKET_BINDING_GROUP).set("standard-sockets");
    DomainTestUtils.executeForResult(add, masterClient);
  }

  static void createServer(
      DomainClient slaveClient, String name, String serverGroup, int portOffset) throws Exception {
    ModelNode add = Util.createAddOperation(SLAVE_ADDR.append(SERVER_CONFIG, name));
    add.get(GROUP).set(serverGroup);
    add.get(PORT_OFFSET).set(portOffset);
    DomainTestUtils.executeForResult(add, slaveClient);
  }

  static void startServer(DomainClient slaveClient, String name) throws Exception {
    ModelNode start = Util.createEmptyOperation(START, SLAVE_ADDR.append(SERVER_CONFIG, name));
    start.get(BLOCKING).set(true);
    DomainTestUtils.executeForResult(start, slaveClient);
  }

  static void stopServer(DomainClient slaveClient, String name) throws Exception {
    PathAddress serverAddr = SLAVE_ADDR.append(SERVER_CONFIG, name);
    ModelNode stop = Util.createEmptyOperation(STOP, serverAddr);
    stop.get(BLOCKING).set(true);
    DomainTestUtils.executeForResult(stop, slaveClient);
  }

  static void removeProfile(DomainClient masterClient, String name) throws Exception {
    PathAddress profileAddr = PathAddress.pathAddress(PROFILE, name);
    DomainTestUtils.executeForResult(
        Util.createRemoveOperation(profileAddr.append(SUBSYSTEM, "logging")), masterClient);
    DomainTestUtils.executeForResult(Util.createRemoveOperation(profileAddr), masterClient);
  }
}
 protected static String performCall(final String url)
     throws ExecutionException, IOException, TimeoutException {
   return HttpRequest.get(url, TimeoutUtil.adjust(10), TimeUnit.SECONDS);
 }