List of usage examples for javax.jms Session createProducer
MessageProducer createProducer(Destination destination) throws JMSException;
From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java
@Test @Ignore// w w w . j a v a2 s . co 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:com.mirth.connect.connectors.jms.JmsDispatcher.java
/** * Retrieve the dispatcherId specific JmsSession from the cache. If the JmsSession does not * exist, create a new one from the connection. */// ww w . j a v a 2 s . c o m private JmsSession getJmsSession(JmsConnection jmsConnection, Long dispatcherId) throws Exception { Map<Long, JmsSession> jmsSessions = jmsConnection.getJmsSessions(); JmsSession jmsSession = jmsSessions.get(dispatcherId); if (jmsSession == null) { Session session = jmsConnection.getConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageProducer producer = session.createProducer(null); jmsSession = new JmsSession(session, producer); jmsSessions.put(dispatcherId, jmsSession); } return jmsSession; }
From source file:org.ahp.core.messaging.AhpJmsProducer.java
public void sendTextMessage(String pTextMessage, AhpJmsDestinationTypes pAhpJmsDestinationTypes, AhpJmsDestinationNames pAhpJmsDestinationNames) { Connection lConnection = null; Session lSession = null; try {/*from w ww. j av a2 s . c o m*/ lConnection = this.mJmsConnectionFactory.createConnection(); lSession = lConnection.createSession(true, Session.AUTO_ACKNOWLEDGE); Destination lDestination = null; if (pAhpJmsDestinationTypes.equals(AhpJmsDestinationTypes.Queue)) lDestination = lSession.createQueue(pAhpJmsDestinationNames.toString()); else lDestination = lSession.createTopic(pAhpJmsDestinationNames.toString()); MessageProducer lMessageProducer = lSession.createProducer(lDestination); lMessageProducer.setDeliveryMode(DeliveryMode.PERSISTENT); //lMessageProducer.setTimeToLive( timeToLive ); Message lTextMessage = lSession.createTextMessage(pTextMessage); LOGGER.debug("AhpJmsProducer sending message to Destination " + pAhpJmsDestinationNames.toString() + " TextMessage :: \n" + pTextMessage); lMessageProducer.send(lTextMessage); lSession.commit(); } catch (JMSException exJms) { LOGGER.error("", exJms); } finally { try { lConnection.close(); } catch (JMSException exJms) { LOGGER.error("", exJms); } } }
From source file:org.apache.activemq.JmsConnectionStartStopTest.java
/** * Tests if the consumer receives the messages that were sent before the * connection was started.// w ww .j a v a 2 s.com * * @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:jenkins.plugins.logstash.persistence.ActiveMqDao.java
@Override public void push(String data) throws IOException { TopicConnection connection = null;//w ww.j a va 2 s.co m Session session = null; try { // Create a Connection connection = connectionFactory.createTopicConnection(); connection.start(); // Create a Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Create the destination Queue Destination destination = session.createTopic(key); // Create the MessageProducer from the Session to the Queue MessageProducer producer = session.createProducer(destination); producer.setDeliveryMode(DeliveryMode.PERSISTENT); // Create the message TextMessage message = session.createTextMessage(data); message.setJMSType("application/json"); // Tell the producer to send the message producer.send(message); //logger.log( Level.FINER, String.format("JMS message sent with ID [%s]", message.getJMSMessageID())); } catch (JMSException e) { logger.log(Level.SEVERE, null != e.getMessage() ? e.getMessage() : e.getClass().getName()); throw new IOException(e); } finally { // Clean up try { if (null != session) session.close(); } catch (JMSException e) { logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName()); } try { if (null != connection) connection.close(); } catch (JMSException e) { logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName()); } } }
From source file:org.springframework.jms.listener.adapter.AbstractAdaptableMessageListener.java
/** * Send the given response message to the given destination. * @param response the JMS message to send * @param destination the JMS destination to send to * @param session the JMS session to operate on * @throws JMSException if thrown by JMS API methods * @see #postProcessProducer//from w ww . j av a2s .c om * @see javax.jms.Session#createProducer * @see javax.jms.MessageProducer#send */ protected void sendResponse(Session session, Destination destination, Message response) throws JMSException { MessageProducer producer = session.createProducer(destination); try { postProcessProducer(producer, response); QosSettings settings = getResponseQosSettings(); if (settings != null) { producer.send(response, settings.getDeliveryMode(), settings.getPriority(), settings.getTimeToLive()); } else { producer.send(response); } } finally { JmsUtils.closeMessageProducer(producer); } }
From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkRestartTest.java
public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { bridge(SPOKE, HUB);//from w ww .j a va 2 s . c om 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.dawnsci.commandserver.core.consumer.RemoteSubmission.java
/** * Submits the bean onto the server. From there events about this * bean are tacked by monitoring the status queue. * //from w ww . j a v a2 s .c om * @param uri * @param bean */ public synchronized TextMessage submit(StatusBean bean, boolean prepareBean) throws Exception { if (getQueueName() == null || "".equals(getQueueName())) throw new Exception("Please specify a queue name!"); Connection send = null; Session session = null; MessageProducer producer = null; try { QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); send = connectionFactory.createConnection(); session = send.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = session.createQueue(queueName); producer = session.createProducer(queue); producer.setDeliveryMode(DeliveryMode.PERSISTENT); ObjectMapper mapper = new ObjectMapper(); if (getTimestamp() < 1) setTimestamp(System.currentTimeMillis()); if (getPriority() < 1) setPriority(1); if (getLifeTime() < 1) setLifeTime(7 * 24 * 60 * 60 * 1000); // 7 days in ms if (prepareBean) { if (bean.getUserName() == null) bean.setUserName(System.getProperty("user.name")); bean.setUniqueId(uniqueId); bean.setSubmissionTime(getTimestamp()); } String jsonString = mapper.writeValueAsString(bean); TextMessage message = session.createTextMessage(jsonString); message.setJMSMessageID(uniqueId); message.setJMSExpiration(getLifeTime()); message.setJMSTimestamp(getTimestamp()); message.setJMSPriority(getPriority()); producer.send(message); return message; } finally { if (send != null) send.close(); if (session != null) session.close(); if (producer != null) producer.close(); } }
From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.factory.JMSConnectionFactory.java
/** * This is a JMS spec independent method to create a MessageProducer. Please be cautious when * making any changes/*from w w w .j av a 2s .co m*/ * * @param session JMS session * @param destination the Destination * @param isQueue is the Destination a queue? * @param jmsSpec11 should we use JMS 1.1 API ? * @return a MessageProducer to send messages to the given Destination * @throws JMSException on errors, to be handled and logged by the caller */ public MessageProducer createProducer(Session session, Destination destination, Boolean isQueue) throws JMSException { if ("2.0".equals(jmsSpec) || "1.1".equals(jmsSpec) || isQueue == null) { return session.createProducer(destination); } else { if (isQueue) { return ((QueueSession) session).createSender((Queue) destination); } else { return ((TopicSession) session).createPublisher((Topic) destination); } } }
From source file:org.springframework.jms.listener.adapter.MessageListenerAdapter.java
/** * Send the given response message to the given destination. * @param response the JMS message to send * @param destination the JMS destination to send to * @param session the JMS session to operate on * @throws JMSException if thrown by JMS API methods * @see #postProcessProducer/*from ww w . j ava2s . co m*/ * @see javax.jms.Session#createProducer * @see javax.jms.MessageProducer#send */ protected void sendResponse(Session session, Destination destination, Message response) throws JMSException { MessageProducer producer = session.createProducer(destination); try { postProcessProducer(producer, response); producer.send(response); } finally { JmsUtils.closeMessageProducer(producer); } }