Tag: CLI

How to create security-domain in JBossAS7 using CLI


In the month of November-2011 we wrote some articles for (JBossAS7.1.0Beta1) “EJB based CXF WebService with Basic Authentication in JBoss AS7” (http://middlewaremagic.com/jboss/?p=958). And “Basic Authentication in WebApp Based CXF WebService JBoss AS7” (http://middlewaremagic.com/jboss/?p=976).

In the above examples we created the “security-domain” by manually editing the JBoss configuration file “standalone-full.xml”. But as we know that JBoss provides us a lots of reliable and quick options in order to configure various resources. JBoss CLI (Command Line Utility) is one of them, So here we will see how we can very easily create the security-domain on the server with the help of CLI.

Configuring “security-domain” using CLI

Step1). Make sure that your JBoss is running so and it’s Native Management Port and Address is accessible to the CLI utility. I am starting the JBoss with the following option:

   ./standalone.sh -c standalone-full.xml -b -bmanagement

NOTE: Here we started JBoss with the “-bmanagement” so that the We can access JBoss using Native interface on address “” by default it will be localhost, Which restricts us to access the JBoss Native Interface remotely.

Step2). Now we will create security-domain with name “cxfservice-security-domain” using code “UsersRoles”. Open a command/Shell Prompt and then move inside “/home/userone/jboss-as-7.1.2.Final/bin” and then run the following script to start the JBoss CLI and to connect it to running JBoss:

  ./jboss-cli.sh --connect --controller=

Step3). Once you get successfully connected to JBoss using CLI then you can run the following two Commands in order to create a security-domain

[standalone@ /]  /subsystem=security/security-domain=cxfservice-security-domain/:add(cache-type=default)

{"outcome" => "success"}

[standalone@ /] /subsystem=security/security-domain=cxfservice-security-domain/authentication=classic:add(login-modules=[{"code"=>"UsersRoles", "flag"=>"required", "module-options"=>[("usersProperties"=>"cxfservice-users.properties"),("rolesProperties"=>"cxfservice-roles.properties"),("unauthenticatedIdentity"=>"nobody")] }]   )

    "outcome" => "success",
    "response-headers" => {
        "operation-requires-reload" => true,
        "process-state" => "reload-required"

As the above two commands got executed successfully so you will be able to see the changes in your “jboss-as-7.1.2.Final/standalone/configuration/standalone-full.xml” file as following:

<security-domain name="cxfservice-security-domain" cache-type="default">
    <login-module code="UsersRoles" flag="required">
      <module-option name="usersProperties" value="cxfservice-users.properties"/>
      <module-option name="rolesProperties" value="cxfservice-roles.properties"/>
      <module-option name="unauthenticatedIdentity" value="nobody"/>


To know how to run jboss-cli.sh in GUI mode ?

refer to the following link: http://middlewaremagic.com/jboss/?p=2018

MiddlewareMagic Team 🙂

Binding & Remote Lookup of Custom Objects in JNDI tree of JBoss AS7.1.1


In this example we will see how to bind custom objects in the JNDI tree of “JBoss AS7.1.1 Final” and What kind of JNDI name we should choose in order to make the Remote client to be able to access (lookup) those JNDI entries.

Point-1). JBoss AS7.1.1.Final provides a Jar file for the Client side in order to perform remote lookup’s of JMS and EJB components “jboss-as-7.1.1.Final/bin/client/jboss-client.jar”. This jar should be used with standalone clients only, not with deployments are that deployed to an AS7 instance.

Point-2). If we want to make the JNDI name accessible for a remote client then the JNDI name must have “exported” keywork in the following pattern: “java:jboss/exported/YOUR_JNDI_NAME”

Point-3). On the client side we will need to use a new Protocol “remote://” as following:

  String JBOSS_CONTEXT="org.jboss.naming.remote.client.InitialContextFactory";;
  Properties props = new Properties();
  props.put(Context.PROVIDER_URL, "remote://localhost:4447"); 
  props.put(Context.SECURITY_PRINCIPAL, "testuser");
  props.put(Context.SECURITY_CREDENTIALS, "testpassword");
  context = new InitialContext(props);	

Point-4). We will use the “jboss-cli.sh” script to configure the custom JNDI bindings on JBoss AS7.1.1.Final

Point-5): [ IMPORTANT ] Security is the main focus now so before running “JBoss AS7.1.1.Final” we will need to create a new Application User by running “${JBOSS_HOME}/bin/add-user.sh” script as following so that Remote User will be able to access the JNDI :

[userone@localhost bin]$ ./add-user.sh 

What type of user do you wish to add? 
 a) Management User (mgmt-users.properties) 
 b) Application User (application-users.properties)
(a): b

Enter the details of the new user to add.
Realm (ApplicationRealm) :  ApplicationRealm
Username : testuser
Password : testpassword
Re-enter Password : testpassword

What roles do you want this user to belong to? (Please enter a comma separated list, or leave blank for none) : testrole
About to add user 'testuser' for realm 'ApplicationRealm'

Is this correct yes/no? yes

Added user 'testuser' to file '/home/userone/jboss-as-7.1.1.Final/standalone/configuration/application-users.properties'
Added user 'testuser' to file '/home/userone/jboss-as-7.1.1.Final/domain/configuration/application-users.properties'
Added user 'testuser' with roles testrole to file '/home/userone/jboss-as-7.1.1.Final/standalone/configuration/application-roles.properties'
Added user 'testuser' with roles testrole to file '/home/userone/jboss-as-7.1.1.Final/domain/configuration/application-roles.properties'

Source Code (Git Repo) Source Code for this Demo Can be downloaded from GIT Repository:

Start JBoss AS7.1.1.Final like following:

$ ./standalone.sh  -c standalone-full.xml

Binding Simple Objects in the JNDI Tree.

Step-1). Open a terminal (command prompt) then nevigate inside your “/home/userone/JBoss_All/jboss-as-7.1.1.Final/bin” directory and then run the following command in order to start and connect the JBoss CLI utility with the running JBoss instance:

$    ./jboss-cli.sh -c --controller=localhost:9999
[userone@localhost bin]$    ./jboss-cli.sh -c 
[userone@localhost bin]$    ./jboss-cli.sh -c --controller=localhost:9999  --gui        

Step-2). Now in order to bind a simple Integer Data type value in the JNDI tree just run the following command:


If you dont want to use the command line utility to achieve the above then you can edit the naming subsystem of your “standalone-full.xml” file as following:

        <subsystem xmlns="urn:jboss:domain:naming:1.1">
                <simple name="java:jboss/exported/test" value="100" type="int"/>

Binding Complex/Custom Objects in the JNDI Tree.

Step-1). Suppose you have created a class like “TestBean.java” and you want to bind an instance of this class in the JNDI tree of your JBoss, then we will need to compile this class and we will need to make sure that this class is present inside the JBoss Classpath (using the JBoss Modules concept we can do that). Just write the following kind of class “TestBean.java”

package test.jndi.demo;
public class TestBean implements java.io.Serializable
      private String name;
      private String value;

      public TestBean(String name,String value)
         System.out.println("[TestBean] TestBean initialized.");

      public String getName()  
          return name;
      public String getValue()  
          return value;

Step-2). Now in order to bind a Complex Data type value in the JNDI tree we will need to create a class which implements the “javax.naming.spi.ObjectFactory” interface and the getObjectInstance(…,…,..) method of this class should return the object which we want to bind in the JNDI tree of JBoss as following:

package test.jndi.demo;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
public class MyCustomObjectFactory implements ObjectFactory 
       public MyCustomObjectFactory() 
            System.out.println("[MyCustomObjectFactory] MyCustomObjectFactory initialized.");

       public Object getObjectInstance(Object obj, Name name, Context nameCtx,Hashtable environment) throws Exception 
            TestBean bean = new TestBean("City","Pune (India)");
            return bean;

Step-3). Now compile the above two classes “TestBean.java” and “MyCustomObjectFactory.java” and then make a Jar file which should contain these classes. Suppose your JAR file name is “testJndiBinding.jar”

Step-4). Now we will need to make a JBoss module containing the above Jar “testJndiBinding.jar”. In order to create JBoss Module simply create a directory “test/jndi/demo/main” inside JBoss modules directory like:

mkdir “/home/userone/JBoss_All/jboss-as-7.1.1.Final/modules/test/jndi/demo/main”

Step-5). Now place your “testJndiBinding.jar” file inside “jboss-as-7.1.1.Final/modules/test/jndi/demo/main” directory and then create a file with name “module.xml” inside “jboss-as-7.1.1.Final/modules/test/jndi/demo/main” as following:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="test.jndi.demo">
        <resource-root path="testJndiBinding.jar"/>
        <module name="javax.api"/>

Step-6). Restart your JBoss so that the Module can be utilized.

Step-7). Now in order to bind the “TestBean.class” object in the JNDI tree of JBoss AS7.1.1.Final we will need to run the following CLI command:


If you dont want to use the command line utility to achieve the above then you can edit the naming subsystem of your “standalone-full.xml” file as following:

        <subsystem xmlns="urn:jboss:domain:naming:1.1">
                <simple name="java:jboss/exported/test" value="100" type="int"/>
                <object-factory name="java:jboss/exported/test2" module="test.jndi.demo" class="test.jndi.demo.MyCustomObjectFactory"/>

Creating Aliases of the JNDI Names.

Step-7). If you want to create various alias Lookup names for your JNDI names then you can do the following….. (Suppose you want to create various alias names for your JNDI name “java:jboss/exported/test2”)


If you dont want to use the command line utility to achieve the above then you can edit the naming subsystem of your “standalone-full.xml” file as following:

        <subsystem xmlns="urn:jboss:domain:naming:1.1">
                <!-- Binding primitive Data types in the JNDI Tree -->
                <simple name="java:jboss/exported/test" value="1000" type="int"/>

                <!-- Binding Custom Objects in the JNDI Tree -->
                <object-factory name="java:jboss/exported/test2" module="test.jndi.demo" class="test.jndi.demo.MyCustomObjectFactory"/>

                <!--  Following is used for Aliasing JNDI names -->
                <lookup name="java:jboss/exported/test3" lookup="java:jboss/exported/test2"/>
                <lookup name="java:jboss/exported/test4" lookup="java:jboss/exported/test2"/>
                <lookup name="java:jboss/exported/test5" lookup="java:jboss/exported/test2"/>
                <lookup name="java:jboss/exported/test6" lookup="java:jboss/exported/test2"/>
                <lookup name="java:jboss/exported/test7" lookup="java:jboss/exported/test2"/>

Testing the Remote JNDI Lookup

Now as we have already binded various objects in the in the JNDI tree of JBoss, so now we will write simple Standalone Java code in order to perform the Remote JNDI Lookup.

Write the following code somewhere in your file system “BindJndiDemo.java”

import java.io.*;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class BindJndiDemo
public final static String JNDI_FACTORY="org.jboss.naming.remote.client.InitialContextFactory";

public static void main(String[] args) throws Exception 
     if (args.length != 1) {
         System.out.println("Usage: java BindJndiDemo URL");
         System.out.println("Example:  java BindJndiDemo remote://localhost:4447");

     InitialContext ic = getInitialContext(args[0]);
     BindJndiDemo demo = new BindJndiDemo();

     System.out.println("nnt *** Following shows Looking up a Primitive Datatype located in the JNDI ***");
     Object primitiveLookup=ic.lookup("test");
     System.out.println("tic.lookup("test") primitiveLookup = "+primitiveLookup);

     System.out.println("nnt *** Following shows Looking up a Custom Bean/Object located in the JNDI ***");
     test.jndi.demo.TestBean testBean=(test.jndi.demo.TestBean)ic.lookup("test2");
     System.out.println("t(test.jndi.demo.TestBean)ic.lookup("test2") testBean = "+testBean);

     System.out.println("nnt *** Following shows the JNDI Name Aliasing ***");
     Object obj=ic.lookup("test3");
     System.out.println("tAliasing Demo ic.lookup("test3") = "+obj);
     System.out.println("tAliasing Demo ic.lookup("test4") = "+obj);
     System.out.println("tAliasing Demo ic.lookup("test5") = "+obj);

private static InitialContext getInitialContext(String url) throws NamingException
        Hashtable env = new Hashtable();
        env.put(Context.PROVIDER_URL, url);

        //*************** UserName & Password for the Initial Context for JNDI lookup *************************
        env.put(Context.SECURITY_PRINCIPAL, "testuser");
        env.put(Context.SECURITY_CREDENTIALS, "testpassword");
        InitialContext ic=new InitialContext(env);
        System.out.println("nnt Got InitialContext ic: "+ic);
        return ic;

Now before compiling and running the above program just make sure that the “jboss-as-7.1.1.Final/bin/client/jboss-client.jar” is added in your CLASSPATH as following:

[userone@localhost Binding_Custom_Object_IN_JBossAS711Final]$ echo $PATH

[userone@localhost Binding_Custom_Object_IN_JBossAS711Final]$ echo $CLASSPATH

[userone@localhost Binding_Custom_Object_IN_JBossAS711Final]$  java BindJndiDemo remote://localhost:4447
Apr 29, 2012 12:38:43 AM org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.3.GA
Apr 29, 2012 12:38:43 AM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.3.GA
Apr 29, 2012 12:38:43 AM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.3.GA

	 Got InitialContext ic: javax.naming.InitialContext@671ff436

	 *** Following shows Looking up a Primitive Datatype located in the JNDI ***
	ic.lookup("test") primitiveLookup = 100

	 *** Following shows Looking up a Custom Bean/Object located in the JNDI ***
	(test.jndi.demo.TestBean)ic.lookup("test2") testBean = test.jndi.demo.TestBean@12b754b2
	name=City	value=Pune (India)

	 *** Following shows the JNDI Name Aliasing ***
	Aliasing Demo ic.lookup("test3") = test.jndi.demo.TestBean@63b0bdc8
	Aliasing Demo ic.lookup("test4") = test.jndi.demo.TestBean@359eda2c
	Aliasing Demo ic.lookup("test5") = test.jndi.demo.TestBean@4c349471

Thanks 🙂
Middleware Magic Team

How to create a Topic in JBoss AS 7 ?

In this article we would show how to create a Topic in JBoss AS7 which uses HornetQ, in this example we would use CLI command to create a Topic as well to deploy an EAR file which would consists of both a message sender as well as an MDB which would work as the consumer to consume the messages by the sender code.

We would be using the standalone mode for this article and in JBoss AS 7.1.0.CR1 version we have a different xml file called standalone-full.xml which has the all the HornetQ related configuration, but it has been said that the same would be integrated in the standalone.xml file in coming JBoss AS 7.1 version.

Before creating a Topic lets create an MDB and a Topic sender program which would be used to send and receive the messages.

Steps to create an MDB & Topic Sender

  1. Create a folder called MDB-3.
  2. In “MDB-3” folder create three folders called MDB3.jar, META-INF, TopicSender.war
  3. In “MDB3.jar” folder create MyMDB.java file and copy the below code in it and compile it as well.
  4. import javax.jms.Message;
    import javax.jms.TextMessage;
    import javax.jms.JMSException;
    import javax.jms.MessageListener;
    import javax.ejb.MessageDriven;
    import javax.ejb.ActivationConfigProperty;
    @MessageDriven(activationConfig =
            @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Topic"),
            @ActivationConfigProperty(propertyName="destination", propertyValue="topic/MyTopic"),
            //************************* RECONNECT PARAMERTERS  *****************************
            @ActivationConfigProperty(propertyName="reconnectAttempts", propertyValue="60"),
            @ActivationConfigProperty(propertyName="reconnectInterval", propertyValue="10")
    public class MyMDB implements MessageListener{
        public void onMessage(Message message) {
            TextMessage textMessage = (TextMessage) message;
            try {
                System.out.println("===> MyMDB Received: "+ textMessage.getText());
            } catch (JMSException e) {
  5. In “META-INF” folder create application.xml file and copy the below code in it.
  6. <?xml version="1.0" encoding="UTF-8"?>
    <application version="5" xmlns="http://java.sun.com/xml/ns/javaee"
                  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd">
  7. In “TopicSender.war” folder create WEB-INF folder which has classes folder and web.xml inside it and copy the below code in “web.xml”.
  8. <web-app>
  9. Then In “classes” folder create TopicSenderServlet.java file and copy the below code in it and compile it as well
  10. import java.io.*;
    import java.util.*;
    import javax.jms.*;
    import javax.naming.*;
    import javax.transaction.*;
    import javax.servlet.http.*;
    import javax.rmi.PortableRemoteObject;
    import javax.servlet.ServletException;
    public class TopicSenderServlet extends HttpServlet 
    	static PrintWriter out;
    	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    			InitialContext ic = getInitialContext();
    			init(ic, TOPIC_NAME);
    		catch(Exception e)
    	//*************** Connection Factory JNDI name *************************
    	public final static String CONN_FACTORY="/ConnectionFactory";
    	//*************** Topic JNDI name *************************
    	public final static String TOPIC_NAME="topic/MyTopic";
    	protected TopicConnectionFactory tconFactory;
    	protected TopicConnection tcon;
    	protected TopicSession tsession;
    	protected static TopicPublisher tpublisher;
    	protected Topic topic;
    	protected static TextMessage msg;
    	public void init(Context ctx, String topicName) throws NamingException, JMSException
    		tconFactory = (TopicConnectionFactory) PortableRemoteObject.narrow(ctx.lookup(CONN_FACTORY),TopicConnectionFactory.class);
    		tcon = tconFactory.createTopicConnection();
    		tsession = tcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    		topic = (Topic) PortableRemoteObject.narrow(ctx.lookup(topicName), Topic.class);
    		tpublisher = tsession.createPublisher(topic);
    		msg = tsession.createTextMessage();
    	private static void sendMsg(TopicSenderServlet ts) throws IOException, JMSException
    		boolean readFlag=true;
    		out.println("<H1>Topic Sender Servlet</H1>");
    		out.println("Following Messages has been sent !!!<br>");
    		for(int j=1;j<=3;j++) 
            		msg.setText(""+j); 		// Messages 
            		tpublisher.publish(msg); 	// Messages sent
       			out.println("<BR>Message Sent = "+j);
    	private static InitialContext getInitialContext() throws NamingException
    		return new InitialContext();
  11. Once you have done with all this you now just have to create an EAR file out of this, for that you need to be in the MDB-3 folder and run the below command (make sure you have setted the java/bin in your PATH). Note: you would have to give the (.) dot at last as well
  12. MDB-3] jar -cvf MDB-3.ear .

Steps for creating a Topic in JBoss AS 7

  1. Now we would have to start our JBoss AS 7 with standalone-full.xml using -c parameter during the start-up of JBoss
  2. bin] ./standalone.sh -c standalone-full.xml
  3. Once the JBoss server is up and running properly then you can run the below CLI command with using the a Topic-setup.cli file which would make sure that a new Topic MyTopic is been created and it would also deploy the MDB-3.ear to the server.
  4. Create a file called Topic-setup.cli in the bin folder of JBoss and copy the below content

    add-jms-topic --name=MyTopic --entries=topic/MyTopic
    deploy /home/urs/JMS/MDB-3/MDB-3.ear

    Run the below command

    bin] ./jboss-admin.sh --file=Topic-setup.cli


Once you can successfully created a Topic and deployed the application using the above CLI command now its time for testing our newly created Topic

  1. Open a browser and hit the below URL (I am supposing that you are running JBoss on default port and IP) and that would send 3 messages to the Topic which can be seen on the browser itself
  2. http://localhost:8080/TopicSender/TopicSenderServlet

  3. After hitting the above URL you would see the below messages been received by the MDB on the running JBoss server prompt
  4. 14:32:48,295 INFO  [stdout] (Thread-1 (group:HornetQ-client-global-threads-1623557144)) ===> MyMDB Received: 1
    14:32:48,295 INFO  [stdout] (Thread-0 (group:HornetQ-client-global-threads-1623557144)) ===> MyMDB Received: 2
    14:32:48,296 INFO  [stdout] (Thread-2 (group:HornetQ-client-global-threads-1623557144)) ===> MyMDB Received: 3

Copyright © 2010-2012 Middleware Magic. All rights reserved. |