Example #1
0
  @Override
  @After
  public void tearDown() throws Exception {
    if (clientSession != null) {
      try {
        clientSession.close();
      } catch (HornetQException e1) {
        //
      }
    }
    if (clientSessionXa != null) {
      try {
        clientSessionXa.close();
      } catch (HornetQException e1) {
        //
      }
    }
    if (locator != null) {
      locator.close();
    }
    if (server != null && server.isStarted()) {
      try {
        server.stop();
      } catch (Exception e1) {
        //
      }
    }
    server = null;
    clientSession = null;

    super.tearDown();
  }
  public ConnectionEntry createConnectionEntry(
      final Acceptor acceptorUsed, final Connection connection) {
    final Configuration config = server.getConfiguration();

    Executor connectionExecutor = server.getExecutorFactory().getExecutor();

    final CoreRemotingConnection rc =
        new RemotingConnectionImpl(
            connection,
            interceptors,
            config.isAsyncConnectionExecutionEnabled() ? connectionExecutor : null,
            server.getNodeID());

    Channel channel1 = rc.getChannel(CHANNEL_ID.SESSION.id, -1);

    ChannelHandler handler = new HornetQPacketHandler(this, server, channel1, rc);

    channel1.setHandler(handler);

    long ttl = HornetQClient.DEFAULT_CONNECTION_TTL;

    if (config.getConnectionTTLOverride() != -1) {
      ttl = config.getConnectionTTLOverride();
    }

    final ConnectionEntry entry =
        new ConnectionEntry(rc, connectionExecutor, System.currentTimeMillis(), ttl);

    final Channel channel0 = rc.getChannel(0, -1);

    channel0.setHandler(new LocalChannelHandler(config, entry, channel0, acceptorUsed, rc));

    return entry;
  }
Example #3
0
  @Test
  public void testGetNumberOfBytesPerPage() throws Exception {
    SimpleString address = RandomUtil.randomSimpleString();
    session.createQueue(address, address, true);

    AddressControl addressControl = createManagementControl(address);
    Assert.assertEquals(
        HornetQDefaultConfiguration.getDefaultJournalFileSize(),
        addressControl.getNumberOfBytesPerPage());

    session.close();
    server.stop();

    AddressSettings addressSettings = new AddressSettings();
    addressSettings.setPageSizeBytes(1024);

    server.getAddressSettingsRepository().addMatch(address.toString(), addressSettings);
    server.start();
    ServerLocator locator2 =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));
    addServerLocator(locator2);
    ClientSessionFactory sf2 = createSessionFactory(locator2);

    session = sf2.createSession(false, true, false);
    session.createQueue(address, address, true);
    Assert.assertEquals(1024, addressControl.getNumberOfBytesPerPage());
  }
Example #4
0
  @Override
  @Before
  public void setUp() throws Exception {
    super.setUp();

    configuration = createDefaultConfig();
    configuration.setSecurityEnabled(false);
    server = createServer(true, configuration);
    // start the server
    server.start();

    qs = new AddressSettings();
    qs.setLastValueQueue(true);
    server.getAddressSettingsRepository().addMatch(address.toString(), qs);
    // then we create a client as normal
    locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(UnitTestCase.INVM_CONNECTOR_FACTORY));

    locator.setBlockOnAcknowledge(true);
    locator.setAckBatchSize(0);
    ClientSessionFactory sessionFactory = createSessionFactory(locator);
    clientSession = sessionFactory.createSession(false, true, true);
    clientSessionXa = sessionFactory.createSession(true, false, false);
    clientSession.createQueue(address, qName1, null, true);
  }
Example #5
0
  public void testConsumerAckImmediateAutoCommitFalse() throws Exception {

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = sf.createSession(false, true, false, true);

    session.createQueue(QUEUE, QUEUE, null, false);

    ClientProducer producer = session.createProducer(QUEUE);

    final int numMessages = 100;

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = createTextMessage(session, "m" + i);
      producer.send(message);
    }

    ClientConsumer consumer = session.createConsumer(QUEUE);
    session.start();
    for (int i = 0; i < numMessages; i++) {
      ClientMessage message2 = consumer.receive(1000);

      Assert.assertEquals("m" + i, message2.getBodyBuffer().readString());
    }
    // assert that all the messages are there and none have been acked
    Assert.assertEquals(
        0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getDeliveringCount());
    Assert.assertEquals(
        0, ((Queue) server.getPostOffice().getBinding(QUEUE).getBindable()).getMessageCount());

    session.close();
  }
Example #6
0
 protected void removeAllMessages(final String queueName, final int index) throws Exception {
   ManagementService managementService = server0.getManagementService();
   if (index == 1) {
     managementService = server1.getManagementService();
   }
   JMSQueueControl queueControl =
       (JMSQueueControl) managementService.getResource(ResourceNames.JMS_QUEUE + queueName);
   queueControl.removeMessages(null);
 }
  @Test
  public void testLargeMessageCompression2() throws Exception {
    final int messageSize = (int) (3.5 * HornetQClient.DEFAULT_MIN_LARGE_MESSAGE_SIZE);

    HornetQServer server = createServer(true, isNetty());

    server.start();

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = addClientSession(sf.createSession(false, false, false));

    session.createTemporaryQueue(ADDRESS, ADDRESS);

    ClientProducer producer = session.createProducer(ADDRESS);

    Message clientFile = createLargeClientMessageStreaming(session, messageSize, true);

    producer.send(clientFile);

    session.commit();

    session.start();

    ClientConsumer consumer = session.createConsumer(ADDRESS);
    ClientMessage msg1 = consumer.receive(1000);
    Assert.assertNotNull(msg1);

    String testDir = getTestDir();
    File testFile = new File(testDir, "async_large_message");
    FileOutputStream output = new FileOutputStream(testFile);

    msg1.setOutputStream(output);

    msg1.waitOutputStreamCompletion(0);

    msg1.acknowledge();

    output.close();

    session.commit();

    consumer.close();

    session.close();

    // verify
    FileInputStream input = new FileInputStream(testFile);
    for (int i = 0; i < messageSize; i++) {
      byte b = (byte) input.read();
      assertEquals("position = " + i, getSamplebyte(i), b);
    }
    input.close();
    testFile.delete();
    validateNoFilesOnLargeDir();
  }
Example #8
0
 protected void checkNoSubscriptions(final Topic topic, final int index) throws Exception {
   ManagementService managementService = server0.getManagementService();
   if (index == 1) {
     managementService = server1.getManagementService();
   }
   TopicControl topicControl =
       (TopicControl)
           managementService.getResource(ResourceNames.JMS_TOPIC + topic.getTopicName());
   Assert.assertEquals(0, topicControl.getSubscriptionCount());
 }
 private AddressControl getAddressControl(
     final OperationContext context, final ModelNode operation) {
   final String addressName =
       PathAddress.pathAddress(operation.require(OP_ADDR)).getLastElement().getValue();
   final ServiceName hqServiceName =
       MessagingServices.getHornetQServiceName(
           PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)));
   ServiceController<?> hqService = context.getServiceRegistry(false).getService(hqServiceName);
   HornetQServer hqServer = HornetQServer.class.cast(hqService.getValue());
   return AddressControl.class.cast(
       hqServer.getManagementService().getResource(ResourceNames.CORE_ADDRESS + addressName));
 }
  @Override
  public void setUp() throws Exception {
    super.setUp();
    Configuration config = createDefaultConfig();

    HashMap<String, AddressSettings> settings = new HashMap<String, AddressSettings>();

    messagingService = createServer(true, config, 10024, 200024, settings);
    messagingService.start();

    pagedServerQueue =
        (QueueImpl) messagingService.createQueue(ADDRESS, ADDRESS, null, true, false);
  }
 private HornetQServer createServer(int node, int remoteNode, BackupStrategy backupStrategy)
     throws Exception {
   TransportConfiguration liveConnector =
       getConnectorTransportConfiguration("liveConnector" + node, node);
   TransportConfiguration remoteConnector =
       getConnectorTransportConfiguration("remoteConnector" + node, remoteNode);
   TransportConfiguration liveAcceptor = getAcceptorTransportConfiguration(node);
   Configuration liveConfiguration =
       getConfiguration(
           "server" + node, backupStrategy, liveConnector, liveAcceptor, remoteConnector);
   HornetQServer server = new HornetQServerImpl(liveConfiguration);
   server.setIdentity("server" + node);
   return server;
 }
Example #12
0
  /**
   * This would force a journal duplication on bindings even with the scenario that generated fixed,
   * the server shouldn't hold of from starting
   *
   * @throws Exception
   */
  @Test
  public void testForceDuplicationOnBindings() throws Exception {
    queue = server.createQueue(QUEUE, QUEUE, null, true, false);

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

    ClientProducer producer = session.createProducer(QUEUE);

    producer.send(session.createMessage(true));
    session.commit();

    long queueID = server.getStorageManager().generateUniqueID();
    long txID = server.getStorageManager().generateUniqueID();

    // Forcing a situation where the server would unexpectedly create a duplicated queue. The server
    // should still start normally
    LocalQueueBinding newBinding =
        new LocalQueueBinding(
            QUEUE,
            new QueueImpl(queueID, QUEUE, QUEUE, null, true, false, null, null, null, null, null),
            server.getNodeID());
    server.getStorageManager().addQueueBinding(txID, newBinding);
    server.getStorageManager().commitBindings(txID);

    server.stop();

    // a duplicate binding would impede the server from starting
    server.start();
    waitForServer(server);

    server.stop();
  }
Example #13
0
  /** @throws Exception */
  protected void initServer() throws Exception {
    configuration = createDefaultConfig();
    configuration.setSecurityEnabled(false);
    configuration.setJournalMinFiles(2);
    server = createServer(true, configuration);
    server.start();

    AddressSettings qs = server.getAddressSettingsRepository().getMatch("*");
    AddressSettings newSets = new AddressSettings();
    newSets.setRedeliveryDelay(DelayedMessageTest.DELAY);
    newSets.merge(qs);
    server.getAddressSettingsRepository().addMatch(qName, newSets);
    locator = createInVMNonHALocator();
  }
  public void testConnection(
      final String acceptorHost, final String connectorHost, final boolean mustConnect)
      throws Exception {
    System.out.println(
        "acceptor="
            + acceptorHost
            + ", connector="
            + connectorHost
            + ", mustConnect="
            + mustConnect);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put(getHostPropertyKey(), acceptorHost);
    TransportConfiguration acceptorConfig =
        new TransportConfiguration(getAcceptorFactoryClassName(), params);
    Set<TransportConfiguration> transportConfigs = new HashSet<TransportConfiguration>();
    transportConfigs.add(acceptorConfig);

    Configuration config = createDefaultConfig(true);
    config.setAcceptorConfigurations(transportConfigs);
    HornetQServer messagingService = createServer(false, config);
    messagingService.start();

    params = new HashMap<String, Object>();
    params.put(getHostPropertyKey(), connectorHost);
    TransportConfiguration connectorConfig =
        new TransportConfiguration(getConnectorFactoryClassName(), params);

    try {
      ClientSessionFactory sf = HornetQClient.createClientSessionFactory(connectorConfig);

      if (mustConnect) {
        ClientSession session = sf.createSession(false, true, true);
        session.close();
        System.out.println("connection OK");
      } else {
        try {
          sf.createSession(false, true, true);
          Assert.fail(
              "session creation must fail because connector must not be able to connect to the server bound to another network interface");
        } catch (Exception e) {
        }
      }
    } finally {
      if (messagingService != null) {
        messagingService.stop();
      }
    }
  }
Example #15
0
  public static ServerManager initializeServer() throws Exception {
    FileConfiguration configuration = null;
    SecurityManager security = null;

    // configuration start
    configuration = new FileConfiguration();
    configuration.setSecurityEnabled(true);
    configuration.setPersistenceEnabled(true);
    configuration.setJournalType(JournalType.NIO);
    configuration.setClusterUser("clusterAdmin");
    configuration.setClusterPassword("H0rnN4tGoo");
    configuration.setConfigurationUrl("hornetq-configuration.xml");

    // load user set properties from file
    Properties properties = loadProperties();

    // set acceptor based on config file
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("protocol", "stomp");
    parameters.put("host", properties.getProperty("server.address"));
    parameters.put("port", properties.getProperty("server.port"));
    parameters.put("use-nio", "true");
    TransportConfiguration tpConf =
        new TransportConfiguration(
            NettyAcceptorFactory.class.getName(), parameters, "stomp-acceptor");
    configuration.getAcceptorConfigurations().add(tpConf);

    configuration.start();

    // Initialize dbconnection
    dbConnect =
        new DbConnect(
            properties.getProperty("database.address"),
            properties.getProperty("database.name"),
            properties.getProperty("database.username"),
            properties.getProperty("database.password"));

    // Create securitymanager
    security = new SecurityManager(dbConnect);

    // we create the HornetQ server using this config
    HornetQServer hornetqServer = HornetQServers.newHornetQServer(configuration, null, security);

    hornetqServer.start();

    ServerManager serverManager = new ServerManagerImpl(hornetqServer, dbConnect, properties);
    return serverManager;
  }
Example #16
0
  @Test
  public void testNoActions() throws Exception {

    setupServer(true);
    StorageManager storage = getStorage();
    manager = liveServer.getReplicationManager();
    waitForComponent(manager);

    Journal replicatedJournal = new ReplicatedJournal((byte) 1, new FakeJournal(), manager);

    replicatedJournal.appendPrepareRecord(1, new FakeData(), false);

    final CountDownLatch latch = new CountDownLatch(1);
    storage.afterCompleteOperations(
        new IOAsyncTask() {

          public void onError(final int errorCode, final String errorMessage) {}

          public void done() {
            latch.countDown();
          }
        });

    Assert.assertTrue(latch.await(1, TimeUnit.SECONDS));

    Assert.assertEquals(
        "should be empty " + manager.getActiveTokens(), 0, manager.getActiveTokens().size());
  }
Example #17
0
 @Override
 protected void performRuntime(
     final OperationContext context,
     final ModelNode operation,
     final ModelNode model,
     final ServiceVerificationHandler verificationHandler,
     final List<ServiceController<?>> newControllers)
     throws OperationFailedException {
   final HornetQServer server = getHornetQServer(context, operation);
   if (server != null) {
     final PathAddress address =
         PathAddress.pathAddress(operation.require(ModelDescriptionConstants.OP_ADDR));
     final AddressSettings settings = createSettings(context, model);
     server.getAddressSettingsRepository().addMatch(address.getLastElement().getValue(), settings);
   }
 }
Example #18
0
  public boolean checkEmpty(final Queue queue, final int index) throws Exception {
    ManagementService managementService = server0.getManagementService();
    if (index == 1) {
      managementService = server1.getManagementService();
    }
    JMSQueueControl queueControl =
        (JMSQueueControl)
            managementService.getResource(ResourceNames.JMS_QUEUE + queue.getQueueName());

    Long messageCount = queueControl.getMessageCount();

    if (messageCount > 0) {
      queueControl.removeMessages(null);
    }
    return true;
  }
Example #19
0
  private synchronized void doClose(final boolean failed) throws Exception {
    if (tx != null && tx.getXid() == null) {
      // We only rollback local txs on close, not XA tx branches

      try {
        rollback(failed, false);
      } catch (Exception e) {
        HornetQLogger.LOGGER.warn(e.getMessage(), e);
      }
    }

    Set<ServerConsumer> consumersClone = new HashSet<ServerConsumer>(consumers.values());

    for (ServerConsumer consumer : consumersClone) {
      consumer.close(failed);
    }

    consumers.clear();

    server.removeSession(name);

    if (currentLargeMessage != null) {
      try {
        currentLargeMessage.deleteFile();
      } catch (Throwable error) {
        HornetQLogger.LOGGER.errorDeletingLargeMessageFile(error);
      }
    }

    remotingConnection.removeFailureListener(this);

    callback.closed();
  }
Example #20
0
  @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]);
  }
Example #21
0
  public void createQueue(
      final SimpleString address,
      final SimpleString name,
      final SimpleString filterString,
      final boolean temporary,
      final boolean durable)
      throws Exception {
    if (durable) {
      // make sure the user has privileges to create this queue
      securityStore.check(address, CheckType.CREATE_DURABLE_QUEUE, this);
    } else {
      securityStore.check(address, CheckType.CREATE_NON_DURABLE_QUEUE, this);
    }

    Queue queue = server.createQueue(address, name, filterString, durable, temporary);

    if (temporary) {
      // Temporary queue in core simply means the queue will be deleted if
      // the remoting connection
      // dies. It does not mean it will get deleted automatically when the
      // session is closed.
      // It is up to the user to delete the queue when finished with it

      TempQueueCleanerUpper cleaner = new TempQueueCleanerUpper(postOffice, name, queue);

      remotingConnection.addCloseListener(cleaner);
      remotingConnection.addFailureListener(cleaner);

      tempQueueCleannerUppers.put(name, cleaner);
    }
  }
Example #22
0
 public void flushExecutor() {
   FutureLatch future = new FutureLatch();
   executor.execute(future);
   if (!future.await(10000)) {
     server.threadDump("Couldn't finish executor on " + this);
   }
 }
Example #23
0
  public synchronized void informClusterOfBackup() {
    String nodeID = server.getNodeID().toString();

    TopologyMemberImpl localMember = new TopologyMemberImpl(nodeID, null, null, connector);

    topology.updateAsLive(nodeID, localMember);
  }
 public void testProducerWithSmallWindowSizeAndLargeMessage() throws Exception {
   final CountDownLatch latch = new CountDownLatch(1);
   server
       .getRemotingService()
       .addInterceptor(
           new Interceptor() {
             public boolean intercept(final Packet packet, final RemotingConnection connection)
                 throws HornetQException {
               if (packet.getType() == PacketImpl.SESS_SEND) {
                 latch.countDown();
               }
               return true;
             }
           });
   ServerLocator locator = createInVMNonHALocator();
   locator.setConfirmationWindowSize(100);
   ClientSessionFactory cf = locator.createSessionFactory();
   ClientSession session = cf.createSession(false, true, true);
   ClientProducer producer = session.createProducer(QUEUE);
   ClientMessage message = session.createMessage(true);
   byte[] body = new byte[1000];
   message.getBodyBuffer().writeBytes(body);
   producer.send(message);
   Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
   session.close();
   locator.close();
 }
Example #25
0
  public void testNotifications() throws Exception {
    SimpleNotificationService.Listener notifListener = new SimpleNotificationService.Listener();
    BridgeControl bridgeControl = createBridgeControl(bridgeConfig.getName(), mbeanServer);

    server_0.getManagementService().addNotificationListener(notifListener);

    Assert.assertEquals(0, notifListener.getNotifications().size());

    bridgeControl.stop();

    Assert.assertEquals(1, notifListener.getNotifications().size());
    Notification notif = notifListener.getNotifications().get(0);
    Assert.assertEquals(NotificationType.BRIDGE_STOPPED, notif.getType());
    Assert.assertEquals(
        bridgeControl.getName(),
        notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString());

    bridgeControl.start();

    Assert.assertEquals(2, notifListener.getNotifications().size());
    notif = notifListener.getNotifications().get(1);
    Assert.assertEquals(NotificationType.BRIDGE_STARTED, notif.getType());
    Assert.assertEquals(
        bridgeControl.getName(),
        notif.getProperties().getSimpleStringProperty(new SimpleString("name")).toString());
  }
Example #26
0
  private void waitForReplication(int count) throws InterruptedException {
    if (liveServer == null) return;

    while (liveServer.getReplicationManager() == null && count < 10) {
      Thread.sleep(50);
      count++;
    }
  }
Example #27
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    server = createServer(false);
    server.start();
    locator = createInVMNonHALocator();
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    server = createServer(false);

    server.start();
  }
Example #29
0
 @Override
 public void setUp() throws Exception {
   super.setUp();
   server = createServer(true);
   server.start();
   locator = createInVMNonHALocator();
   sf = createSessionFactory(locator);
 }
  /** @throws Exception */
  protected void stopServer() throws Exception {
    serverManager.stop();

    server.stop();

    serverManager = null;

    server = null;
  }