List of usage examples for javax.jms Session createTextMessage
TextMessage createTextMessage(String text) throws JMSException;
From source file:org.apache.activemq.JmsConnectionStartStopTest.java
/** * Tests if the consumer receives the messages that were sent before the * connection was started.// ww w .j a v a 2 s . c o m * * @throws JMSException */ public void testStoppedConsumerHoldsMessagesTillStarted() throws JMSException { Session startedSession = startedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Session stoppedSession = stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Setup the consumers. Topic topic = startedSession.createTopic("test"); MessageConsumer startedConsumer = startedSession.createConsumer(topic); MessageConsumer stoppedConsumer = stoppedSession.createConsumer(topic); // Send the message. MessageProducer producer = startedSession.createProducer(topic); TextMessage message = startedSession.createTextMessage("Hello"); producer.send(message); // Test the assertions. Message m = startedConsumer.receive(1000); assertNotNull(m); m = stoppedConsumer.receive(1000); assertNull(m); stoppedConnection.start(); m = stoppedConsumer.receive(5000); assertNotNull(m); startedSession.close(); stoppedSession.close(); }
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
@Test @Ignore//from w w w.ja v a 2s . c o m public void testReplicationQuorumLoss() throws Throwable { System.out.println("======================================"); System.out.println(" Start 2 ActiveMQ nodes."); System.out.println("======================================"); startBrokerAsync(createBrokerNode("node-1", port)); startBrokerAsync(createBrokerNode("node-2", port)); BrokerService master = waitForNextMaster(); System.out.println("======================================"); System.out.println(" Start the producer and consumer"); System.out.println("======================================"); final AtomicBoolean stopClients = new AtomicBoolean(false); final ArrayBlockingQueue<String> errors = new ArrayBlockingQueue<String>(100); final AtomicLong receivedCounter = new AtomicLong(); final AtomicLong sentCounter = new AtomicLong(); Thread producer = startFailoverClient("producer", new Client() { @Override public void execute(Connection connection) throws Exception { Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue("test")); long actual = 0; while (!stopClients.get()) { TextMessage msg = session.createTextMessage("Hello World"); msg.setLongProperty("id", actual++); producer.send(msg); sentCounter.incrementAndGet(); } } }); Thread consumer = startFailoverClient("consumer", new Client() { @Override public void execute(Connection connection) throws Exception { connection.start(); Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(session.createQueue("test")); long expected = 0; while (!stopClients.get()) { Message msg = consumer.receive(200); if (msg != null) { long actual = msg.getLongProperty("id"); if (actual != expected) { errors.offer("Received got unexpected msg id: " + actual + ", expected: " + expected); } msg.acknowledge(); expected = actual + 1; receivedCounter.incrementAndGet(); } } } }); try { assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); System.out.println("======================================"); System.out.println(" Master should stop once the quorum is lost."); System.out.println("======================================"); ArrayList<BrokerService> stopped = stopSlaves();// stopping the slaves should kill the quorum. assertStopsWithin(master, 10, TimeUnit.SECONDS); assertNull(errors.poll()); // clients should not see an error since they are failover clients. stopped.add(master); System.out.println("======================================"); System.out.println(" Restart the slave. Clients should make progress again.."); System.out.println("======================================"); startBrokersAsync(createBrokerNodes(stopped)); assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS); assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS); assertNull(errors.poll()); } catch (Throwable e) { e.printStackTrace(); throw e; } finally { // Wait for the clients to stop.. stopClients.set(true); producer.join(); consumer.join(); } }
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
private void sendMessage(BrokerService brokerService, String body) throws Exception { TransportConnector connector = brokerService.getTransportConnectors().get(0); ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connector.getConnectUri()); Connection connection = factory.createConnection(); try {//from ww w .j a va 2 s . c o m connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(session.createQueue("FOO")); producer.send(session.createTextMessage(body)); } finally { connection.close(); } }
From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java
private void sendMessages(Destination destination, int count) throws Exception { Connection connection = cf.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); for (int i = 0; i < count; ++i) { TextMessage message = session.createTextMessage("Message #" + i + " for destination: " + destination); producer.send(message);/* www . j a va 2 s . c o m*/ } connection.close(); }
From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkDisconnectTest.java
public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { bridgeBrokers(SPOKE, HUB);/*from ww w . j ava2 s. c o m*/ startAllBrokers(); // Setup connection URI hubURI = brokers.get(HUB).broker.getVmConnectorURI(); URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI(); ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); Connection conHub = facHub.createConnection(); Connection conSpoke = facSpoke.createConnection(); conHub.setClientID("clientHUB"); conSpoke.setClientID("clientSPOKE"); conHub.start(); conSpoke.start(); Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); String consumerName = "consumerName"; // Setup consumers MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName); remoteConsumer.setMessageListener(new MessageListener() { public void onMessage(Message msg) { try { TextMessage textMsg = (TextMessage) msg; receivedMsgs++; LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText()); } catch (JMSException e) { e.printStackTrace(); } } }); // allow subscription information to flow back to Spoke sleep(1000); // Setup producer MessageProducer localProducer = sesHub.createProducer(topic); localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); // Send messages for (int i = 0; i < MESSAGE_COUNT; i++) { sleep(50); if (i == 50 || i == 150) { if (simulateStalledNetwork) { socketProxy.pause(); } else { socketProxy.close(); } networkDownTimeStart = System.currentTimeMillis(); } else if (networkDownTimeStart > 0) { // restart after NETWORK_DOWN_TIME seconds sleep(NETWORK_DOWN_TIME); networkDownTimeStart = 0; if (simulateStalledNetwork) { socketProxy.goOn(); } else { socketProxy.reopen(); } } else { // slow message production to allow bridge to recover and limit message duplication sleep(500); } Message test = sesHub.createTextMessage("test-" + i); localProducer.send(test); } LOG.info("waiting for messages to flow"); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return receivedMsgs >= MESSAGE_COUNT; } }); assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs, MESSAGE_COUNT <= receivedMsgs); brokers.get(HUB).broker.deleteAllMessages(); brokers.get(SPOKE).broker.deleteAllMessages(); conHub.close(); conSpoke.close(); }
From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkRestartTest.java
public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { bridge(SPOKE, HUB);/*from w ww. j a v a 2 s . co m*/ startAllBrokers(); verifyDuplexBridgeMbean(); // Setup connection URI hubURI = brokers.get(HUB).broker.getTransportConnectors().get(0).getPublishableConnectURI(); URI spokeURI = brokers.get(SPOKE).broker.getTransportConnectors().get(0).getPublishableConnectURI(); ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); Connection conHub = facHub.createConnection(); Connection conSpoke = facSpoke.createConnection(); conHub.setClientID("clientHUB"); conSpoke.setClientID("clientSPOKE"); conHub.start(); conSpoke.start(); Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); String consumerName = "consumerName"; // Setup consumers MessageConsumer remoteConsumer = sesHub.createDurableSubscriber(topic, consumerName); sleep(1000); remoteConsumer.close(); // Setup producer MessageProducer localProducer = sesSpoke.createProducer(topic); localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); final String payloadString = new String(new byte[10 * 1024]); // Send messages for (int i = 0; i < MESSAGE_COUNT; i++) { Message test = sesSpoke.createTextMessage("test-" + i); test.setStringProperty("payload", payloadString); localProducer.send(test); } localProducer.close(); final String options = "?persistent=true&useJmx=true&deleteAllMessagesOnStartup=false"; for (int i = 0; i < 2; i++) { brokers.get(SPOKE).broker.stop(); sleep(1000); createBroker(new URI("broker:(tcp://localhost:61616)/" + SPOKE + options)); bridge(SPOKE, HUB); brokers.get(SPOKE).broker.start(); LOG.info("restarted spoke..:" + i); assertTrue("got mbeans on restart", Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return countMbeans(brokers.get(HUB).broker, "networkBridge", 20000) == (dynamicOnly ? 1 : 2); } })); } }
From source file:org.apache.activemq.usecases.RequestReplyToTopicViaThreeNetworkHopsTest.java
public void testMessages(Session sess, MessageProducer req_prod, Destination resp_dest, int num_msg) throws Exception { MessageConsumer resp_cons;// w w w . j av a 2 s . c o m TextMessage msg; MessageClient cons_client; int cur; int tot_expected; resp_cons = sess.createConsumer(resp_dest); cons_client = new MessageClient(resp_cons, num_msg); cons_client.start(); cur = 0; while ((cur < num_msg) && (!fatalTestError)) { msg = sess.createTextMessage("MSG AAAA " + cur); msg.setIntProperty("SEQ", 100 + cur); msg.setStringProperty("TEST", "TOPO"); msg.setJMSReplyTo(resp_dest); if (cur == (num_msg - 1)) msg.setBooleanProperty("end-of-response", true); sendWithRetryOnDeletedDest(req_prod, msg); LOG.debug("Sent:" + msg); cur++; } // // Give the consumer some time to receive the response. // cons_client.waitShutdown(5000); // // Now shutdown the consumer if it's still running. // if (cons_client.shutdown()) LOG.debug("Consumer client shutdown complete"); else LOG.debug("Consumer client shutdown incomplete!!!"); // // Check that the correct number of messages was received. // tot_expected = num_msg * (echoResponseFill + 1); if (cons_client.getNumMsgReceived() == tot_expected) { LOG.debug("Have " + tot_expected + " messages, as-expected"); } else { testError = true; if (cons_client.getNumMsgReceived() == 0) fatalTestError = true; LOG.error("Have " + cons_client.getNumMsgReceived() + " messages; expected " + tot_expected + " on destination " + resp_dest); } resp_cons.close(); }
From source file:org.apache.juddi.subscription.notify.AMQPNotifier.java
@Override public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException { Connection connection = null; Context context = null;/*w ww.jav a2s . c o m*/ boolean success = false; String err = null; try { if (destination != null && exchangeType != null && exchangeName != null) { log.info("Sending notification AMQP to " + destination); Properties properties = new Properties(); properties.put("java.naming.factory.initial", "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"); properties.put("connectionfactory.qpidConnectionfactory", destination); properties.put("destination." + exchangeName, exchangeType); context = new InitialContext(properties); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionfactory"); connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destinationLocal = (Destination) context.lookup(exchangeName); MessageProducer messageProducer = session.createProducer(destinationLocal); String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES); TextMessage message = session.createTextMessage(subscriptionResultXML); messageProducer.send(message); success = true; } } catch (Exception e) { e.printStackTrace(); log.error("Error deliverying AMQP subscription " + e.getMessage()); log.debug("Error deliverying AMQP subscription " + e.getMessage(), e); err = e.getMessage(); } finally { try { if (connection != null) { connection.close(); } } catch (JMSException ex) { log.error(null, ex); } try { if (context != null) { context.close(); } } catch (NamingException ex) { log.error(null, ex); } } if (!success) { throw new DispositionReportFaultMessage(err, null); } DispositionReport dr = new DispositionReport(); Result res = new Result(); dr.getResult().add(res); return dr; }
From source file:org.apache.qpid.systest.management.jmx.QueueManagementTest.java
@Override public Message createNextMessage(Session session, int messageNumber) throws JMSException { Message message = session.createTextMessage(getContentForMessageNumber(messageNumber)); message.setIntProperty(INDEX, messageNumber); return message; }
From source file:org.apache.servicemix.wsn.jms.JmsPublisher.java
@Override public void notify(NotificationMessageHolderType messageHolder, String mes) { Session session = null; try {//from w w w .j ava 2 s. c o m Topic topic = topicConverter.toActiveMQTopic(messageHolder.getTopic()); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(topic); Message message = session.createTextMessage(mes); producer.send(message); } catch (JMSException e) { log.warn("Error dispatching message", e); } catch (InvalidTopicException e) { log.warn("Error dispatching message", e); } finally { if (session != null) { try { session.close(); } catch (JMSException e) { log.debug("Error closing session", e); } } } }