@Test public void testJmsDestination() throws Exception { ClientSession session = basicSetUp(); jmsServer.createQueue( true, "myQueue", null, true, "myQueueJndiBinding1", "myQueueJndiBinding2"); jmsServer.createTopic(true, "myTopic", "myTopicJndiBinding1", "myTopicJndiBinding2"); session.close(); locator.close(); server.stop(); ByteArrayOutputStream xmlOutputStream = new ByteArrayOutputStream(); XmlDataExporter xmlDataExporter = new XmlDataExporter(); xmlDataExporter.process( xmlOutputStream, server.getConfiguration().getBindingsDirectory(), server.getConfiguration().getJournalDirectory(), server.getConfiguration().getPagingDirectory(), server.getConfiguration().getLargeMessagesDirectory()); System.out.print(new String(xmlOutputStream.toByteArray())); clearDataRecreateServerDirs(); server.start(); locator = createInVMNonHALocator(); factory = createSessionFactory(locator); session = factory.createSession(false, true, true); ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(xmlOutputStream.toByteArray()); XmlDataImporter xmlDataImporter = new XmlDataImporter(); xmlDataImporter.process(xmlInputStream, session); assertNotNull(namingContext.lookup("myQueueJndiBinding1")); assertNotNull(namingContext.lookup("myQueueJndiBinding2")); assertNotNull(namingContext.lookup("myTopicJndiBinding1")); assertNotNull(namingContext.lookup("myTopicJndiBinding2")); jmsServer.createConnectionFactory( "test-cf", false, JMSFactoryType.CF, Arrays.asList("in-vm1"), "test-cf"); ConnectionFactory cf = (ConnectionFactory) namingContext.lookup("test-cf"); Connection connection = cf.createConnection(); Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = jmsSession.createProducer((Destination) namingContext.lookup("myQueueJndiBinding1")); producer.send(jmsSession.createTextMessage()); MessageConsumer consumer = jmsSession.createConsumer((Destination) namingContext.lookup("myQueueJndiBinding2")); connection.start(); assertNotNull(consumer.receive(3000)); consumer = jmsSession.createConsumer((Destination) namingContext.lookup("myTopicJndiBinding1")); producer = jmsSession.createProducer((Destination) namingContext.lookup("myTopicJndiBinding2")); producer.send(jmsSession.createTextMessage()); assertNotNull(consumer.receive(3000)); connection.close(); }
@Test public void testSendnReceiveAuthorization() throws Exception { Connection sendingConn = null; Connection receivingConn = null; // Sender try { Destination dest = new ActiveMQQueue(queueName); receivingConn = factory.createConnection("openwireReceiver", "ReCeIvEr"); receivingConn.start(); sendingConn = factory.createConnection("openwireSender", "SeNdEr"); sendingConn.start(); Session sendingSession = sendingConn.createSession(false, Session.AUTO_ACKNOWLEDGE); Session receivingSession = receivingConn.createSession(false, Session.AUTO_ACKNOWLEDGE); TextMessage message = sendingSession.createTextMessage("Hello World"); MessageProducer producer = null; producer = receivingSession.createProducer(dest); try { producer.send(message); } catch (JMSSecurityException e) { // expected producer.close(); } producer = sendingSession.createProducer(dest); producer.send(message); MessageConsumer consumer = null; try { consumer = sendingSession.createConsumer(dest); } catch (JMSSecurityException e) { // expected } consumer = receivingSession.createConsumer(dest); TextMessage received = (TextMessage) consumer.receive(); assertNotNull(received); assertEquals("Hello World", received.getText()); } finally { if (sendingConn != null) { sendingConn.close(); } if (receivingConn != null) { receivingConn.close(); } } }
/** * Send some messages in transacted session. Don't commit. Verify message are not received by * consumer. */ @Test public void testSendNoCommitTopic() throws Exception { Connection conn = null; try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = producerSess.createProducer(ActiveMQServerTestCase.topic1); Session consumerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = consumerSess.createConsumer(ActiveMQServerTestCase.topic1); conn.start(); final int NUM_MESSAGES = 10; // Send some messages for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } Message m = consumer.receive(500); ProxyAssertSupport.assertNull(m); } finally { if (conn != null) { conn.close(); } } }
public void testDestinationStats() throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue replyTo = session.createTemporaryQueue(); MessageConsumer consumer = session.createConsumer(replyTo); Queue testQueue = session.createQueue("Test.Queue"); MessageProducer producer = session.createProducer(null); Queue query = session.createQueue(StatisticsBroker.STATS_DESTINATION_PREFIX + testQueue.getQueueName()); Message msg = session.createMessage(); producer.send(testQueue, msg); msg.setJMSReplyTo(replyTo); producer.send(query, msg); MapMessage reply = (MapMessage) consumer.receive(10 * 1000); assertNotNull(reply); assertTrue(reply.getMapNames().hasMoreElements()); assertTrue(reply.getJMSTimestamp() > 0); assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); /* for (Enumeration e = reply.getMapNames();e.hasMoreElements();) { String name = e.nextElement().toString(); System.err.println(name+"="+reply.getObject(name)); } */ }
public Publisher() throws JMSException { factory = new ActiveMQConnectionFactory(brokerURL); connection = factory.createConnection(username, password); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(null); }
public UserMessageService(String brokerURL, String queueName) throws JMSException { this.queueName = queueName; ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL); this.con = factory.createConnection(); session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); this.producer = session.createProducer(null); }
/** * check if receive(timeout) does timeout when prefetch=0 and redeliveries=0 * * <p>send a message. consume and rollback to ensure redeliverCount is incremented try to consume * message with a timeout. */ @Test(timeout = 20000) public void testConsumerReceivePrefetchZeroRedeliveryZero() throws Exception { connection.start(); // push message to queue Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue("test.prefetch.zero"); MessageProducer producer = session.createProducer(queue); TextMessage textMessage = session.createTextMessage("test Message"); producer.send(textMessage); session.close(); // consume and rollback - increase redelivery counter on message session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageConsumer consumer = session.createConsumer(queue); Message message = consumer.receive(2000); assertNotNull(message); session.rollback(); session.close(); // Reconnect with zero prefetch and zero redeliveries allowed. connection.close(); connection = createConnection(); connection.getPrefetchPolicy().setQueuePrefetch(0); connection.getRedeliveryPolicy().setMaximumRedeliveries(0); connection.start(); // try consume with timeout - expect it to timeout and return NULL message session = connection.createSession(true, Session.SESSION_TRANSACTED); consumer = session.createConsumer(queue); message = consumer.receive(3000); assertNull(message); }
/** * Check a session is rollbacked on a Session close(); * * @throws Exception */ public void xtestTransactionRollbackOnSessionClose() throws Exception { Destination destination = createDestination(getClass().getName()); Connection connection = createConnection(); connection.setClientID(idGen.generateId()); connection.start(); Session consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = null; if (topic) { consumer = consumerSession.createDurableSubscriber((Topic) destination, "TESTRED"); } else { consumer = consumerSession.createConsumer(destination); } Session producerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSession.createProducer(destination); producer.setDeliveryMode(deliveryMode); TextMessage sentMsg = producerSession.createTextMessage(); sentMsg.setText("msg1"); producer.send(sentMsg); producerSession.commit(); Message recMsg = consumer.receive(RECEIVE_TIMEOUT); assertFalse(recMsg.getJMSRedelivered()); consumerSession.close(); consumerSession = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); consumer = consumerSession.createConsumer(destination); recMsg = consumer.receive(RECEIVE_TIMEOUT); consumerSession.commit(); assertTrue(recMsg.equals(sentMsg)); connection.close(); }
/* * (non-Javadoc) * * @see com.sitewhere.spi.server.lifecycle.ILifecycleComponent#start() */ @Override public void start() throws SiteWhereException { try { String key = URLEncoder.encode(getSasKey(), "UTF8"); String connectionString = "amqps://" + getSasName() + ":" + key + "@" + getServiceBusName(); File file = File.createTempFile("eventhub", ".props"); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write("connectionfactory.SBCF = " + connectionString); writer.newLine(); writer.write("queue.EVENTHUB = " + getEventHubName()); writer.newLine(); writer.close(); Hashtable<String, String> env = new Hashtable<String, String>(); env.put( Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.amqp_1_0.jms.jndi.PropertiesFileInitialContextFactory"); env.put(Context.PROVIDER_URL, file.getAbsolutePath()); Context context = new InitialContext(env); this.factory = (ConnectionFactory) context.lookup("SBCF"); this.destination = (Destination) context.lookup("EVENTHUB"); this.connection = factory.createConnection(); this.session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); this.sender = session.createProducer(destination); } catch (IOException e) { throw new SiteWhereException(e); } catch (NamingException e) { throw new SiteWhereException(e); } catch (JMSException e) { throw new SiteWhereException(e); } }
public void send(Scenario scenario) throws Exception { Connection connection = null; try { ConnectionFactory factory = new ActiveMQConnectionFactory(scenario.getBrokerUrl()); connection = factory.createConnection(); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); ActiveMQQueue destination = new ActiveMQQueue(scenario.getInputQueue()); MessageProducer producer = null; try { producer = session.createProducer(destination); scenario.send(session, producer); } finally { if (producer != null) { producer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { connection.close(); } } }
public void produceMessage(int x) { try { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination // Destination destination = session.createQueue("Testqueue"); Destination destination = session.createTopic("Testtopic"); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // Create a messages String text = "Hello world " + x + "! From: " + Thread.currentThread().getName() + " : " + this.hashCode(); TextMessage message = session.createTextMessage(text); // Tell the producer to send the message System.out.println( "Sent message: " + message.hashCode() + " : " + Thread.currentThread().getName()); producer.send(message); session.close(); } catch (Exception e) { System.out.println("Caught: " + e); e.printStackTrace(); } }
protected void setUp() throws Exception { super.setUp(); // Create Client _clientConnection = getConnection("guest", "guest"); _clientConnection.start(); Session clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = clientSession.createQueue("message-listener-test-queue"); _consumer = clientSession.createConsumer(queue); // Create Producer Connection producerConnection = getConnection("guest", "guest"); producerConnection.start(); Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSession.createProducer(queue); for (int msg = 0; msg < MSG_COUNT; msg++) { producer.send(producerSession.createTextMessage("Message " + msg)); } producerConnection.close(); }
@Test public void testSendRollbackQueue() throws Exception { Connection conn = null; try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = producerSess.createProducer(queue1); Session consumerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = consumerSess.createConsumer(queue1); conn.start(); final int NUM_MESSAGES = 10; // Send some messages for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } producerSess.rollback(); Message m = consumer.receive(500); ProxyAssertSupport.assertNull(m); } finally { if (conn != null) { conn.close(); } } }
/** * Send some messages in transacted session. Don't commit. Verify message are not received by * consumer. */ @Test public void testSendNoCommitQueue() throws Exception { Connection conn = null; try { conn = createConnection(); Session producerSess = conn.createSession(true, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = producerSess.createProducer(queue1); Session consumerSess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = consumerSess.createConsumer(queue1); conn.start(); final int NUM_MESSAGES = 10; // Send some messages for (int i = 0; i < NUM_MESSAGES; i++) { Message m = producerSess.createMessage(); producer.send(m); } checkEmpty(queue1); } finally { if (conn != null) { conn.close(); } } }
/** Make sure redelivered flag is set on redelivery via rollback */ @Test public void testRedeliveredQueue() throws Exception { Connection conn = null; try { conn = createConnection(); Session sess = conn.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = sess.createProducer(queue1); MessageConsumer consumer = sess.createConsumer(queue1); conn.start(); Message mSent = sess.createTextMessage("igloo"); producer.send(mSent); sess.commit(); TextMessage mRec = (TextMessage) consumer.receive(2000); ProxyAssertSupport.assertEquals("igloo", mRec.getText()); ProxyAssertSupport.assertFalse(mRec.getJMSRedelivered()); sess.rollback(); mRec = (TextMessage) consumer.receive(2000); ProxyAssertSupport.assertEquals("igloo", mRec.getText()); ProxyAssertSupport.assertTrue(mRec.getJMSRedelivered()); sess.commit(); } finally { if (conn != null) { conn.close(); } } }
private void doTestIdleConsumer(boolean transacted) throws Exception { Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); producer.send(session.createTextMessage("Msg1")); producer.send(session.createTextMessage("Msg2")); if (transacted) { session.commit(); } // now lets receive it MessageConsumer consumer = session.createConsumer(queue); session.createConsumer(queue); TextMessage answer = (TextMessage) consumer.receive(5000); assertEquals("Should have received a message!", answer.getText(), "Msg1"); if (transacted) { session.commit(); } // this call would return null if prefetchSize > 0 answer = (TextMessage) consumer.receive(5000); assertEquals("Should have received a message!", answer.getText(), "Msg2"); if (transacted) { session.commit(); } answer = (TextMessage) consumer.receiveNoWait(); assertNull("Should have not received a message!", answer); }
/** Send a test message now. */ protected void sendMessage() throws JMSException { Session sess = this.producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(queue); prod.send(sess.createTextMessage("X-TEST-MSG-X")); prod.close(); sess.close(); }
@Test public void testSendReceiveMessage() throws Exception { Connection conn = createConnection(); Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer prod = sess.createProducer(queue1); // Make persistent to make sure message gets serialized prod.setDeliveryMode(DeliveryMode.PERSISTENT); MessageConsumer cons = sess.createConsumer(queue1); TestMessage tm = new TestMessage(123, false); ObjectMessage om = sess.createObjectMessage(); om.setObject(tm); conn.start(); prod.send(om); ObjectMessage om2 = (ObjectMessage) cons.receive(1000); ProxyAssertSupport.assertNotNull(om2); TestMessage tm2 = (TestMessage) om2.getObject(); ProxyAssertSupport.assertEquals(123, tm2.getID()); conn.close(); }
/* * Initiate the snapshot by sending a Marker message to one of the Players (Player0) * Any Player could have been used to initiate the snapshot. */ private void sendInitSnapshot() { try { // Gather necessary JMS resources Context ctx = new InitialContext(); ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory"); Queue q = (Queue) ctx.lookup("jms/PITplayer0"); Connection con = cf.createConnection(); Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer writer = session.createProducer(q); /* * As part of the snapshot algorithm, players need to record * what other Players they receive markers from. * "-1" indicates to the PITplayer0 that this marker is coming from * the monitor, not another Player. */ Marker m = new Marker(-1); ObjectMessage msg = session.createObjectMessage(m); System.out.println("Initiating Snapshot"); writer.send(msg); con.close(); } catch (JMSException e) { System.out.println("JMS Exception thrown" + e); } catch (Throwable e) { System.out.println("Throwable thrown" + e); } }
@Test public void sendToNonExistantDestination() throws Exception { Destination destination = HornetQJMSClient.createQueue("DoesNotExist"); TransportConfiguration transportConfiguration = new TransportConfiguration(InVMConnectorFactory.class.getName()); ConnectionFactory localConnectionFactory = HornetQJMSClient.createConnectionFactoryWithoutHA( JMSFactoryType.CF, transportConfiguration); // Using JMS 1 API Connection connection = localConnectionFactory.createConnection(); Session session = connection.createSession(); try { MessageProducer messageProducer = session.createProducer(null); messageProducer.send(destination, session.createMessage()); Assert.fail("Succeeded in sending message to a non-existant destination using JMS 1 API!"); } catch (JMSException e) { // Expected } } // Using JMS 2 API JMSContext context = localConnectionFactory.createContext(); JMSProducer jmsProducer = context.createProducer().setDeliveryMode(DeliveryMode.PERSISTENT); try { jmsProducer.send(destination, context.createMessage()); Assert.fail("Succeeded in sending message to a non-existant destination using JMS 2 API!"); } catch (JMSRuntimeException e) { // Expected } } }
private void enqueueOneMessage() throws Exception { Session session = connection.createSession(true, Session.SESSION_TRANSACTED); MessageProducer producer = session.createProducer(destination); producer.send(session.createTextMessage("middle")); session.commit(); session.close(); }
public static void main(String[] args) { try { Parameters parameters = new Parameters(args); ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(parameters.url); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic destination = session.createTopic(parameters.topic); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); String messageBody = IOUtils.toString(new FileReader(parameters.message)); TextMessage message = session.createTextMessage(messageBody); message.setStringProperty("Channel", parameters.channel); message.setJMSExpiration(parameters.expiration); LOG.info("Sent message: {}", message); producer.send(message); session.close(); connection.close(); } catch (Exception e) { LOG.error("Producing interrupted", e); } }
public void produceMsg(String text) throws Exception { // Create a ConnectionFactory ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); // Create a Connection Connection connection = connectionFactory.createConnection(); connection.start(); // Create a Session Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create the destination (Topic or Queue) Destination destination = session.createQueue("TEST.FOO"); // Create a MessageProducer from the Session to the Topic or Queue MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // Create a messages TextMessage message = session.createTextMessage(text); producer.send(message); // Clean up session.close(); connection.close(); }
/** * Send a command via JMS. * * <p>Note: Opens and closes the connection per invocation of this method which, when run outside * a JavaEE container, is not very efficient. * * @param command * @throws JMSException */ public void sendCommandMessage(Command command) throws JMSException { Connection connection = null; Session session = null; try { connection = connectionFactory.createConnection(); session = connection.createSession(TRANSACTIONAL, Session.AUTO_ACKNOWLEDGE); // Construct a JMS "TextMessage" final TextMessage newMessage = session.createTextMessage(); newMessage.setStringProperty("issuer", command.getIssuer()); newMessage.setStringProperty("type", command.getType()); newMessage.setText(command.getPayload()); // Send the message final MessageProducer producer = session.createProducer(this.commandQueue); producer.send(newMessage); if (TRANSACTIONAL) { // JavaEE containers would manage this session.commit(); } } finally { if (connection != null) { try { if (session != null) { session.close(); } connection.stop(); connection.close(); } catch (JMSException e) { e.printStackTrace(); } } } }
public void sendMessage(Order order) { ConnectionFactory factory = new ActiveMQConnectionFactory("failover://tcp://localhost:61616"); Queue queue = new ActiveMQQueue("sequence"); Connection conn = null; Session sen = null; MessageProducer producer = null; TextMessage msg = null; JSONMapper mapper = new JSONMapper(); Destination des = null; try { conn = factory.createConnection(); sen = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = sen.createProducer(queue); conn.start(); String str = mapper.writeObjectAsString(order); System.out.println(str); msg = sen.createTextMessage(str); producer.send(msg); producer.close(); sen.close(); conn.close(); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); Connection connection = null; out.write("<h1>Produce JMS ObjectMessages</h1>"); try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(queue); ObjectMessage message = session.createObjectMessage(); MyResource resource = new MyResource("This is my resource"); message.setObject(resource); producer.send(message); out.write("<p>Send JMS Message with object: " + resource + "</p>"); } catch (JMSException e) { e.printStackTrace(); out.write("<h2>A problem occurred during the delivery of this message</h2>"); out.write("</br>"); out.write( "<p><i>Go your the JBoss Application Server console or Server log to see the error stack trace</i></p>"); } finally { if (connection != null) { try { connection.close(); } catch (JMSException e) { e.printStackTrace(); } } if (out != null) { out.close(); } } }
public void testBrokerStatsReset() throws Exception { Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue replyTo = session.createTemporaryQueue(); MessageConsumer consumer = session.createConsumer(replyTo); Queue testQueue = session.createQueue("Test.Queue"); Queue query = session.createQueue(StatisticsBroker.STATS_BROKER_PREFIX); MessageProducer producer = session.createProducer(null); producer.send(testQueue, session.createMessage()); Message msg = session.createMessage(); msg.setJMSReplyTo(replyTo); producer.send(query, msg); MapMessage reply = (MapMessage) consumer.receive(10 * 1000); assertNotNull(reply); assertTrue(reply.getMapNames().hasMoreElements()); assertTrue(reply.getLong("enqueueCount") >= 1); msg = session.createMessage(); msg.setBooleanProperty(StatisticsBroker.STATS_BROKER_RESET_HEADER, true); msg.setJMSReplyTo(replyTo); producer.send(query, msg); reply = (MapMessage) consumer.receive(10 * 1000); assertNotNull(reply); assertTrue(reply.getMapNames().hasMoreElements()); assertEquals(0, reply.getLong("enqueueCount")); assertTrue(reply.getJMSTimestamp() > 0); assertEquals(Message.DEFAULT_PRIORITY, reply.getJMSPriority()); }
/** * Initializes the qpid connection with a jndiName of cow, and a host and port taken from the * cow-server.properties file. */ public void init() { String connectionFactorylocation = "amqp://*****:*****@clientid/test?brokerlist='tcp://" + host + ":" + port + "'"; String destinationType = "topic"; String jndiName = "cow"; String destinationName = "myTopic"; try { properties = new Properties(); properties.setProperty( Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"); properties.setProperty("connectionfactory.amqpConnectionFactory", connectionFactorylocation); properties.setProperty(destinationType + "." + jndiName, destinationName); context = new InitialContext(properties); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("amqpConnectionFactory"); Connection connection = connectionFactory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = (Destination) context.lookup(jndiName); messageProducer = session.createProducer(destination); initialized = true; } catch (Exception e) { log.debug(e.getMessage()); initialized = false; } }
protected void publish(String text, String subject) throws JMSException { Session session = createSession(); Destination destination = createDestination(session, subject); MessageProducer publisher = session.createProducer(destination); if (isDurable()) { publisher.setDeliveryMode(DeliveryMode.PERSISTENT); } else { publisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT); } System.out.println( "Starting publisher on : " + destination + " of type: " + destination.getClass().getName()); System.out.println("Message length: " + text.length()); if (loops <= 0) { while (true) { publishLoop(session, publisher, text); } } else { for (int i = 0; i < loops; i++) { publishLoop(session, publisher, text); } } }
@Test public void testSendMessage() throws Exception { ConnectionFactory connFactory = lookup("ConnectionFactory", ConnectionFactory.class); Connection conn = connFactory.createConnection(); conn.start(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); TemporaryQueue replyQueue = session.createTemporaryQueue(); TextMessage msg = session.createTextMessage("Hello world"); msg.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT); msg.setJMSReplyTo(replyQueue); Queue queue = lookup("java:jboss/" + queueName, Queue.class); MessageProducer producer = session.createProducer(queue); producer.send(msg); MessageConsumer consumer = session.createConsumer(replyQueue); Message replyMsg = consumer.receive(5000); Assert.assertNotNull(replyMsg); if (replyMsg instanceof ObjectMessage) { Exception e = (Exception) ((ObjectMessage) replyMsg).getObject(); throw e; } Assert.assertTrue(replyMsg instanceof TextMessage); String actual = ((TextMessage) replyMsg).getText(); Assert.assertEquals("SUCCESS", actual); consumer.close(); producer.close(); session.close(); conn.stop(); }