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(); } }
/** * Listen to a message from JMS from a given destination by name. * * @param destinationName destinationName * @param messageListener messageListener */ public void listenTextMessagesWithDestination( final String destinationName, final Consumer<String> messageListener) { final MessageConsumer consumer = getConsumer(destinationName); try { consumer.setMessageListener( message -> { try { messageListener.accept(((TextMessage) message).getText()); if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) { message.acknowledge(); } } catch (JMSException e) { throw new IllegalStateException( "Unable to register get text from message in listener " + destinationName, e); } catch (Exception ex) { throw new IllegalStateException("Unable handle JMS Consumer " + destinationName, ex); } }); } catch (JMSException e) { throw new IllegalStateException("Unable to register message listener " + destinationName, e); } }
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 static void main(String[] args) { try { Context ctx = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); Queue queue = (Queue) ctx.lookup("inbound"); Connection con = factory.createConnection(); final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); final MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener( new MessageListener() { @Override public void onMessage(Message message) { final String type; try { type = message.getStringProperty("type"); if (type != null && type.equals("xml")) { System.out.println(((TextMessage) message).getText()); } } catch (JMSException e) { e.printStackTrace(); } } }); con.start(); } catch (Exception e) { e.printStackTrace(); } }
@Override public void start() { try { connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); messageConsumer = session.createConsumer(schedulerQueue); messageConsumer.setMessageListener(this); connection.start(); } catch (JMSException e) { e.printStackTrace(); } }
private void setupMessageQueueConsumer() { ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(messageBrokerUrl); Connection connection; try { connection = connectionFactory.createConnection(); connection.start(); this.session = connection.createSession(this.transacted, ackMode); Destination adminQueue = this.session.createQueue(messageQueueName); // Setup a message producer to respond to messages from clients, we will get the destination // to send to from the JMSReplyTo header field from a Message this.replyProducer = this.session.createProducer(null); this.replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); // Set up a consumer to consume messages off of the admin queue MessageConsumer consumer = this.session.createConsumer(adminQueue); consumer.setMessageListener(this); } catch (JMSException e) { // Handle the exception appropriately } }
/** @param args the command line arguments */ public static void main(String[] args) throws NamingException, JMSException, InterruptedException { BasicConfigurator.resetConfiguration(); BasicConfigurator.configure(); try { Properties props = new Properties(); props.setProperty( Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory"); props.setProperty(Context.PROVIDER_URL, "tcp://miniserver.local:61616"); Context context = new InitialContext(props); ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("ConnectionFactory"); FileSystemListener myListener = new FileSystemListener(); Destination destination = (Destination) context.lookup("dynamicTopics/eXistdb"); LOG.info("Destination=" + destination); Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = session.createConsumer(destination); messageConsumer.setMessageListener(myListener); connection.start(); LOG.info("Receiver is ready"); } catch (Throwable t) { LOG.error(t.getMessage(), t); } }
public static void main(String[] args) { Connection connection = null; try { Context context = new InitialContext(); ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME); Destination destination = (Destination) context.lookup(DESTINATION_NAME); Destination controlDestination = (Destination) context.lookup(CONTROL_DESTINATION_NAME); connection = factory.createConnection(); // create a session for the control producer Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageProducer controlProducer = session.createProducer(controlDestination); MessageConsumer consumer = session.createConsumer(destination); consumer.setMessageListener(new JmsMessageListener(session, controlProducer)); // Must have a separate session or connection for the sync MessageConsumer // per JMS spec you cannot have sync and async message consumers on the same // session Session controlSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE); MessageConsumer controlConsumer = controlSession.createConsumer(controlDestination); // calling start after the listeners have been registered connection.start(); LOG.info("Start control message consumer"); int i = 1; while (true) { // sync receive for message consumer Message message = controlConsumer.receive(MESSAGE_TIMEOUT_MILLISECONDS); if (message != null) { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); LOG.info("Got " + (i++) + ". message: " + text); if (text.startsWith("SHUTDOWN")) { break; } } } } controlConsumer.close(); controlSession.close(); consumer.close(); controlProducer.close(); session.close(); } catch (Exception e) { LOG.error(e); } finally { // got to clean up the connections and other resources! if (connection != null) { try { connection.close(); } catch (JMSException e) { LOG.error(e); } } } }
public static void main(String[] args) { _logger.info("Starting..."); final String host; final int port; final String username; final String password; final String virtualPath; final int numExpectedMessages; if (args.length == 0) { host = "localhost"; port = 5672; username = "******"; password = "******"; virtualPath = "/test"; numExpectedMessages = 100; } else if (args.length == 6) { host = args[0]; port = Integer.parseInt(args[1]); username = args[2]; password = args[3]; virtualPath = args[4]; numExpectedMessages = Integer.parseInt(args[5]); } else { System.out.println("Usage: host port username password virtual-path expectedMessageCount"); System.exit(1); throw new RuntimeException("cannot be reached"); } try { InetAddress address = InetAddress.getLocalHost(); AMQConnection con = new AMQConnection(host, port, username, password, address.getHostName(), virtualPath); final AMQSession session = (AMQSession) con.createSession(false, Session.AUTO_ACKNOWLEDGE); final int expectedMessageCount = numExpectedMessages; MessageConsumer consumer = session.createConsumer( new AMQTopic(session.getDefaultTopicExchangeName(), new AMQShortString("large")), 100, true, false, null); consumer.setMessageListener( new MessageListener() { private int _messageCount; private long _startTime = 0; public void onMessage(Message message) { validateMessage(message); if (_messageCount++ == 0) { _startTime = System.currentTimeMillis(); } if (_logger.isInfoEnabled()) { _logger.info("Got message '" + message + "'"); } if (_messageCount == expectedMessageCount) { long totalTime = System.currentTimeMillis() - _startTime; _logger.error( "Total time to receive " + _messageCount + " messages was " + totalTime + "ms. Rate is " + (_messageCount / (totalTime / 1000.0))); } } private void validateMessage(Message message) { if (!(message instanceof BytesMessage)) { _logger.error( "Message is not of correct type - should be BytesMessage and is " + message.getClass()); } BytesMessage bm = (BytesMessage) message; final int expectedSize = 1024 * 187; // 187k try { if (bm.getBodyLength() != expectedSize) { _logger.error( "Message is not correct length - should be " + expectedSize + " and is " + bm.getBodyLength()); } } catch (JMSException e) { _logger.error("Failed to validate message: " + e, e); } try { byte[] data = new byte[(int) bm.getBodyLength()]; bm.readBytes(data); for (int i = 0; i < data.length; i++) { if (data[i] != (byte) (i % 25)) { _logger.error( "byte " + i + " of message is wrong - should be " + i % 25 + " but is " + data[i]); } } _logger.info("***** Validated message successfully"); } catch (JMSException e) { _logger.error("Failed to validate message: " + e, e); } } }); con.start(); } catch (Throwable t) { System.err.println("Fatal error: " + t); t.printStackTrace(); } System.out.println("Waiting..."); }