Software

How to Send a Message to an Apache ActiveMQ Queue with Java

JAX-RS

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;

@WebServlet(name = "SampleActiveMQServlet", value = "/")
public class SampleActiveMQServlet extends HttpServlet {

  protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    Client client = ClientBuilder.newClient();

    client.target("http://host:8161/api/message/SampleTopic").queryParam("type", "queue").queryParam("body", "Simples Assim").request(MediaType.TEXT_XML_TYPE).post(Entity.xml(""));

    client.close();
  }

}

JMS

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class ActiveMQSample {

  public static void main(String[] args) throws Exception {
    ConnectionFactory connFactory = new ActiveMQConnectionFactory();

    Connection conn = connFactory.createConnection();

    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);

    Destination dest = sess.createQueue("SampleQueue");

    MessageProducer prod = sess.createProducer(dest);

    Message msg = sess.createTextMessage("Simples Assim");

    prod.send(msg);

    conn.close();
  }

}

Java API for WebSocket

import java.io.IOException;

import javax.websocket.ClientEndpoint;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;

@ClientEndpoint
public class SampleActiveMQEndpoint {

  @OnOpen
  public void onOpen(Session sess) throws IOException {
    RemoteEndpoint.Basic remote = sess.getBasicRemote();

    remote.sendText("CONNECT\n\n\0");

    remote.sendText("SEND\ndestination:SampleQueue\n\nSimples Assim\0");

    remote.sendText("DISCONNECT\n\n\0");
  }

}

One thought on “How to Send a Message to an Apache ActiveMQ Queue with Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.