Beispiel #1
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]);
  }
Beispiel #2
0
    @Override
    public void run() {
      locator.setReconnectAttempts(0);

      final ClientSessionFactory sessionFactory;
      ClientSession session;
      try {
        sessionFactory = locator.createSessionFactory(tc);
        if (sessionFactory != null) {
          session = sessionFactory.createSession();
          if (session != null) {
            if (nodeIsDown(total, count.incrementAndGet())) {
              while (latch.getCount() > 0) latch.countDown();
            }
            session.close();
            sessionFactory.close();
          }
        }
      } catch (Exception e) {
        // no-op
      } finally {
        latch.countDown();
        locator.close();
      }
    }
      @Override
      public void run() {
        ClientSession session = null;
        latchReady.countDown();
        try {
          UnitTestCase.waitForLatch(latchStart);
          session = sf.createSession(true, true);
          session.start();
          ClientConsumer cons = session.createConsumer(CompactingStressTest.Q2);
          for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) {
            ClientMessage msg = cons.receive(60 * 1000);
            msg.acknowledge();
          }

          Assert.assertNull(cons.receiveImmediate());
        } catch (Throwable e) {
          this.e = e;
        } finally {
          try {
            session.close();
          } catch (Throwable e) {
            this.e = e;
          }
        }
      }
  public void testNoReceiveWithListener() throws Exception {
    ClientSessionFactory sf = createSessionFactory(locator);

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

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

    ClientConsumer consumer = session.createConsumer(QUEUE);

    consumer.setMessageHandler(
        new MessageHandler() {
          public void onMessage(final ClientMessage msg) {}
        });

    try {
      consumer.receiveImmediate();
      Assert.fail("Should throw exception");
    } catch (HornetQIllegalStateException ise) {
      // ok
    } catch (HornetQException me) {
      Assert.fail("Wrong exception code");
    }

    session.close();
  }
Beispiel #5
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();
  }
  private void drainQueue() throws Exception {
    PerfBase.log.info("Draining queue");

    ClientSession session = null;

    try {
      session = factory.createSession();

      ClientConsumer consumer = session.createConsumer(perfParams.getQueueName());

      session.start();

      ClientMessage message = null;

      int count = 0;
      do {
        message = consumer.receive(3000);

        if (message != null) {
          message.acknowledge();

          count++;
        }
      } while (message != null);

      PerfBase.log.info("Drained " + count + " messages");
    } finally {
      if (session != null) {
        session.close();
      }
    }
  }
  @Test
  public void testXACommit() throws Exception {
    HornetQResourceAdapter qResourceAdapter = newResourceAdapter();
    MyBootstrapContext ctx = new MyBootstrapContext();
    qResourceAdapter.start(ctx);
    HornetQActivationSpec spec = new HornetQActivationSpec();
    spec.setResourceAdapter(qResourceAdapter);
    spec.setUseJNDI(false);
    spec.setDestinationType("javax.jms.Queue");
    spec.setDestination(MDBQUEUE);
    qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
    CountDownLatch latch = new CountDownLatch(1);
    XADummyEndpoint endpoint = new XADummyEndpoint(latch);
    DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, true);
    qResourceAdapter.endpointActivation(endpointFactory, spec);
    ClientSession session = locator.createSessionFactory().createSession();
    ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
    ClientMessage message = session.createMessage(true);
    message.getBodyBuffer().writeString("teststring");
    clientProducer.send(message);
    session.close();
    latch.await(5, TimeUnit.SECONDS);

    assertNotNull(endpoint.lastMessage);
    assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "teststring");
    endpoint.prepare();
    endpoint.commit();
    qResourceAdapter.endpointDeactivation(endpointFactory, spec);
    qResourceAdapter.stop();
  }
  @Test
  public void testSimpleMessageReceivedOnQueueManyMessages() throws Exception {
    HornetQResourceAdapter qResourceAdapter = newResourceAdapter();
    MyBootstrapContext ctx = new MyBootstrapContext();
    qResourceAdapter.start(ctx);
    HornetQActivationSpec spec = new HornetQActivationSpec();
    spec.setResourceAdapter(qResourceAdapter);
    spec.setUseJNDI(false);
    spec.setDestinationType("javax.jms.Queue");
    spec.setDestination(MDBQUEUE);
    qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
    CountDownLatch latch = new CountDownLatch(15);
    MultipleEndpoints endpoint = new MultipleEndpoints(latch, false);
    DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
    qResourceAdapter.endpointActivation(endpointFactory, spec);
    ClientSession session = locator.createSessionFactory().createSession();
    ClientProducer clientProducer = session.createProducer(MDBQUEUEPREFIXED);
    for (int i = 0; i < 15; i++) {
      ClientMessage message = session.createMessage(true);
      message.getBodyBuffer().writeString("teststring" + i);
      clientProducer.send(message);
    }
    session.close();
    latch.await(5, TimeUnit.SECONDS);

    qResourceAdapter.endpointDeactivation(endpointFactory, spec);

    qResourceAdapter.stop();
  }
Beispiel #9
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();
  }
  private void receiveMessages() throws Exception {
    ClientSession session = sf.createSession(true, true);
    session.start();
    ClientConsumer consumer = session.createConsumer(ADDRESS);
    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = consumer.receive(100);
      assertNotNull("Expecting a message " + i, message);
      assertMessageBody(i, message);
      assertEquals(i, message.getIntProperty("int").intValue());
      assertEquals((short) i, message.getShortProperty("short").shortValue());
      assertEquals((byte) i, message.getByteProperty("byte").byteValue());
      assertEquals(floatValue(i), message.getFloatProperty("float").floatValue(), 0.001);
      assertEquals(
          new SimpleString(Integer.toString(i)),
          message.getSimpleStringProperty(SIMPLE_STRING_KEY.toString()));
      assertEqualsByteArrays(byteArray(i), message.getBytesProperty("byte[]"));

      assertTrue(message.containsProperty("null-value"));
      assertEquals(message.getObjectProperty("null-value"), null);

      message.acknowledge();
    }
    assertNull("no more messages", consumer.receive(50));
    consumer.close();
    session.commit();
  }
Beispiel #11
0
  public void testRestartJournal() throws Throwable {
    runExternalProcess(0, JournalCrashTest.FIRST_RUN);
    runExternalProcess(JournalCrashTest.FIRST_RUN, JournalCrashTest.SECOND_RUN);
    runExternalProcess(JournalCrashTest.SECOND_RUN, JournalCrashTest.THIRD_RUN);
    runExternalProcess(JournalCrashTest.THIRD_RUN, JournalCrashTest.FOURTH_RUN);

    printJournal();

    ClientSession session = null;
    try {
      startServer();

      session = factory.createSession(true, true);
      ClientConsumer consumer = session.createConsumer(QUEUE);
      session.start();

      for (int i = 0; i < JournalCrashTest.FOURTH_RUN; i++) {
        ClientMessage msg = consumer.receive(5000);

        Assert.assertNotNull("Msg at " + i, msg);

        msg.acknowledge();

        Assert.assertEquals(i, msg.getObjectProperty(new SimpleString("key")));
      }
      session.close();
    } finally {
      try {
        session.close();
      } catch (Throwable ignored) {
      }
    }
  }
Beispiel #12
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());
  }
Beispiel #13
0
  /**
   * Setup the activation
   *
   * @throws Exception Thrown if an error occurs
   */
  protected synchronized void setup() throws Exception {
    HornetQRALogger.LOGGER.debug("Setting up " + spec);

    setupCF();

    setupDestination();
    for (int i = 0; i < spec.getMaxSession(); i++) {
      ClientSession session = null;

      try {
        ClientSessionFactory cf = factory.getServerLocator().createSessionFactory();
        session = setupSession(cf);
        HornetQMessageHandler handler =
            new HornetQMessageHandler(this, ra.getTM(), (ClientSessionInternal) session, cf, i);
        handler.setup();
        session.start();
        handlers.add(handler);
      } catch (Exception e) {
        if (session != null) {
          session.close();
        }

        throw e;
      }
    }

    resourceRecovery =
        ra.getRecoveryManager().register(factory, spec.getUser(), spec.getPassword());

    HornetQRALogger.LOGGER.debug("Setup complete " + this);
  }
 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();
 }
  public void testSSL() throws Exception {
    String text = RandomUtil.randomString();

    tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
    tc.getParams()
        .put(TransportConstants.KEYSTORE_PATH_PROP_NAME, TransportConstants.DEFAULT_KEYSTORE_PATH);
    tc.getParams()
        .put(
            TransportConstants.KEYSTORE_PASSWORD_PROP_NAME,
            TransportConstants.DEFAULT_KEYSTORE_PASSWORD);

    ServerLocator locator = addServerLocator(HornetQClient.createServerLocatorWithoutHA(tc));
    ClientSessionFactory sf = createSessionFactory(locator);
    ClientSession session = sf.createSession(false, true, true);
    session.createQueue(CoreClientOverSSLTest.QUEUE, CoreClientOverSSLTest.QUEUE, false);
    ClientProducer producer = session.createProducer(CoreClientOverSSLTest.QUEUE);

    ClientMessage message = createTextMessage(session, text);
    producer.send(message);

    ClientConsumer consumer = session.createConsumer(CoreClientOverSSLTest.QUEUE);
    session.start();

    Message m = consumer.receive(1000);
    Assert.assertNotNull(m);
    Assert.assertEquals(text, m.getBodyBuffer().readString());
  }
Beispiel #16
0
  @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 testFailure() throws Exception {
    try {
      String testName = "testFailure";
      startup();
      deployTopic(testName);

      ClientRequest request = new ClientRequest(generateURL("/topics/" + testName));

      ClientResponse<?> response = request.head();
      response.releaseConnection();
      Assert.assertEquals(200, response.getStatus());
      Link sender =
          MessageTestBase.getLinkByTitle(
              manager.getQueueManager().getLinkStrategy(), response, "create");
      System.out.println("create: " + sender);
      Link pushSubscriptions =
          MessageTestBase.getLinkByTitle(
              manager.getQueueManager().getLinkStrategy(), response, "push-subscriptions");
      System.out.println("push subscriptions: " + pushSubscriptions);

      PushTopicRegistration reg = new PushTopicRegistration();
      reg.setDurable(true);
      XmlLink target = new XmlLink();
      target.setHref("http://localhost:3333/error");
      target.setRelationship("uri");
      reg.setTarget(target);
      reg.setDisableOnFailure(true);
      reg.setMaxRetries(3);
      reg.setRetryWaitMillis(10);
      response = pushSubscriptions.request().body("application/xml", reg).post();
      Assert.assertEquals(201, response.getStatus());
      Link pushSubscription = response.getLocationLink();
      response.releaseConnection();

      ClientResponse<?> res = sender.request().body("text/plain", Integer.toString(1)).post();
      res.releaseConnection();
      Assert.assertEquals(201, res.getStatus());

      Thread.sleep(5000);

      response = pushSubscription.request().get();
      PushTopicRegistration reg2 = response.getEntity(PushTopicRegistration.class);
      response.releaseConnection();
      Assert.assertEquals(reg.isDurable(), reg2.isDurable());
      Assert.assertEquals(reg.getTarget().getHref(), reg2.getTarget().getHref());
      Assert.assertFalse(reg2.isEnabled());
      response.releaseConnection();

      String destination = reg2.getDestination();
      ClientSession session =
          manager.getQueueManager().getSessionFactory().createSession(false, false, false);
      ClientSession.QueueQuery query = session.queueQuery(new SimpleString(destination));
      Assert.assertFalse(query.isExists());

      manager.getQueueManager().getPushStore().removeAll();
    } finally {
      shutdown();
    }
  }
Beispiel #18
0
  /**
   * Connects to the yamcs server. This method blocks until a connection is established or some
   * error has occurred, thus this should be called in a separate thread. Hornetq will try
   * indefinitely to establish the connection and also provides automatic re-connection afterwards.
   *
   * @throws Exception if the hornetq session could not be established due to some error
   */
  public void connect() throws Exception {
    for (ConnectionListener cl : connectionListeners) {
      cl.connecting(connParams.getUrl());
    }

    Map<String, Object> tcpConfig = new HashMap<String, Object>();
    tcpConfig.put(TransportConstants.HOST_PROP_NAME, connParams.host);
    tcpConfig.put(TransportConstants.PORT_PROP_NAME, connParams.port);

    locator =
        HornetQClient.createServerLocatorWithoutHA(
            new TransportConfiguration(NettyConnectorFactory.class.getName(), tcpConfig));

    locator.setInitialConnectAttempts(initialConnectAttempts);
    locator.setReconnectAttempts(reconnectAttempts);
    locator.setRetryInterval(retryInterval);
    locator.setRetryIntervalMultiplier(retryIntervalMultiplier);
    locator.setMaxRetryInterval(maxRetryInterval);
    locator.setAckBatchSize(ackBatchSize);

    sessionFactory = locator.createSessionFactory();

    // TODO Use hornetq auth (like YamcsConnector), or keep anonymous connection?
    session = sessionFactory.createSession(false, true, true, preAcknowledge);
    session.addFailureListener(YamcsAckConnector.this);
    session.start();

    for (ConnectionListener cl : connectionListeners) {
      cl.connected(connParams.getUrl());
    }
  }
    @Override
    public void run() {
      try {
        if (shareConnectionFactory) {
          session = sharedSf.createSession(false, false);
        } else {
          locator = createInVMNonHALocator();
          sf = createSessionFactory(locator);
          session = sf.createSession(false, false);
        }

        ClientProducer prod = session.createProducer(MultipleConsumersPageStressTest.ADDRESS);

        int count = 0;

        while (enabled()) {
          int numberOfMessages = getNumberOfMessages();

          for (int i = 0; i < numberOfMessages; i++) {
            ClientMessage msg = session.createMessage(true);
            msg.putStringProperty("Test", "This is a simple test");
            msg.putIntProperty("count", count++);
            prod.send(msg);
          }

          messagesAvailable.addAndGet(numberOfMessages);
          session.commit();
        }
      } catch (Throwable e) {
        exceptionHappened(e);
      }
    }
 @Override
 public void close() {
   try {
     session.rollback();
     session.close();
   } catch (Exception ignored) {
   }
 }
 public MessageProducer(String addressName, ClientSessionFactory factory) {
   this.addressName = addressName;
   try {
     producerSession = factory.createSession(true, true);
     producer = producerSession.createProducer(addressName);
     producerSession.start();
   } catch (HornetQException ex) {
     Logger.getLogger(MessageProducer.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
  @Test
  public void testDurableSubscription() throws Exception {
    HornetQResourceAdapter qResourceAdapter = newResourceAdapter();
    MyBootstrapContext ctx = new MyBootstrapContext();
    qResourceAdapter.start(ctx);
    HornetQActivationSpec spec = new HornetQActivationSpec();
    spec.setResourceAdapter(qResourceAdapter);
    spec.setUseJNDI(false);
    spec.setDestinationType("javax.jms.Topic");
    spec.setDestination("mdbTopic");
    spec.setSubscriptionDurability("Durable");
    spec.setSubscriptionName("durable-mdb");
    spec.setClientID("id-1");
    qResourceAdapter.setConnectorClassName(INVM_CONNECTOR_FACTORY);
    CountDownLatch latch = new CountDownLatch(1);
    DummyMessageEndpoint endpoint = new DummyMessageEndpoint(latch);
    DummyMessageEndpointFactory endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
    qResourceAdapter.endpointActivation(endpointFactory, spec);
    ClientSession session = locator.createSessionFactory().createSession();
    ClientProducer clientProducer = session.createProducer("jms.topic.mdbTopic");
    ClientMessage message = session.createMessage(true);
    message.getBodyBuffer().writeString("1");
    clientProducer.send(message);

    latch.await(5, TimeUnit.SECONDS);

    assertNotNull(endpoint.lastMessage);
    assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "1");

    qResourceAdapter.endpointDeactivation(endpointFactory, spec);

    message = session.createMessage(true);
    message.getBodyBuffer().writeString("2");
    clientProducer.send(message);

    latch = new CountDownLatch(1);
    endpoint = new DummyMessageEndpoint(latch);
    endpointFactory = new DummyMessageEndpointFactory(endpoint, false);
    qResourceAdapter.endpointActivation(endpointFactory, spec);
    latch.await(5, TimeUnit.SECONDS);

    assertNotNull(endpoint.lastMessage);
    assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "2");
    latch = new CountDownLatch(1);
    endpoint.reset(latch);
    message = session.createMessage(true);
    message.getBodyBuffer().writeString("3");
    clientProducer.send(message);
    latch.await(5, TimeUnit.SECONDS);

    assertNotNull(endpoint.lastMessage);
    assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "3");
    qResourceAdapter.endpointDeactivation(endpointFactory, spec);
    qResourceAdapter.stop();
  }
  /**
   * Basic fail-back test.
   *
   * @throws Exception
   */
  @Test
  public void testFailBack() throws Exception {
    createSessionFactory();
    ClientSession session = sendAndConsume(sf, true);

    ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);

    sendMessages(session, producer, NUM_MESSAGES);
    session.commit();

    crash(session);

    session.start();
    ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS);
    receiveMessages(consumer, 0, NUM_MESSAGES, true);
    producer = session.createProducer(FailoverTestBase.ADDRESS);
    sendMessages(session, producer, 2 * NUM_MESSAGES);
    session.commit();
    assertFalse("must NOT be a backup", liveServer.getServer().getConfiguration().isBackup());
    adaptLiveConfigForReplicatedFailBack(liveServer.getServer().getConfiguration());

    CountDownSessionFailureListener listener = new CountDownSessionFailureListener();
    session.addFailureListener(listener);

    liveServer.start();

    assertTrue(listener.getLatch().await(5, TimeUnit.SECONDS));
    assertTrue(
        "live initialized after restart",
        liveServer.getServer().waitForActivation(15, TimeUnit.SECONDS));

    session.start();
    receiveMessages(consumer, 0, NUM_MESSAGES, true);
  }
  @Test
  public void testAutoFailbackThenFailover() throws Exception {
    createSessionFactory();
    ClientSession session = sendAndConsume(sf, true);

    CountDownSessionFailureListener listener = new CountDownSessionFailureListener();

    session.addFailureListener(listener);

    liveServer.crash(session);

    ClientProducer producer = session.createProducer(FailoverTestBase.ADDRESS);

    ClientMessage message = session.createMessage(true);

    setBody(0, message);

    producer.send(message);

    session.removeFailureListener(listener);

    listener = new CountDownSessionFailureListener();

    session.addFailureListener(listener);

    log.info("restarting live node now");
    liveServer.start();

    assertTrue("expected a session failure", listener.getLatch().await(5, TimeUnit.SECONDS));

    message = session.createMessage(true);

    setBody(1, message);

    producer.send(message);

    session.removeFailureListener(listener);

    listener = new CountDownSessionFailureListener();

    session.addFailureListener(listener);

    waitForBackup(sf, 10);

    liveServer.crash();

    assertTrue("expected a session failure", listener.getLatch().await(5, TimeUnit.SECONDS));

    session.close();

    wrapUpSessionFactory();
  }
Beispiel #25
0
  @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);
  }
  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();
      }
    }
  }
 @Before
 public void init() throws Exception {
   this.factory = new EventFactory(mockPrincipalProvider);
   this.principal = TestUtil.createOwnerPrincipal();
   eventFilter = new EventFilter(new CandlepinCommonTestConfig());
   when(mockPrincipalProvider.get()).thenReturn(this.principal);
   when(mockSessionFactory.createTransactedSession()).thenReturn(mockClientSession);
   when(mockClientSession.createProducer(anyString())).thenReturn(mockClientProducer);
   when(mockClientSession.createMessage(anyBoolean())).thenReturn(mockClientMessage);
   when(mockClientMessage.getBodyBuffer()).thenReturn(HornetQBuffers.fixedBuffer(2000));
   when(mockSessionFactory.getServerLocator()).thenReturn(mockLocator);
   this.mapper = spy(new ObjectMapper());
   this.eventSinkImpl = createEventSink(mockSessionFactory);
   o = new Owner("test owner");
 }
Beispiel #28
0
  // https://jira.jboss.org/jira/browse/HORNETQ-111
  // Test that, on rollback credits are released for messages cleared in the buffer
  public void testConsumerCreditsOnRollbackLargeMessages() throws Exception {

    locator.setConsumerWindowSize(10000);
    locator.setMinLargeMessageSize(1000);

    ClientSessionFactory sf = createSessionFactory(locator);

    ClientSession session = sf.createTransactedSession();

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

    ClientProducer producer = session.createProducer(QUEUE);

    final int numMessages = 100;

    final byte[] bytes = new byte[10000];

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = session.createMessage(false);

      message.getBodyBuffer().writeBytes(bytes);

      message.putIntProperty("count", i);

      producer.send(message);
    }

    session.commit();

    ClientConsumer consumer = session.createConsumer(QUEUE);
    session.start();

    for (int i = 0; i < 110; i++) {
      ClientMessage message = consumer.receive();

      int count = message.getIntProperty("count");

      boolean redelivered = message.getDeliveryCount() > 1;

      if (count % 2 == 0 && !redelivered) {
        session.rollback();
      } else {
        session.commit();
      }
    }

    session.close();
  }
Beispiel #29
0
 protected void callCommit() throws Exception {
   pendingCommit = true;
   session.commit(activeXid, false);
   pendingCommit = false;
   activeXid = null;
   onCommit();
 }
Beispiel #30
0
 private ClientMessage createDurableMessage(final ClientSession session, final String body) {
   ClientMessage message =
       session.createMessage(
           HornetQTextMessage.TYPE, true, 0, System.currentTimeMillis(), (byte) 1);
   message.getBodyBuffer().writeString(body);
   return message;
 }