@Test
  public void testSimpleMessageReceivedOnQueueWithSelector() 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);
    spec.setMessageSelector("color='red'");
    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(MDBQUEUEPREFIXED);
    ClientMessage message = session.createMessage(true);
    message.getBodyBuffer().writeString("blue");
    message.putStringProperty("color", "blue");
    clientProducer.send(message);
    message = session.createMessage(true);
    message.getBodyBuffer().writeString("red");
    message.putStringProperty("color", "red");
    clientProducer.send(message);
    session.close();
    latch.await(5, TimeUnit.SECONDS);

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

    qResourceAdapter.endpointDeactivation(endpointFactory, spec);
    qResourceAdapter.stop();
  }
  @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();
  }
Ejemplo n.º 3
0
  @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();
  }
  @Test
  public void testSessionClosedOnRemotingConnectionFailure() throws Exception {
    ClientSession session = addClientSession(sf.createSession());

    session.createQueue("fooaddress", "fooqueue");

    ClientProducer prod = session.createProducer("fooaddress");

    ClientConsumer cons = session.createConsumer("fooqueue");

    session.start();

    prod.send(session.createMessage(false));

    Assert.assertNotNull(cons.receive());

    // Now fail the underlying connection

    RemotingConnection connection = ((ClientSessionInternal) session).getConnection();

    connection.fail(new HornetQNotConnectedException());

    Assert.assertTrue(session.isClosed());

    Assert.assertTrue(prod.isClosed());

    Assert.assertTrue(cons.isClosed());

    // Now try and use the producer

    try {
      prod.send(session.createMessage(false));

      Assert.fail("Should throw exception");
    } catch (HornetQObjectClosedException oce) {
      // ok
    } catch (HornetQException e) {
      fail("Invalid Exception type:" + e.getType());
    }

    try {
      cons.receive();

      Assert.fail("Should throw exception");
    } catch (HornetQObjectClosedException oce) {
      // ok
    } catch (HornetQException e) {
      fail("Invalid Exception type:" + e.getType());
    }

    session.close();
  }
  @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();
  }
Ejemplo n.º 6
0
 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 sendMessage(Object object) throws HornetQException {
    ObjectOutputStream oos = null;
    try {

      ClientMessage clientMessage = producerSession.createMessage(true);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(baos);
      oos.writeObject(object);
      oos.flush();

      byte[] data = baos.toByteArray();

      clientMessage.getBodyBuffer().writeInt(data.length);
      clientMessage.getBodyBuffer().writeBytes(data);
      producer.send(clientMessage);

    } catch (IOException ex) {
      Logger.getLogger(MessageProducer.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        oos.close();
      } catch (IOException ex) {
        Logger.getLogger(MessageProducer.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Ejemplo n.º 8
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;
 }
Ejemplo n.º 9
0
  public void sendMessages(final int start, final int end) throws Exception {
    ClientSession session = null;
    try {

      session = factory.createSession(false, false);

      try {
        session.createQueue(QUEUE, QUEUE, true);
      } catch (Exception ignored) {
      }

      ClientProducer prod = session.createProducer(QUEUE);

      for (int i = start; i < end; i++) {
        ClientMessage msg = session.createMessage(true);
        msg.putIntProperty(new SimpleString("key"), i);
        msg.getBodyBuffer().writeUTF("message " + i);
        prod.send(msg);
      }

      session.commit();
      session.close();
      // server.stop(); -- this test was not supposed to stop the server, it should crash
    } finally {
      session.close();
    }
  }
    @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);
      }
    }
Ejemplo n.º 11
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();
  }
Ejemplo n.º 12
0
 private Object invokeSyncOperation(
     final String resourceName, final String operationName, final Object... parameters)
     throws Exception {
   ClientMessage message = clientSession.createMessage(false);
   ManagementHelper.putOperationInvocation(message, resourceName, operationName, parameters);
   ClientMessage reply;
   try {
     reply = requestor.request(message, 3000);
   } catch (Exception e) {
     throw new IllegalStateException(
         "Exception while invoking " + operationName + " on " + resourceName, e);
   }
   if (reply == null) {
     throw new IllegalStateException(
         "no reply received when invoking " + operationName + " on " + resourceName);
   }
   if (!ManagementHelper.hasOperationSucceeded(reply)) {
     throw new IllegalStateException(
         "operation failed when invoking "
             + operationName
             + " on "
             + resourceName
             + ": "
             + ManagementHelper.getResult(reply));
   }
   return ManagementHelper.getResult(reply);
 }
Ejemplo n.º 13
0
 protected ClientMessage createTextMessage(
     final String s, final boolean durable, final ClientSession clientSession) {
   ClientMessage message =
       clientSession.createMessage(
           HornetQTextMessage.TYPE, durable, 0, System.currentTimeMillis(), (byte) 4);
   message.getBodyBuffer().writeString(s);
   return message;
 }
 protected ClientMessage writeBodyToMessage(Object payload, ClientSession session)
     throws IOException {
   if (payload instanceof CharSequence) {
     ClientMessage msg = session.createMessage(Message.TEXT_TYPE, true);
     return writeBodyToMessage((CharSequence) payload, msg);
   } else if (payload instanceof byte[]) {
     ClientMessage msg = session.createMessage(Message.BYTES_TYPE, true);
     return writeBodyToMessage((byte[]) payload, msg);
   } else if (payload instanceof InputStream) {
     ClientMessage msg = session.createMessage(Message.BYTES_TYPE, true);
     return writeBodyToMessage((InputStream) payload, msg);
   } else if (payload instanceof Serializable) {
     ClientMessage msg = session.createMessage(Message.OBJECT_TYPE, true);
     return writeBodyToMessage((Serializable) payload, msg);
   } else {
     throw new IllegalArgumentException(
         "Must be CharSequence, byte[], InputStream or Serializable");
   }
 }
Ejemplo n.º 15
0
      @Override
      public void run() {
        ClientSession session = null;
        ClientSession sessionSlow = null;
        latchReady.countDown();
        try {
          UnitTestCase.waitForLatch(latchStart);
          session = sf.createSession(true, true);
          sessionSlow = sf.createSession(false, false);
          ClientProducer prod = session.createProducer(CompactingStressTest.AD2);
          ClientProducer slowProd = sessionSlow.createProducer(CompactingStressTest.AD1);
          for (int i = 0; i < NUMBER_OF_FAST_MESSAGES; i++) {
            if (i % SLOW_INTERVAL == 0) {
              if (numberOfMessages.incrementAndGet() % 5 == 0) {
                sessionSlow.commit();
              }
              slowProd.send(session.createMessage(true));
            }
            ClientMessage msg = session.createMessage(true);

            prod.send(msg);
          }
          sessionSlow.commit();
        } catch (Throwable e) {
          this.e = e;
        } finally {
          try {
            session.close();
          } catch (Throwable e) {
            this.e = e;
          }
          try {
            sessionSlow.close();
          } catch (Throwable e) {
            this.e = e;
          }
        }
      }
Ejemplo n.º 16
0
 @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");
 }
Ejemplo n.º 17
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();
  }
Ejemplo n.º 18
0
  // An exception during delivery shouldn't make the message disappear
  @Test
  public void testExceptionWhileDelivering() throws Exception {
    queue = server.createQueue(QUEUE, QUEUE, null, true, false);

    HangInterceptor hangInt = new HangInterceptor();
    try {
      locator.addInterceptor(hangInt);

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

      ClientProducer producer = session.createProducer(QUEUE);

      ClientConsumer consumer = session.createConsumer(QUEUE);

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

      hangInt.close();

      session.start();

      Assert.assertTrue(hangInt.reusableLatch.await(10, TimeUnit.SECONDS));

      hangInt.pendingException = new HornetQException();

      hangInt.open();

      session.close();

      session = factory.createSession(false, false);
      session.start();

      consumer = session.createConsumer(QUEUE);

      ClientMessage msg = consumer.receive(5000);
      Assert.assertNotNull(msg);
      msg.acknowledge();

      session.commit();
    } finally {
      hangInt.open();
    }
  }
  // https://issues.jboss.org/browse/JBPAPP-8017
  @Test
  public void testNonDurableSubscriptionDeleteAfterCrash() throws Exception {
    HornetQResourceAdapter qResourceAdapter = newResourceAdapter();
    qResourceAdapter.setTransactionManagerLocatorClass("");
    qResourceAdapter.setTransactionManagerLocatorMethod("");
    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");
    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");

    HornetQActivation activation = lookupActivation(qResourceAdapter);

    SimpleString tempQueueName = activation.getTopicTemporaryQueue();

    QueueQuery query = session.queueQuery(tempQueueName);
    assertTrue(query.isExists());

    // this should be enough to simulate the crash
    qResourceAdapter.getDefaultHornetQConnectionFactory().close();
    qResourceAdapter.stop();

    query = session.queueQuery(tempQueueName);

    assertFalse(query.isExists());
  }
Ejemplo n.º 20
0
  private void sendMessages() throws Exception {
    ClientSession session = sf.createSession(true, true);
    session.createQueue(ADDRESS, ADDRESS, null, true);
    ClientProducer producer = session.createProducer(ADDRESS);

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message = session.createMessage(true);
      setBody(i, message);
      message.putIntProperty("int", i);
      message.putShortProperty("short", (short) i);
      message.putByteProperty("byte", (byte) i);
      message.putFloatProperty("float", floatValue(i));
      message.putStringProperty(SIMPLE_STRING_KEY, new SimpleString(Integer.toString(i)));
      message.putBytesProperty("byte[]", byteArray(i));
      message.putObjectProperty("null-value", null);
      producer.send(message);
    }
    session.commit();
  }
Ejemplo n.º 21
0
  private ClientSession sendAndConsume(final ClientSessionFactory sf, final boolean createQueue)
      throws Exception {
    ClientSession session = sf.createSession(false, true, true);

    if (createQueue) {
      session.createQueue(FailoverTestBase.ADDRESS, FailoverTestBase.ADDRESS, null, true);
    }

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

    final int numMessages = 1000;

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message =
          session.createMessage(
              HornetQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1);
      message.putIntProperty(new SimpleString("count"), i);
      message.getBodyBuffer().writeString("aardvarks");
      producer.send(message);
    }

    ClientConsumer consumer = session.createConsumer(FailoverTestBase.ADDRESS);

    session.start();

    for (int i = 0; i < numMessages; i++) {
      ClientMessage message2 = consumer.receive();

      Assert.assertEquals("aardvarks", message2.getBodyBuffer().readString());

      Assert.assertEquals(i, message2.getObjectProperty(new SimpleString("count")));

      message2.acknowledge();
    }

    ClientMessage message3 = consumer.receiveImmediate();

    consumer.close();

    Assert.assertNull(message3);

    return session;
  }
Ejemplo n.º 22
0
  @Test
  public void testSendPacketsWithFailure() throws Exception {
    final int nMsg = 100;
    final int stop = 37;
    setupServer(true, TestInterceptor.class.getName());

    manager = liveServer.getReplicationManager();
    waitForComponent(manager);
    ClientSessionFactory sf = createSessionFactory(locator);
    final ClientSession session = sf.createSession();
    final ClientSession session2 = sf.createSession();
    session.createQueue(ADDRESS, ADDRESS, null, true);

    final ClientProducer producer = session.createProducer(ADDRESS);

    session.start();
    session2.start();
    try {
      final ClientConsumer consumer = session2.createConsumer(ADDRESS);
      for (int i = 0; i < nMsg; i++) {

        ClientMessage message = session.createMessage(true);
        setBody(i, message);
        message.putIntProperty("counter", i);
        producer.send(message);
        if (i == stop) {
          // Now we start intercepting the communication with the backup
          TestInterceptor.value.set(false);
        }
        ClientMessage msgRcvd = consumer.receive(1000);
        Assert.assertNotNull("Message should exist!", msgRcvd);
        assertMessageBody(i, msgRcvd);
        Assert.assertEquals(i, msgRcvd.getIntProperty("counter").intValue());
        msgRcvd.acknowledge();
      }
    } finally {
      TestInterceptor.value.set(false);
      if (!session.isClosed()) session.close();
      if (!session2.isClosed()) session2.close();
    }
  }
  @Test
  public void testXARollback() throws Exception {
    setupDLQ(10);
    HornetQResourceAdapter qResourceAdapter = newResourceAdapter();
    qResourceAdapter.setConnectorClassName(UnitTestCase.INVM_CONNECTOR_FACTORY);
    MyBootstrapContext ctx = new MyBootstrapContext();
    qResourceAdapter.start(ctx);
    HornetQActivationSpec spec = new HornetQActivationSpec();
    spec.setResourceAdapter(qResourceAdapter);
    spec.setMaxSession(1);
    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");
    latch = new CountDownLatch(1);
    endpoint.reset(latch);
    endpoint.rollback();
    latch.await(5, TimeUnit.SECONDS);

    assertNotNull(endpoint.lastMessage);
    assertEquals(endpoint.lastMessage.getCoreMessage().getBodyBuffer().readString(), "teststring");
    qResourceAdapter.endpointDeactivation(endpointFactory, spec);
    qResourceAdapter.stop();
  }
Ejemplo n.º 24
0
  @Test
  public void testExpireMessage() throws Exception {
    locator.setBlockOnNonDurableSend(true);
    locator.setBlockOnDurableSend(true);
    locator.setReconnectAttempts(-1);

    ClientSessionFactoryInternal sf = createSessionFactoryAndWaitForTopology(locator, 2);
    session = sf.createSession(true, true, 0);

    session.createQueue(PagingFailoverTest.ADDRESS, PagingFailoverTest.ADDRESS, true);

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

    final int TOTAL_MESSAGES = 1000;

    for (int i = 0; i < TOTAL_MESSAGES; i++) {
      ClientMessage msg = session.createMessage(true);
      msg.putIntProperty(new SimpleString("key"), i);
      msg.setExpiration(System.currentTimeMillis() + 1000);
      prod.send(msg);
    }

    crash(session);

    session.close();

    Queue queue = backupServer.getServer().locateQueue(ADDRESS);

    long timeout = System.currentTimeMillis() + 60000;

    while (timeout > System.currentTimeMillis() && queue.getPageSubscription().isPaging()) {
      Thread.sleep(100);
      // Simulating what would happen on expire
      queue.expireReferences();
    }

    assertFalse(queue.getPageSubscription().isPaging());
  }
  public void testSinglePersistentBlockingNonSync() throws Exception {
    HornetQServer server = createServer(true);
    ClientSession session = null;
    ClientSessionFactory factory = null;

    ServerLocator locator = null;

    server.getConfiguration().setJournalSyncNonTransactional(false);
    server.getConfiguration().setJournalBufferTimeout_AIO(15000);

    server.start();

    System.out.println("sync = " + server.getConfiguration().isJournalSyncNonTransactional());
    locator = createFactory(false);
    locator.setBlockOnDurableSend(true);
    factory = locator.createSessionFactory();

    session = factory.createSession();

    session.createQueue("address", "queue");

    ClientProducer prod = session.createProducer("address");

    ClientMessage message = session.createMessage(true);

    prod.send(message);

    ClientConsumer consumer = session.createConsumer("queue");

    session.start();

    ClientMessage msg = consumer.receive(5000);

    Assert.assertNotNull(msg);

    msg.acknowledge();
  }
Ejemplo n.º 26
0
  @Test
  public void testAutoFailback() throws Exception {
    createSessionFactory();
    final CountDownLatch latch = new CountDownLatch(1);

    ClientSession session = sendAndConsume(sf, true);

    CountDownSessionFailureListener listener = new CountDownSessionFailureListener(latch);

    session.addFailureListener(listener);

    liveServer.crash();

    assertTrue(latch.await(5, TimeUnit.SECONDS));

    log.info(
        "backup (nowLive) topology = "
            + backupServer
                .getServer()
                .getClusterManager()
                .getDefaultConnection(null)
                .getTopology()
                .describe());

    log.info("Server Crash!!!");

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

    ClientMessage message = session.createMessage(true);

    setBody(0, message);

    producer.send(message);

    verifyMessageOnServer(1, 1);

    session.removeFailureListener(listener);

    final CountDownLatch latch2 = new CountDownLatch(1);

    listener = new CountDownSessionFailureListener(latch2);

    session.addFailureListener(listener);

    log.info("******* starting live server back");
    liveServer.start();

    Thread.sleep(1000);

    System.out.println("After failback: " + locator.getTopology().describe());

    assertTrue(latch2.await(5, TimeUnit.SECONDS));

    message = session.createMessage(true);

    setBody(1, message);

    producer.send(message);

    session.close();

    verifyMessageOnServer(0, 1);

    wrapUpSessionFactory();
  }
Ejemplo n.º 27
0
  @Test
  public void testHangOnDelivery() throws Exception {
    queue = server.createQueue(QUEUE, QUEUE, null, true, false);
    try {

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

      ServerLocator consumerLocator = createInVMNonHALocator();
      ClientSessionFactory factoryConsumer = consumerLocator.createSessionFactory();
      ClientSession sessionConsumer = factoryConsumer.createSession();

      ClientProducer producer = sessionProducer.createProducer(QUEUE);

      ClientConsumer consumer = sessionConsumer.createConsumer(QUEUE);

      producer.send(sessionProducer.createMessage(true));

      blockConsumers();

      sessionProducer.commit();

      sessionConsumer.start();

      awaitBlocking();

      // this shouldn't lock
      producer.send(sessionProducer.createMessage(true));
      sessionProducer.commit();

      // These two operations should finish without the test hanging
      queue.getMessagesAdded(1);
      queue.getMessageCount(1);

      releaseConsumers();

      // a rollback to make sure everything will be reset on the deliveries
      // and that both consumers will receive each a message
      // this is to guarantee the server will have both consumers regsitered
      sessionConsumer.rollback();

      // a flush to guarantee any pending task is finished on flushing out delivery and pending msgs
      queue.flushExecutor();
      Assert.assertEquals(2, queue.getMessageCount());
      Assert.assertEquals(2, queue.getMessagesAdded());

      ClientMessage msg = consumer.receive(5000);
      Assert.assertNotNull(msg);
      msg.acknowledge();

      msg = consumer.receive(5000);
      Assert.assertNotNull(msg);
      msg.acknowledge();

      sessionProducer.commit();
      sessionConsumer.commit();

      sessionProducer.close();
      sessionConsumer.close();
    } finally {
      releaseConsumers();
    }
  }
Ejemplo n.º 28
0
  /**
   * This would recreate the scenario where a queue was duplicated
   *
   * @throws Exception
   */
  @Test
  public void testHangDuplicateQueues() throws Exception {
    final Semaphore blocked = new Semaphore(1);
    final CountDownLatch latchDelete = new CountDownLatch(1);
    class MyQueueWithBlocking extends QueueImpl {

      /**
       * @param id
       * @param address
       * @param name
       * @param filter
       * @param pageSubscription
       * @param durable
       * @param temporary
       * @param scheduledExecutor
       * @param postOffice
       * @param storageManager
       * @param addressSettingsRepository
       * @param executor
       */
      public MyQueueWithBlocking(
          final long id,
          final SimpleString address,
          final SimpleString name,
          final Filter filter,
          final PageSubscription pageSubscription,
          final boolean durable,
          final boolean temporary,
          final ScheduledExecutorService scheduledExecutor,
          final PostOffice postOffice,
          final StorageManager storageManager,
          final HierarchicalRepository<AddressSettings> addressSettingsRepository,
          final Executor executor) {
        super(
            id,
            address,
            name,
            filter,
            pageSubscription,
            durable,
            temporary,
            scheduledExecutor,
            postOffice,
            storageManager,
            addressSettingsRepository,
            executor);
      }

      @Override
      public synchronized int deleteMatchingReferences(final int flushLimit, final Filter filter)
          throws Exception {
        latchDelete.countDown();
        blocked.acquire();
        blocked.release();
        return super.deleteMatchingReferences(flushLimit, filter);
      }
    }

    class LocalFactory extends QueueFactoryImpl {
      public LocalFactory(
          final ExecutorFactory executorFactory,
          final ScheduledExecutorService scheduledExecutor,
          final HierarchicalRepository<AddressSettings> addressSettingsRepository,
          final StorageManager storageManager) {
        super(executorFactory, scheduledExecutor, addressSettingsRepository, storageManager);
      }

      @Override
      public Queue createQueue(
          final long persistenceID,
          final SimpleString address,
          final SimpleString name,
          final Filter filter,
          final PageSubscription pageSubscription,
          final boolean durable,
          final boolean temporary) {
        queue =
            new MyQueueWithBlocking(
                persistenceID,
                address,
                name,
                filter,
                pageSubscription,
                durable,
                temporary,
                scheduledExecutor,
                postOffice,
                storageManager,
                addressSettingsRepository,
                executorFactory.getExecutor());
        return queue;
      }
    }

    LocalFactory queueFactory =
        new LocalFactory(
            server.getExecutorFactory(),
            server.getScheduledPool(),
            server.getAddressSettingsRepository(),
            server.getStorageManager());

    queueFactory.setPostOffice(server.getPostOffice());

    ((HornetQServerImpl) server).replaceQueueFactory(queueFactory);

    queue = server.createQueue(QUEUE, QUEUE, null, true, false);

    blocked.acquire();

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

    ClientProducer producer = session.createProducer(QUEUE);

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

    Thread tDelete =
        new Thread() {
          @Override
          public void run() {
            try {
              server.destroyQueue(QUEUE);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };

    tDelete.start();

    Assert.assertTrue(latchDelete.await(10, TimeUnit.SECONDS));

    try {
      server.createQueue(QUEUE, QUEUE, null, true, false);
    } catch (Exception expected) {
    }

    blocked.release();

    server.stop();

    tDelete.join();

    session.close();

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

    server.stop();
  }
Ejemplo n.º 29
0
  private void sendMessages(
      final int numberOfMessages,
      final int txBatchSize,
      final boolean durable,
      final boolean transacted,
      final boolean display,
      final int throttleRate,
      final int messageSize,
      final boolean useSendAcks)
      throws Exception {
    ClientSession session = null;

    try {
      session = factory.createSession(!transacted, !transacted);

      CountDownLatch theLatch = null;

      if (useSendAcks) {
        final CountDownLatch latch = new CountDownLatch(numberOfMessages);

        class MySendAckHandler implements SendAcknowledgementHandler {
          public void sendAcknowledged(Message message) {
            latch.countDown();
          }
        }

        session.setSendAcknowledgementHandler(new MySendAckHandler());

        theLatch = latch;
      }

      ClientProducer producer = session.createProducer(perfParams.getAddress());

      ClientMessage message = session.createMessage(durable);

      byte[] payload = PerfBase.randomByteArray(messageSize);

      message.getBodyBuffer().writeBytes(payload);

      final int modulo = 2000;

      TokenBucketLimiter tbl =
          throttleRate != -1 ? new TokenBucketLimiterImpl(throttleRate, false) : null;

      boolean committed = false;

      for (int i = 1; i <= numberOfMessages; i++) {
        producer.send(message);

        if (transacted) {
          if (i % txBatchSize == 0) {
            session.commit();
            committed = true;
          } else {
            committed = false;
          }
        }
        if (display && i % modulo == 0) {
          double duration = (1.0 * System.currentTimeMillis() - start) / 1000;
          PerfBase.log.info(String.format("sent %6d messages in %2.2fs", i, duration));
        }

        // log.info("sent message " + i);

        if (tbl != null) {
          tbl.limit();
        }
      }

      if (transacted && !committed) {
        session.commit();
      }

      session.close();

      if (useSendAcks) {
        theLatch.await();
      }
    } finally {
      if (session != null) {
        session.close();
      }
    }
  }
Ejemplo n.º 30
0
  @Test
  public void testGetNumberOfPages() throws Exception {
    session.close();
    server.stop();
    server.getConfiguration().setPersistenceEnabled(true);

    SimpleString address = RandomUtil.randomSimpleString();

    AddressSettings addressSettings = new AddressSettings();
    addressSettings.setPageSizeBytes(1024);
    addressSettings.setMaxSizeBytes(10 * 1024);
    final int NUMBER_MESSAGES_BEFORE_PAGING = 5;

    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.start();
    session.createQueue(address, address, true);

    QueueImpl serverQueue = (QueueImpl) server.locateQueue(address);

    ClientProducer producer = session.createProducer(address);

    for (int i = 0; i < NUMBER_MESSAGES_BEFORE_PAGING; i++) {
      ClientMessage msg = session.createMessage(true);
      msg.getBodyBuffer().writeBytes(new byte[512]);
      producer.send(msg);
    }
    session.commit();

    AddressControl addressControl = createManagementControl(address);
    Assert.assertEquals(0, addressControl.getNumberOfPages());

    ClientMessage msg = session.createMessage(true);
    msg.getBodyBuffer().writeBytes(new byte[512]);
    producer.send(msg);

    session.commit();
    Assert.assertEquals(1, addressControl.getNumberOfPages());

    msg = session.createMessage(true);
    msg.getBodyBuffer().writeBytes(new byte[512]);
    producer.send(msg);

    session.commit();
    Assert.assertEquals(1, addressControl.getNumberOfPages());

    msg = session.createMessage(true);
    msg.getBodyBuffer().writeBytes(new byte[512]);
    producer.send(msg);

    session.commit();

    Assert.assertEquals("# of pages is 2", 2, addressControl.getNumberOfPages());

    System.out.println("Address size=" + addressControl.getAddressSize());

    Assert.assertEquals(
        serverQueue.getPageSubscription().getPagingStore().getAddressSize(),
        addressControl.getAddressSize());
  }