#
WRITE a message into a WildFly Queue
This tutorial explains to you how we can write (send) a simple message to a WildFly queue with Java. I used a WildFly 10 Application Server.
To see the initial number of messages in a WildFly Queue, connect to the Admin Console of the Server and after that go to "Runtime" -> "Subsystems" -> "Messaging ActiveMQ" -> click on View -> click on View and you will see:
After the message is sent you will see one message added:
In my example I used a WildFly 10, Java EE 8 and PrimeFaces. The message is sent from a Web Application which is running on WildFly as well.
Here is the code I put on the JSF (.xhtml) page:
<h:form>
<p:commandbutton value="Send Message" id="ajax" actionlistener="#{wildflyJms.sendMessage}">
</p:commandbutton>
</h:form>
For sending a message I used the WildflyJms.java file:
/*
* Here you have an example of Java code for writing a message to a WildFly Queue
*
*/
package resources;
import java.util.Hashtable;
import java.util.Properties;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.naming.*;
import javax.jms.*;
@ManagedBean (name="wildflyJms")
public class WildflyJms {
// Set the JNDI context factory for a JBOSS/ WildFly Server.
public final static String JNDI_FACTORY="org.jboss.ejb.client.naming";
// Set the JMS context factory.
public final static String JMS_FACTORY="java:/ConnectionFactory";
// Set the queue.
public final static String QUEUE="java:/MyWildFlyQueue";
// Set Wildfly URL.
public final static String WildflyURL="http-remoting://localhost:8080";
public void sendMessage(String message) throws Exception {
//1) Create and start a connection
Properties properties = new Properties();
properties.put(Context.URL_PKG_PREFIXES, JNDI_FACTORY);
InitialContext ic=new InitialContext(properties);
QueueConnectionFactory f=(QueueConnectionFactory)ic.lookup(JMS_FACTORY) ;
QueueConnection con=f.createQueueConnection();
con.start();
//2) create queue session
QueueSession ses=con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
//3) get the Queue object
Queue t=(Queue)ic.lookup(QUEUE);
//4)create QueueSender object
QueueSender sender=ses.createSender(t);
//5) create TextMessage object
TextMessage msg=ses.createTextMessage();
msg.setText("This message will be send to a WildFly Queue !");
//6) send message
sender.send(msg);
System.out.println("Message successfully sent to a WildFly Queue.");
//7) connection close
con.close();
}
}