Skip to content

Instantly share code, notes, and snippets.

@steos
Created November 4, 2011 12:57
Show Gist options
  • Save steos/1339261 to your computer and use it in GitHub Desktop.
Save steos/1339261 to your computer and use it in GitHub Desktop.
minimal/naive sample on how to use activemq peer protocol
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import net.miginfocom.swing.MigLayout;
import org.apache.activemq.ActiveMQConnectionFactory;
public class MinimalActiveMQPeerProtocolSample {
static final private String peerGroup = "foo";
static final private String brokerName = "bar";
static final private String topic = "lorem";
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
ActiveMQConnectionFactory connFact = new ActiveMQConnectionFactory(
"peer://" + peerGroup + "/" + brokerName + "?persistent=false");
Connection conn = connFact.createConnection();
conn.start();
final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Destination dest = sess.createTopic(topic);
final MessageProducer prod = sess.createProducer(dest);
prod.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
final MessageConsumer cons = sess.createConsumer(dest);
final JFrame f = new JFrame("testit");
final JTextField input = new JTextField();
final JTextArea output = new JTextArea();
output.setEditable(false);
final JPanel content = new JPanel(new MigLayout("fill",
"[grow,fill,:200:][]", "[][grow,fill,:100:]"));
final JButton sendBtn = new JButton("Send");
content.add(input);
content.add(sendBtn, "wrap");
content.add(output, "span");
cons.setMessageListener(new MessageListener() {
public void onMessage(Message msg) {
if (msg instanceof TextMessage) {
TextMessage tm = (TextMessage)msg;
try {
output.setText(output.getText() + tm.getText() + "\n");
}
catch (JMSException e) {
e.printStackTrace();
}
}
};
});
sendBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = input.getText().trim();
input.setText("");
if (msg.length() == 0) {
return;
}
try {
TextMessage tm = sess.createTextMessage(msg);
prod.send(tm);
}
catch (JMSException ex) {
throw new RuntimeException(ex);
}
}
});
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(content);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment