@Test
  public void testGetQueueNames() throws Exception {
    SimpleString address = RandomUtil.randomSimpleString();
    SimpleString queue = RandomUtil.randomSimpleString();
    SimpleString anotherQueue = RandomUtil.randomSimpleString();

    session.createQueue(address, queue, true);

    AddressControl addressControl = createManagementControl(address);
    String[] queueNames = addressControl.getQueueNames();
    Assert.assertEquals(1, queueNames.length);
    Assert.assertEquals(queue.toString(), queueNames[0]);

    session.createQueue(address, anotherQueue, false);
    queueNames = addressControl.getQueueNames();
    Assert.assertEquals(2, queueNames.length);

    session.deleteQueue(queue);

    queueNames = addressControl.getQueueNames();
    Assert.assertEquals(1, queueNames.length);
    Assert.assertEquals(anotherQueue.toString(), queueNames[0]);

    session.deleteQueue(anotherQueue);
  }
  @Test
  public void testGetBindingNames() throws Exception {
    SimpleString address = RandomUtil.randomSimpleString();
    SimpleString queue = RandomUtil.randomSimpleString();
    String divertName = RandomUtil.randomString();

    session.createQueue(address, queue, false);

    AddressControl addressControl = createManagementControl(address);
    String[] bindingNames = addressControl.getBindingNames();
    assertEquals(1, bindingNames.length);
    assertEquals(queue.toString(), bindingNames[0]);

    server
        .getHornetQServerControl()
        .createDivert(
            divertName,
            randomString(),
            address.toString(),
            RandomUtil.randomString(),
            false,
            null,
            null);

    bindingNames = addressControl.getBindingNames();
    Assert.assertEquals(2, bindingNames.length);

    session.deleteQueue(queue);

    bindingNames = addressControl.getBindingNames();
    assertEquals(1, bindingNames.length);
    assertEquals(divertName.toString(), bindingNames[0]);
  }
  /**
   * Remove any old message queues that have a 0 message count in them. This lets us not worry about
   * changing around the registered listeners.
   */
  private void cleanupOldQueues() {
    log.debug("Cleaning old message queues");
    try {
      String[] queues = hornetqServer.getHornetQServer().getHornetQServerControl().getQueueNames();

      ServerLocator locator =
          HornetQClient.createServerLocatorWithoutHA(
              new TransportConfiguration(InVMConnectorFactory.class.getName()));

      ClientSessionFactory factory = locator.createSessionFactory();
      ClientSession session = factory.createSession(true, true);
      session.start();

      for (int i = 0; i < queues.length; i++) {
        long msgCount = session.queueQuery(new SimpleString(queues[i])).getMessageCount();
        if (msgCount == 0) {
          log.debug(String.format("found queue '%s' with 0 messages. deleting", queues[i]));
          session.deleteQueue(queues[i]);
        } else {
          log.debug(String.format("found queue '%s' with %d messages. kept", queues[i], msgCount));
        }
      }

      session.stop();
      session.close();
    } catch (HornetQException e) {
      log.error("Problem cleaning old message queues:", e);
      throw new RuntimeException(e);
    } catch (Exception e) {
      log.error("Problem cleaning old message queues:", e);
      throw new RuntimeException(e);
    }
  }
  @Test
  public void testGetAddress() throws Exception {
    SimpleString address = RandomUtil.randomSimpleString();
    SimpleString queue = RandomUtil.randomSimpleString();

    session.createQueue(address, queue, false);

    AddressControl addressControl = createManagementControl(address);

    Assert.assertEquals(address.toString(), addressControl.getAddress());

    session.deleteQueue(queue);
  }
  private void deleteSubscriberQueue(QueueConsumer consumer) {
    String subscriptionName = consumer.getId();
    ClientSession session = null;
    try {
      session = sessionFactory.createSession();

      session.deleteQueue(subscriptionName);
    } catch (HornetQException e) {
    } finally {
      if (session != null) {
        try {
          session.close();
        } catch (HornetQException e) {
        }
      }
    }
  }
  @Test
  public void testGetRolesAsJSON() throws Exception {
    SimpleString address = RandomUtil.randomSimpleString();
    SimpleString queue = RandomUtil.randomSimpleString();
    Role role =
        new Role(
            RandomUtil.randomString(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean());

    session.createQueue(address, queue, true);

    AddressControl addressControl = createManagementControl(address);
    String jsonString = addressControl.getRolesAsJSON();
    Assert.assertNotNull(jsonString);
    RoleInfo[] roles = RoleInfo.from(jsonString);
    Assert.assertEquals(0, roles.length);

    Set<Role> newRoles = new HashSet<Role>();
    newRoles.add(role);
    server.getSecurityRepository().addMatch(address.toString(), newRoles);

    jsonString = addressControl.getRolesAsJSON();
    Assert.assertNotNull(jsonString);
    roles = RoleInfo.from(jsonString);
    Assert.assertEquals(1, roles.length);
    RoleInfo r = roles[0];
    Assert.assertEquals(role.getName(), roles[0].getName());
    Assert.assertEquals(role.isSend(), r.isSend());
    Assert.assertEquals(role.isConsume(), r.isConsume());
    Assert.assertEquals(role.isCreateDurableQueue(), r.isCreateDurableQueue());
    Assert.assertEquals(role.isDeleteDurableQueue(), r.isDeleteDurableQueue());
    Assert.assertEquals(role.isCreateNonDurableQueue(), r.isCreateNonDurableQueue());
    Assert.assertEquals(role.isDeleteNonDurableQueue(), r.isDeleteNonDurableQueue());
    Assert.assertEquals(role.isManage(), r.isManage());

    session.deleteQueue(queue);
  }
  @Test
  public void testGetRoles() throws Exception {
    SimpleString address = RandomUtil.randomSimpleString();
    SimpleString queue = RandomUtil.randomSimpleString();
    Role role =
        new Role(
            RandomUtil.randomString(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean(),
            RandomUtil.randomBoolean());

    session.createQueue(address, queue, true);

    AddressControl addressControl = createManagementControl(address);
    Object[] roles = addressControl.getRoles();
    Assert.assertEquals(0, roles.length);

    Set<Role> newRoles = new HashSet<Role>();
    newRoles.add(role);
    server.getSecurityRepository().addMatch(address.toString(), newRoles);

    roles = addressControl.getRoles();
    Assert.assertEquals(1, roles.length);
    Object[] r = (Object[]) roles[0];
    Assert.assertEquals(role.getName(), r[0]);
    Assert.assertEquals(CheckType.SEND.hasRole(role), r[1]);
    Assert.assertEquals(CheckType.CONSUME.hasRole(role), r[2]);
    Assert.assertEquals(CheckType.CREATE_DURABLE_QUEUE.hasRole(role), r[3]);
    Assert.assertEquals(CheckType.DELETE_DURABLE_QUEUE.hasRole(role), r[4]);
    Assert.assertEquals(CheckType.CREATE_NON_DURABLE_QUEUE.hasRole(role), r[5]);
    Assert.assertEquals(CheckType.DELETE_NON_DURABLE_QUEUE.hasRole(role), r[6]);
    Assert.assertEquals(CheckType.MANAGE.hasRole(role), r[7]);

    session.deleteQueue(queue);
  }
  /**
   * https://jira.jboss.org/jira/browse/HORNETQ-286
   *
   * <p>the test checks that the temp queue is properly propagated to the cluster (assuming we wait
   * for the bindings)
   */
  @Test
  public void testSendToTempQueueFromAnotherClusterNode() throws Exception {
    setupCluster();

    startServers(0, 1);

    setupSessionFactory(0, isNetty());
    setupSessionFactory(1, isNetty());

    String tempAddress = "queues.tempaddress";
    String tempQueue = "tempqueue";
    // create temp queue on node #0
    ClientSession session = sfs[0].createSession(false, true, true);
    session.createTemporaryQueue(tempAddress, tempQueue);
    ClientConsumer consumer = session.createConsumer(tempQueue);

    // check the binding is created on node #1
    waitForBindings(1, tempAddress, 1, 1, false);

    // send to the temp address on node #1
    send(1, tempAddress, 10, false, null);

    session.start();

    // check consumer bound to node #0 receives from the temp queue
    for (int j = 0; j < 10; j++) {
      ClientMessage message = consumer.receive(5000);
      if (message == null) {
        Assert.assertNotNull("consumer did not receive message on temp queue " + j, message);
      }
      message.acknowledge();
    }

    consumer.close();
    session.deleteQueue(tempQueue);
    session.close();
  }
  public void testCreateAndDestroyBridge() throws Exception {
    String name = RandomUtil.randomString();
    String sourceAddress = RandomUtil.randomString();
    String sourceQueue = RandomUtil.randomString();
    String targetAddress = RandomUtil.randomString();
    String targetQueue = RandomUtil.randomString();

    HornetQServerControl serverControl = createManagementControl();

    checkNoResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name));
    assertEquals(0, serverControl.getBridgeNames().length);

    ServerLocator locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    ClientSessionFactory csf = locator.createSessionFactory();
    ClientSession session = csf.createSession();

    session.createQueue(sourceAddress, sourceQueue);
    session.createQueue(targetAddress, targetQueue);

    serverControl.createBridge(
        name,
        sourceQueue,
        targetAddress,
        null, // forwardingAddress
        null, // filterString
        HornetQClient.DEFAULT_RETRY_INTERVAL,
        HornetQClient.DEFAULT_RETRY_INTERVAL_MULTIPLIER,
        HornetQClient.DEFAULT_RECONNECT_ATTEMPTS,
        false, // duplicateDetection
        1, // confirmationWindowSize
        HornetQClient.DEFAULT_CLIENT_FAILURE_CHECK_PERIOD,
        connectorConfig.getName(), // liveConnector
        false,
        false,
        null,
        null);

    checkResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name));
    String[] bridgeNames = serverControl.getBridgeNames();
    assertEquals(1, bridgeNames.length);
    assertEquals(name, bridgeNames[0]);

    BridgeControl bridgeControl = ManagementControlHelper.createBridgeControl(name, mbeanServer);
    assertEquals(name, bridgeControl.getName());
    assertTrue(bridgeControl.isStarted());

    // check that a message sent to the sourceAddress is put in the tagetQueue
    ClientProducer producer = session.createProducer(sourceAddress);
    ClientMessage message = session.createMessage(false);
    String text = RandomUtil.randomString();
    message.putStringProperty("prop", text);
    producer.send(message);

    session.start();

    ClientConsumer targetConsumer = session.createConsumer(targetQueue);
    message = targetConsumer.receive(5000);
    assertNotNull(message);
    assertEquals(text, message.getStringProperty("prop"));

    ClientConsumer sourceConsumer = session.createConsumer(sourceQueue);
    assertNull(sourceConsumer.receiveImmediate());

    serverControl.destroyBridge(name);

    checkNoResource(ObjectNameBuilder.DEFAULT.getBridgeObjectName(name));
    assertEquals(0, serverControl.getBridgeNames().length);

    // check that a message is no longer diverted
    message = session.createMessage(false);
    String text2 = RandomUtil.randomString();
    message.putStringProperty("prop", text2);
    producer.send(message);

    assertNull(targetConsumer.receiveImmediate());
    message = sourceConsumer.receive(5000);
    assertNotNull(message);
    assertEquals(text2, message.getStringProperty("prop"));

    sourceConsumer.close();
    targetConsumer.close();

    session.deleteQueue(sourceQueue);
    session.deleteQueue(targetQueue);

    session.close();

    locator.close();
  }
  public void testCreateAndDestroyDivert() throws Exception {
    String address = RandomUtil.randomString();
    String name = RandomUtil.randomString();
    String routingName = RandomUtil.randomString();
    String forwardingAddress = RandomUtil.randomString();

    HornetQServerControl serverControl = createManagementControl();

    checkNoResource(ObjectNameBuilder.DEFAULT.getDivertObjectName(name));
    assertEquals(0, serverControl.getDivertNames().length);

    serverControl.createDivert(
        name.toString(), routingName, address, forwardingAddress, true, null, null);

    checkResource(ObjectNameBuilder.DEFAULT.getDivertObjectName(name));
    DivertControl divertControl =
        ManagementControlHelper.createDivertControl(name.toString(), mbeanServer);
    assertEquals(name.toString(), divertControl.getUniqueName());
    assertEquals(address, divertControl.getAddress());
    assertEquals(forwardingAddress, divertControl.getForwardingAddress());
    assertEquals(routingName, divertControl.getRoutingName());
    assertTrue(divertControl.isExclusive());
    assertNull(divertControl.getFilter());
    assertNull(divertControl.getTransformerClassName());
    String[] divertNames = serverControl.getDivertNames();
    assertEquals(1, divertNames.length);
    assertEquals(name, divertNames[0]);

    // check that a message sent to the address is diverted exclusively
    ServerLocator locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));

    ClientSessionFactory csf = locator.createSessionFactory();
    ClientSession session = csf.createSession();

    String divertQueue = RandomUtil.randomString();
    String queue = RandomUtil.randomString();
    session.createQueue(forwardingAddress, divertQueue);
    session.createQueue(address, queue);

    ClientProducer producer = session.createProducer(address);
    ClientMessage message = session.createMessage(false);
    String text = RandomUtil.randomString();
    message.putStringProperty("prop", text);
    producer.send(message);

    ClientConsumer consumer = session.createConsumer(queue);
    ClientConsumer divertedConsumer = session.createConsumer(divertQueue);

    session.start();

    assertNull(consumer.receiveImmediate());
    message = divertedConsumer.receive(5000);
    assertNotNull(message);
    assertEquals(text, message.getStringProperty("prop"));

    serverControl.destroyDivert(name.toString());

    checkNoResource(ObjectNameBuilder.DEFAULT.getDivertObjectName(name));
    assertEquals(0, serverControl.getDivertNames().length);

    // check that a message is no longer diverted
    message = session.createMessage(false);
    String text2 = RandomUtil.randomString();
    message.putStringProperty("prop", text2);
    producer.send(message);

    assertNull(divertedConsumer.receiveImmediate());
    message = consumer.receive(5000);
    assertNotNull(message);
    assertEquals(text2, message.getStringProperty("prop"));

    consumer.close();
    divertedConsumer.close();
    session.deleteQueue(queue);
    session.deleteQueue(divertQueue);
    session.close();

    locator.close();
  }