public void sendResponse( Destination destination, Serializable message, String correlationId, String transactionId) throws JMSException { Connection connection = null; Session session = null; try { InitialContext initialContext = new InitialContext(initialContextProperties); // InitialContext initialContext = new InitialContext(); connectionFactoryName = "/ConnectionFactory"; if (connectionFactory == null) connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName); if (destination == null) destination = (Destination) initialContext.lookup(destinationName); if (userName == null || password == null) connection = connectionFactory.createConnection(); else connection = connectionFactory.createConnection(userName, password); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // session. MessageProducer producer = session.createProducer(destination); connection.start(); ObjectMessage objectMessage = session.createObjectMessage(message); // objectMessage.setLongProperty(MessageConstants.PROPERTY_REQUEST_ID, requestId); objectMessage.setStringProperty(MessageConstants.PROPERTY_CORRELATION_ID, correlationId); objectMessage.setStringProperty(MessageConstants.PROPERTY_TRANSACTION_ID, transactionId); // objectMessage.setObjectProperty(MessageConstants.PROPERTY_MESSAGE_CONTENT, message); objectMessage.setJMSReplyTo(null); producer.send(objectMessage); } catch (NamingException e) { connectionFactory = null; destination = null; throw ExceptionUtil.rewrap(e); } catch (JMSException e) { connectionFactory = null; destination = null; throw e; } finally { // it is important to close session if (session != null) session.close(); try { // Closing a connection automatically returns the connection and // its session plus producer to the resource reference pool. if (connection != null) connection.close(); } catch (JMSException e) { // ignore } ; } }
public void testRun() { // http://pookey.co.uk/wordpress/archives/74-playing-with-activemq-using-maven // http://java.sun.com/developer/technicalArticles/Ecommerce/jms/index.html String brokerURL = "tcp://localhost:61616"; ConnectionFactory factory; Connection connection; Session session; MessageProducer producer; final String fedoraAppEmailQueue = FedoraAppConstants.JMS_ECTD_RESULTS_Q; String string_1 = "/home/chet/batch_space/codu/ectd/logs/codu.ectd.april-08-2011_17:15:36-297.txt"; // ingest // report String string_2 = "/home/chet/batch_space/codu/ectd/logs/codu.ectd.april-08-2011_17:15:36-297.csv"; // pid // report try { factory = new ActiveMQConnectionFactory(brokerURL); connection = factory.createConnection(); connection.start(); session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); System.out.println("\n\n** session transactions is set to :" + session.getTransacted()); // send message Destination destination = session.createQueue(fedoraAppEmailQueue); producer = session.createProducer(destination); System.out.println("Creating Message "); Message message = session.createTextMessage(string_1 + "\n" + string_2 + "\n"); producer.send(message); connection.close(); // consume message connection = factory.createConnection(); connection.start(); session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); destination = session.createQueue(fedoraAppEmailQueue); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(null); consumer.setMessageListener(new ActiveMQListener()); for (int i = 1; i < 10000000; i++) { System.out.println("looping"); } } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } // testRun
/* (non-Javadoc) * @see org.ikasan.spec.management.ManagedResource#startManagedResource() */ public void startManagedResource() { ConnectionFactory _connectionFactory = null; try { if (this.configuration.isRemoteJNDILookup()) { Context context = getInitialContext(); if (this.configuration.getConnectionFactoryName() == null) { throw new RuntimeException( "ConnectionFactory name cannot be 'null' when using remoteJNDILookup"); } _connectionFactory = (ConnectionFactory) context.lookup(this.configuration.getConnectionFactoryName()); if (this.configuration.getDestinationName() == null) { throw new RuntimeException( "DestinationName name cannot be 'null' when using remoteJNDILookup"); } this.destination = (Destination) context.lookup(this.configuration.getDestinationName()); } else { if (this.connectionFactory == null) { throw new RuntimeException( "You must specify the remoteJNDILookup as true or provide a ConnectionFactory instance for this class."); } _connectionFactory = this.connectionFactory; } if (this.configuration.getUsername() != null && this.configuration.getUsername().trim().length() > 0) { connection = _connectionFactory.createConnection( this.configuration.getUsername(), this.configuration.getPassword()); } else { connection = _connectionFactory.createConnection(); } this.session = connection.createSession( this.configuration.isTransacted(), this.configuration.getAcknowledgement()); if (this.destination == null) { if (destinationResolver == null) { throw new RuntimeException( "destination and destinationResolver are both 'null'. No means of resolving a destination."); } this.destination = this.destinationResolver.getDestination(); } } catch (JMSException e) { throw new EndpointException(e); } catch (NamingException e) { throw new RuntimeException(e); } }
public void sendMessage(Serializable message) throws JMSException { Connection connection = null; Session session = null; try { InitialContext initialContext = new InitialContext(initialContextProperties); // InitialContext initialContext = new InitialContext(); if (connectionFactory == null) connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName); if (destination == null) destination = (Destination) initialContext.lookup(destinationName); if (userName == null || password == null) connection = connectionFactory.createConnection(); else connection = connectionFactory.createConnection(userName, password); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // session. MessageProducer producer = session.createProducer(destination); connection.start(); ObjectMessage objectMessage = session.createObjectMessage(message); producer.send(objectMessage); } catch (NamingException e) { connectionFactory = null; destination = null; throw ExceptionUtil.rewrap(e); } catch (JMSException e) { connectionFactory = null; destination = null; throw e; } finally { // it is important to close session if (session != null) session.close(); try { // Closing a connection automatically returns the connection and // its session plus producer to the resource reference pool. if (connection != null) connection.close(); } catch (JMSException e) { // ignore } ; } }
/** * 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; } }
@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(); } } }
@Test public void procuder() throws Exception { Connection connection = null; Session session = null; try { // 创建链接工厂 ConnectionFactory factory = new ActiveMQConnectionFactory( ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL); // 通过工厂创建一个连接 connection = factory.createConnection(); // 启动连接 connection.start(); // 创建一个session会话 session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE); // 创建一个消息队列 Destination destination = session.createQueue(DESTINATION); // 创建消息制作者 MessageProducer producer = session.createProducer(destination); // 设置持久化模式 producer.setDeliveryMode(DeliveryMode.PERSISTENT); sendMessage(session, producer); // 提交会话 session.commit(); } finally { // 关闭释放资源 if (session != null) { session.close(); } if (connection != null) { connection.close(); } } }
public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException() throws JMSException { MockControl cfControl = MockControl.createControl(ConnectionFactory.class); ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); TestConnection con = new TestConnection(); TestExceptionListener listener = new TestExceptionListener(); cf.createConnection(); cfControl.setReturnValue(con, 2); cfControl.replay(); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setExceptionListener(listener); scf.setReconnectOnException(true); Connection con1 = scf.createConnection(); assertSame(listener, con1.getExceptionListener()); con1.start(); con.getExceptionListener().onException(new JMSException("")); Connection con2 = scf.createConnection(); con2.start(); scf.destroy(); // should trigger actual close cfControl.verify(); assertEquals(2, con.getStartCount()); assertEquals(2, con.getCloseCount()); assertEquals(1, listener.getCount()); }
public void initConnection() throws Exception { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?create=false"); connection = (ActiveMQConnection) connectionFactory.createConnection(); connection.setWatchTopicAdvisories(false); connection.start(); }
public static void main(String[] args) throws JMSException { // Getting JMS connection from the server ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); // Creating session for seding messages Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Getting the queue 'JMSBEGINQUEUE' Destination destination = session.createQueue(subject); // MessageConsumer is used for receiving (consuming) messages MessageConsumer consumer = session.createConsumer(destination); // Here we receive the message. // By default this call is blocking, which means it will wait // for a message to arrive on the queue. Message message = consumer.receive(); // There are many types of Message and TextMessage // is just one of them. Producer sent us a TextMessage // so we must cast to it to get access to its .getText() // method. if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; System.out.println("Received message '" + textMessage.getText() + "'"); } connection.close(); }
@Test public void testNetworkedBrokerDetach() throws Exception { LOG.info("Creating Consumer on the networked broker ..."); // Create a consumer on the networked broker ConnectionFactory consFactory = createConnectionFactory(networkedBroker); Connection consConn = consFactory.createConnection(); Session consSession = consConn.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQDestination destination = (ActiveMQDestination) consSession.createQueue(DESTINATION_NAME); for (int i = 0; i < NUM_CONSUMERS; i++) { consSession.createConsumer(destination); } assertTrue( "got expected consumer count from mbean within time limit", verifyConsumerCount(1, destination, broker)); LOG.info("Stopping Consumer on the networked broker ..."); // Closing the connection will also close the consumer consConn.close(); // We should have 0 consumer for the queue on the local broker assertTrue( "got expected 0 count from mbean within time limit", verifyConsumerCount(0, destination, broker)); }
public static void main(String[] args) throws JMSException { AsyncSimpleConsumer asyncConsumer = new AsyncSimpleConsumer(); ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination destination = session.createQueue(subject); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(asyncConsumer); connection.setExceptionListener(asyncConsumer); try { while (true) { if (AsyncSimpleConsumer.catchExit) { break; } Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Sleep interrupted"); } connection.close(); }
public void testMultipleSenders() throws Exception { ConnectionFactory cf = (ConnectionFactory) ic.lookup("/ConnectionFactory"); Queue queue = (Queue) ic.lookup("/queue/StressTestQueue"); drainDestination(cf, queue); Connection conn = cf.createConnection(); Session[] sessions = new Session[CorruptMessageStressTest.PRODUCER_COUNT]; MessageProducer[] producers = new MessageProducer[CorruptMessageStressTest.PRODUCER_COUNT]; for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) { sessions[i] = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); producers[i] = sessions[i].createProducer(queue); producers[i].setDeliveryMode(DeliveryMode.NON_PERSISTENT); } Thread[] threads = new Thread[CorruptMessageStressTest.PRODUCER_COUNT]; for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) { threads[i] = new Thread(new Sender(sessions[i], producers[i]), "Sender Thread #" + i); threads[i].start(); } // wait for the threads to finish for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) { threads[i].join(); } conn.close(); }
public void lookupJMSConnectionFactory() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); Object obj = ctx.lookup("java:comp/env/jms"); Assert.assertNotNull("The JMS ConnectionFactory is null", obj); Assert.assertTrue("Not an instance of ConnectionFactory", obj instanceof ConnectionFactory); final ConnectionFactory connectionFactory = (ConnectionFactory) obj; testJmsConnection(connectionFactory.createConnection()); obj = ctx.lookup("java:comp/env/TopicCF"); Assert.assertNotNull("The JMS TopicConnectionFactory is null", obj); Assert.assertTrue( "Not an instance of TopicConnectionFactory", obj instanceof TopicConnectionFactory); final TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) obj; testJmsConnection(topicConnectionFactory.createConnection()); obj = ctx.lookup("java:comp/env/QueueCF"); Assert.assertNotNull("The JMS QueueConnectionFactory is null", obj); Assert.assertTrue( "Not an instance of QueueConnectionFactory", obj instanceof QueueConnectionFactory); final QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) obj; testJmsConnection(queueConnectionFactory.createConnection()); } catch (final Exception e) { e.printStackTrace(); Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }
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 Message receive(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.getOutputQueue()); MessageConsumer consumer = null; try { consumer = session.createConsumer(destination); return scenario.receive(session, consumer); } finally { if (consumer != null) { consumer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { connection.close(); } } }
@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(); }
/* * (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); } }
private void createAndStartConnection(String userName, String password, String url) throws JMSException { ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, url); connection = (ActiveMQConnection) connectionFactory.createConnection(); connection.start(); LOG.info("Connected successfully to {}", url); }
@Test public void testCompositeDestConsumer() throws Exception { final int numDests = 20; final int numMessages = 200; StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < numDests; i++) { if (stringBuffer.length() != 0) { stringBuffer.append(','); } stringBuffer.append("ST." + i); } stringBuffer.append("?consumer.prefetchSize=100"); ActiveMQQueue activeMQQueue = new ActiveMQQueue(stringBuffer.toString()); ConnectionFactory factory = new ActiveMQConnectionFactory(brokerService.getVmConnectorURI()); Connection connection = factory.createConnection(); connection.start(); MessageProducer producer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createProducer(activeMQQueue); for (int i = 0; i < numMessages; i++) { producer.send(new ActiveMQTextMessage()); } MessageConsumer consumer = connection.createSession(false, Session.AUTO_ACKNOWLEDGE).createConsumer(activeMQQueue); try { for (int i = 0; i < numMessages * numDests; i++) { assertNotNull("recieved:" + i, consumer.receive(4000)); } } finally { connection.close(); } }
public Mail receiveMail() { ConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616"); Destination destination = new ActiveMQQueue("mail.queue"); Connection conn = null; try { conn = cf.createConnection(); Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(destination); conn.start(); MapMessage message = (MapMessage) consumer.receive(); Mail mail = new Mail(); mail.setFrom(message.getString("from")); mail.setTo(message.getString("to")); mail.setSubject(message.getString("subject")); mail.setContent(message.getString("content")); mail.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(message.getString("date"))); session.close(); return mail; } catch (JMSException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (JMSException e) { } } } }
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); }
/* * 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); } }
public void start() throws JMSException { String selector = "next = '" + myId + "'"; try { ConnectionFactory factory = template.getConnectionFactory(); final Connection c = connection = factory.createConnection(); // we might be a reusable connection in spring // so lets only set the client ID once if its not set synchronized (c) { if (c.getClientID() == null) { c.setClientID(myId); } } connection.start(); session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE); consumer = session.createConsumer(destination, selector, false); consumer.setMessageListener(this); } catch (JMSException ex) { LOG.error("", ex); throw ex; } }
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); }
public void testWithConnectionFactoryAndClientId() throws JMSException { MockControl cfControl = MockControl.createControl(ConnectionFactory.class); ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); MockControl conControl = MockControl.createControl(Connection.class); Connection con = (Connection) conControl.getMock(); cf.createConnection(); cfControl.setReturnValue(con, 1); con.setClientID("myId"); conControl.setVoidCallable(1); con.start(); conControl.setVoidCallable(1); con.stop(); conControl.setVoidCallable(1); con.close(); conControl.setVoidCallable(1); cfControl.replay(); conControl.replay(); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setClientId("myId"); Connection con1 = scf.createConnection(); con1.start(); con1.close(); // should be ignored Connection con2 = scf.createConnection(); con2.start(); con2.close(); // should be ignored scf.destroy(); // should trigger actual close cfControl.verify(); conControl.verify(); }
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(); } }
@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 } } }
public DigitalLibraryServer() { try { Properties properties = new Properties(); properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces"); properties.put(Context.PROVIDER_URL, "localhost"); InitialContext jndi = new InitialContext(properties); ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory"); connection = conFactory.createConnection(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); try { counterTopic = (Topic) jndi.lookup("counterTopic"); } catch (NamingException NE1) { System.out.println("NamingException: " + NE1 + " : Continuing anyway..."); } if (null == counterTopic) { counterTopic = session.createTopic("counterTopic"); jndi.bind("counterTopic", counterTopic); } consumer = session.createConsumer(counterTopic); consumer.setMessageListener(this); System.out.println("Server started waiting for client requests"); connection.start(); } catch (NamingException NE) { System.out.println("Naming Exception: " + NE); } catch (JMSException JMSE) { System.out.println("JMS Exception: " + JMSE); JMSE.printStackTrace(); } }
/** * 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(); } } } }