Labels

Showing posts with label JBoss. Show all posts
Showing posts with label JBoss. Show all posts

Thursday, August 7, 2014

How to Install JBoss 6 on Linux

This post will cover installing JBoss 6.0 on CentOS 5.x.

(If you are looking to install JBoss 7, please see my post here: http://www.davidghedini.com/pg/entry/install_jboss_7_on_centos)

We'll also set up JBoss to run as a service, as well as secure the JMX and Web Service consoles

While there are similarities to JBoss 5.1 installation, the file locations have changed in some instances

Here is an outline of the steps we will follow:

1. Download and Install the Java Development Kit (JDK)
2. Download and Install JBoss 6.0 Application Server
3. Create the user, jboss, who will own and run JBoss
4. Set the required JAVA_HOME and JBOSS_HOME paths
5. Create a start/stop/restart script for JBoss
6. Configure JBoss to run as a service
7. Access the JBoss Admin console
8. Change the JBoss Admin Password
9. Secure the JMX Console
10. Securing the Web Service Console
11. Set memory parameters for JBoss using JAVA_OPTS
12. Configure JBoss to run on port 80
Step 1: Download and Install the Java Development Kit (JDK)


You can download the JDK here: http://www.oracle.com/technetwork/java/javase/downloads/index.html

I'm using JDK 6, update 24, the latest as of this post. The JDK is specific to 32 and 64 bit versions.

My CentOS box is 64 bit, so I'll need: jdk-6u24-linux-x64.bin.

If you are on 32 bit, you'll need: jdk-6u24-linux-i586.bin

Download the appropriate JDK and save it to a directory. I'm saving it to /root.

Move (mv) or copy (cp) the file to the /opt directory:


  1. [root@sv2 ~]# mv jdk-6u24-linux-x64.bin /opt/jdk-6u24-linux-x64.bin  


Create the directory /usr/java.


  1. [root@sv2 ~]# mkdir /usr/java  


Change to the /usr/java directory we created and install the JDK using 'sh /opt/jdk-6u24-linux-x64.bin'


  1. [root@sv2 ~]# cd /usr/java  
  2. [root@sv2 java]# sh /opt/jdk-6u24-linux-x64.bin  


We now have the JDK installed at /usr/java/jdk1.6.0_24. We'll use this for our JAVA_HOME a bit later in step


Step 2: Download and Install JBoss 6.0 Application Server


Download jboss-6.0.0.Final.zip at http://sourceforge.net/projects/jboss/files/JBoss/jboss-6.0.0.Final/ or use wget:


  1. [root@sv2 ~]# wget http://sourceforge.net/projects/jboss/files/JBoss/JBoss-6.0.0.Final/jboss-as-distribution-6.0.0.Final.zip/download  
  2. .  
  3. .  
  4. .  
  5. 100%[======================================>] 181,267,148  816K/s   in 3m 31s  
  6.   
  7. 2011-03-13 00:56:44 (839 KB/s) - `jboss-as-distribution-6.0.0.Final.zip' saved [181267148/181267148]  


Move (mv) or copy (cp) the file to /usr/share/jboss-6.0.0.Final.zip.


  1. [root@sv2 ~]# mv jboss-as-distribution-6.0.0.Final.zip /usr/share/jboss-as-distribution-6.0.0.Final.zip  


Change to the /usr/share directory and unzip the file:


  1. [root@sv2 ~]# cd /usr/share  
  2. [root@sv2 share]# unzip -q jboss-as-distribution-6.0.0.Final.zip  


The unzip will create the following directory: /usr/share/jboss-6.0.0.Final

This directory will be our JBOSS_HOME, which we will use below in Step 4.


Step 3: Create the user, jboss, who will own and run JBoss


Since we will want to run JBoss as a non-root user with minimal privileges, we'll create a user, jboss, who will own the JBoss files and JBoss will run under his account.

To do this, we can need to the following.

Create a new group, jboss, and then create the user jboss and add the user to the jboss group.


  1. [root@sv2 ~]# groupadd jboss  
  2. [root@sv2 ~]# useradd -s /bin/bash -g jboss jboss  


Change ownership of the JBoss home directory, /usr/share/jboss-6.0.0.Final so all files are owned by the user jboss we created.


  1. [root@sv2 ~]# chown -Rf jboss.jboss /usr/share/jboss-6.0.0.Final/  



Step 4: Set the required JAVA_HOME and JBOSS_HOME paths


We no need to set the JAVA_HOME and JBOSS_HOME.

The JAVA_HOME is where we installed the JDK above, /usr/java/jdk1.6.0_24, and the JBOSS_HOME is where we installed JBoss above /usr/share/jboss-6.0.0.Final.

Add the following to the jboss users .bash_profile:


  1. JAVA_HOME=/usr/java/jdk1.6.0_24  
  2. export JAVA_HOME  
  3. PATH=$JAVA_HOME/bin:$PATH  
  4. export PATH  
  5. JBOSS_HOME=/usr/share/jboss-6.0.0.Final  
  6. export JBOSS_HOME  


To set the JAVA_HOME for users, we add this to the user ~/.bashrc or ~/.bash_profile of the user. We can also add it /etc/profile and then source it to give to all users.


  1. JAVA_HOME=/usr/java/jdk1.6.0_24   
  2. export JAVA_HOME   
  3. PATH=$JAVA_HOME/bin:$PATH   
  4. export PATH  


Once you have added the above to ~/.bash_profile or ~/.bashrc, you should su to the user jboss and verify that the JAVA_HOME and JBOSS_HOME are set correctly.


  1. [root@sv2 ~]#  su jboss  
  2. [jboss@sv2 ~]#  echo $JAVA_HOME  
  3. /usr/java/jdk1.6.0_24  
  4. [jboss@sv2 ~]#  echo $JBOSS_HOME  
  5. /usr/share/jboss-6.0.0.Final  



Step 5: Create a start/stop/restart script for JBoss.


For our JBoss script we will simply copy the existing jboss_init_redhat.sh script located at at /usr/share/jboss-6.0.0.Final/bin, copy it to /etc/init.d and rename it to 'jboss':

So, as root:


  1. [root@sv2 ~]# cd /usr/share/jboss-6.0.0.Final/bin   
  2. [root@sv2 bin]# cp jboss_init_redhat.sh /etc/init.d/jboss  


In the jboss script (shown completed below), make the following changes:

1. Add lines 3,4, and 5:
# description: JBoss Start Stop Restart
# processname: jboss
# chkconfig: 234 20 80
2. Line 22, Set the JBOSS_HOME to where we unpacked JBoss in step 2 above:
JBOSS_HOME=${JBOSS_HOME:-"/usr/share/jboss-6.0.0.Final"}

3. Line 28. Set the JAVA_HOME to where we installed the JDK in step 1 above:
JAVAPTH=${JAVAPTH:-"/usr/java/jdk1.6.0_24"}

4. Add line 34, which sets the JBOSS_HOST to 0.0.0.0, allowing JBoss to bind to any IP.
JBOSS_HOST="0.0.0.0"


  1. #!/bin/sh  
  2. #  
  3. # description: JBoss Start Stop Restart  
  4. # processname: jboss6  
  5. # chkconfig: 234 20 80  
  6. #  
  7. # $Id: jboss_init_redhat.sh 81068 2008-11-14 15:14:35Z dimitris@jboss.org $  
  8. #  
  9. # JBoss Control Script  
  10. #  
  11. # To use this script run it as root - it will switch to the specified user  
  12. #  
  13. # Here is a little (and extremely primitive) startup/shutdown script  
  14. # for RedHat systems. It assumes that JBoss lives in /usr/local/jboss,  
  15. # it's run by user 'jboss' and JDK binaries are in /usr/local/jdk/bin.  
  16. # All this can be changed in the script itself.   
  17. #  
  18. # Either modify this script for your requirements or just ensure that  
  19. # the following variables are set correctly before calling the script.  
  20.  
  21. #define where jboss is - this is the directory containing directories log, bin, conf etc  
  22. JBOSS_HOME=${JBOSS_HOME:-"/usr/share/jboss-6.0.0.Final"}  
  23.  
  24. #define the user under which jboss will run, or use 'RUNASIS' to run as the current user  
  25. JBOSS_USER=${JBOSS_USER:-"jboss"}  
  26.  
  27. #make sure java is in your path  
  28. JAVAPTH=${JAVAPTH:-"/usr/java/jdk1.6.0_24"}  
  29.  
  30. #configuration to use, usually one of 'minimal', 'default', 'all'  
  31. JBOSS_CONF=${JBOSS_CONF:-"default"}  
  32.  
  33. #if JBOSS_HOST specified, use -b to bind jboss services to that address  
  34. JBOSS_HOST="0.0.0.0"  
  35. JBOSS_BIND_ADDR=${JBOSS_HOST:+"-b $JBOSS_HOST"}  
  36.  
  37. #define the classpath for the shutdown class  
  38. JBOSSCP=${JBOSSCP:-"$JBOSS_HOME/bin/shutdown.jar:$JBOSS_HOME/client/jnet.jar"}  
  39.  
  40. #define the script to use to start jboss  
  41. JBOSSSH=${JBOSSSH:-"$JBOSS_HOME/bin/run.sh -c $JBOSS_CONF $JBOSS_BIND_ADDR"}  
  42.   
  43. if [ "$JBOSS_USER" = "RUNASIS" ]; then  
  44.   SUBIT=""  
  45. else  
  46.   SUBIT="su - $JBOSS_USER -c "  
  47. fi  
  48.   
  49. if [ -n "$JBOSS_CONSOLE" -a ! -d "$JBOSS_CONSOLE" ]; then  
  50.   # ensure the file exists  
  51.   touch $JBOSS_CONSOLE  
  52.   if [ ! -z "$SUBIT" ]; then  
  53.     chown $JBOSS_USER $JBOSS_CONSOLE  
  54.   fi   
  55. fi  
  56.   
  57. if [ -n "$JBOSS_CONSOLE" -a ! -f "$JBOSS_CONSOLE" ]; then  
  58.   echo "WARNING: location for saving console log invalid: $JBOSS_CONSOLE"  
  59.   echo "WARNING: ignoring it and using /dev/null"  
  60.   JBOSS_CONSOLE="/dev/null"  
  61. fi  
  62.  
  63. #define what will be done with the console log  
  64. JBOSS_CONSOLE=${JBOSS_CONSOLE:-"/dev/null"}  
  65.   
  66. JBOSS_CMD_START="cd $JBOSS_HOME/bin; $JBOSSSH"  
  67. JBOSS_CMD_STOP=${JBOSS_CMD_STOP:-"java -classpath $JBOSSCP org.jboss.Shutdown --shutdown"}  
  68.   
  69. if [ -z "`echo $PATH | grep $JAVAPTH`" ]; then  
  70.   export PATH=$PATH:$JAVAPTH  
  71. fi  
  72.   
  73. if [ ! -d "$JBOSS_HOME" ]; then  
  74.   echo JBOSS_HOME does not exist as a valid directory : $JBOSS_HOME  
  75.   exit 1  
  76. fi  
  77.   
  78. echo JBOSS_CMD_START = $JBOSS_CMD_START  
  79.   
  80. case "$1" in  
  81. start)  
  82.     cd $JBOSS_HOME/bin  
  83.     if [ -z "$SUBIT" ]; then  
  84.         eval $JBOSS_CMD_START >${JBOSS_CONSOLE} 2>&1 &  
  85.     else  
  86.         $SUBIT "$JBOSS_CMD_START >${JBOSS_CONSOLE} 2>&1 &"   
  87.     fi  
  88.     ;;  
  89. stop)  
  90.     if [ -z "$SUBIT" ]; then  
  91.         $JBOSS_CMD_STOP  
  92.     else  
  93.         $SUBIT "$JBOSS_CMD_STOP"  
  94.     fi   
  95.     ;;  
  96. restart)  
  97.     $0 stop  
  98.     $0 start  
  99.     ;;  
  100. *)  
  101.     echo "usage: $0 (start|stop|restart|help)"  
  102. esac  



Step 6: Run JBoss as a Service.


To run JBoss as a service and enable start up at boot, make the script we created above executable and add it to our chkconfig so it starts at boot.


  1. [root@sv2 init.d]# chmod 755 jboss  
  2. [root@sv2 init.d]# chkconfig --add jboss  
  3. [root@sv2 init.d]# chkconfig --level 234 jboss on  


We should now be able to Start, Stop, and Restart JBoss as a service.

Start JBoss:

Note: JBoss can take some time to start.


  1. [root@sv2 init.d]# service jboss6 start  
  2. JBOSS_CMD_START = cd /usr/share/jboss-6.0.0.Final/bin; /usr/share/jboss-6.0.0.Final/bin/run.sh -c default -b 0.0.0.0  


Stop JBoss:
  1. [root@sv2 init.d]# service jboss6 stop  
  2. JBOSS_CMD_START = cd /usr/share/jboss-6.0.0.Final/bin; /usr/share/jboss-6.0.0.Final/bin/run.sh -c default -b 0.0.0.0  
  3. Shutdown message has been posted to the server.  
  4. Server shutdown may take a while - check logfiles for completion  



Step 7: Access the JBoss Admin.


Make sure JBoss is started and you should now be able to access the Jboss Console at:

http://yourdomain.com:8080 or http://yourip:8080

The default user name and password for the JBoss Admin Console is admin/admin




Access the Admin Console by clicking on the Administration Console link.





Step 8: Change the JBoss Admin Password


To change the default Admin Console password, go to:

/usr/share/jboss-6.0.0.Final/server/default/conf/props

Open the jmx-console-users.properties file in text editor and change the password.


  1. # A sample users.properties file for use with the UsersRolesLoginModule  
  2. admin=MyPassword  



Step 9: Secure the JMX Console


To secure the JMX Console, go to:

/usr/share/jboss-6.0.0.Final/common/deploy/jmx-console.war/WEB-INF

First, edit the web.xml file. Towards the bottom, you will find the security-constraint as shown below:


  1. <!-- A security constraint that restricts access to the HTML JMX console  
  2.    to users with the role JBossAdmin. Edit the roles to what you want and  
  3.    uncomment the WEB-INF/jboss-web.xml/security-domain element to enable  
  4.    secured access to the HTML JMX console.  
  5.    <security-constraint>  
  6.      <web-resource-collection>  
  7.        <web-resource-name>HtmlAdaptor</web-resource-name>  
  8.        <description>An example security config that only allows users with the  
  9.          role JBossAdmin to access the HTML JMX console web application  
  10.        </description>  
  11.        <url-pattern>/*</url-pattern>  
  12.      </web-resource-collection>  
  13.      <auth-constraint>  
  14.        <role-name>JBossAdmin</role-name>  
  15.      </auth-constraint>  
  16.    </security-constraint>  
  17.    -->  


Un-comment the security-constraint section so it appears thus:


  1. <security-constraint>  
  2.      <web-resource-collection>  
  3.        <web-resource-name>HtmlAdaptor</web-resource-name>  
  4.        <description>An example security config that only allows users with the  
  5.          role JBossAdmin to access the HTML JMX console web application  
  6.        </description>  
  7.        <url-pattern>/*</url-pattern>  
  8.      </web-resource-collection>  
  9.      <auth-constraint>  
  10.        <role-name>JBossAdmin</role-name>  
  11.      </auth-constraint>  
  12.    </security-constraint>  


Next, still in the WEB-INF directory, edit the jboss-web.xml file, which will look as below:


  1. <!DOCTYPE jboss-web PUBLIC  
  2.    "-//JBoss//DTD Web Application 5.0//EN"  
  3.    "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd">  
  4.      
  5. <jboss-web>  
  6.    <!-- Uncomment the security-domain to enable security. You will  
  7.       need to edit the htmladaptor login configuration to setup the  
  8.       login modules used to authentication users.  
  9.       <security-domain>java:/jaas/jmx-console</security-domain>  
  10.    -->  
  11. </jboss-web>  


Uncomment the security-domain so it appears thus:

<pre class="js" name="code"><!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 5.0//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd"> <jboss-web> <security-domain>java:/jaas/jmx-console</security-domain> </jboss-web>

At this point, the password for the JMX Console will be the same as the password we set for the Admin Console in step 8 above.

Both the Admin Console and JMX Console are are using the jmx-console-roles.properties and jmx-console-users.properties files.


Step 10: Secure the Web Service Console


To secure the Web Service Console, go to:

/usr/share/jboss-6.0.0.Final/common/deploy/jbossws-console.war/WEB-INF

First, edit the web.xml file. Towards the bottom, you will find the security-constraint as shown below:


  1. <!-- A security constraint that restricts access  
  2.    <security-constraint>  
  3.      <web-resource-collection>  
  4.        <web-resource-name>ContextServlet</web-resource-name>  
  5.        <description>An example security config that only allows users with the  
  6.          role 'friend' to access the JBossWS console web application  
  7.        </description>  
  8.        <url-pattern>/*</url-pattern>  
  9.      </web-resource-collection>  
  10.      <auth-constraint>  
  11.        <role-name>friend</role-name>  
  12.      </auth-constraint>  
  13.    </security-constraint>  
  14.    -->  


Un-comment the security-constraint section so it appears thus:


  1. <security-constraint>  
  2.      <web-resource-collection>  
  3.        <web-resource-name>ContextServlet</web-resource-name>  
  4.        <description>An example security config that only allows users with the  
  5.          role 'friend' to access the JBossWS console web application  
  6.        </description>  
  7.        <url-pattern>/*</url-pattern>  
  8.      </web-resource-collection>  
  9.      <auth-constraint>  
  10.        <role-name>friend</role-name>  
  11.      </auth-constraint>  
  12.    </security-constraint>  


Next, still in the WEB-INF directory, edit the jboss-web.xml file, which will look as below:


  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2.   
  3. <!DOCTYPE jboss-web  
  4.     PUBLIC "-//JBoss//DTD Web Application 2.3V2//EN"  
  5.     "http://www.jboss.org/j2ee/dtd/jboss-web_3_2.dtd">  
  6.   
  7. <jboss-web>  
  8.   
  9.   <!-- A security domain that restricts access  
  10.   <security-domain>java:/jaas/JBossWS</security-domain>  
  11.   -->  
  12.     
  13.   <context-root>jbossws</context-root>  
  14.   
  15. </jboss-web>  


Uncomment the security-domain so it appears thus:


  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2.   
  3. <!DOCTYPE jboss-web  
  4.     PUBLIC "-//JBoss//DTD Web Application 2.3V2//EN"  
  5.     "http://www.jboss.org/j2ee/dtd/jboss-web_3_2.dtd">  
  6.   
  7. <jboss-web>  
  8.   
  9.    
  10.   <security-domain>java:/jaas/JBossWS</security-domain>  
  11.    
  12.     
  13.   <context-root>jbossws</context-root>  
  14.   
  15. </jboss-web>  


The default user name and password are kermit/thefrog

To change this, go to:

/usr/share/jboss-6.0.0.Final/server/default/conf/props

Open jbossws-roles.properties in a text editor it should appear as below.


  1. # A sample roles.properties file for use with the UsersRolesLoginModule  
  2. kermit=friend  


Change 'kermit' to a new user name. For example, we'll change it to 'mywsuser' as shown below:


  1. # A sample roles.properties file for use with the UsersRolesLoginModule  
  2. mywsuser=friend  


Open jbossws-users.properties in a text editor it should appear as below.


  1. # A sample users.properties file for use with the UsersRolesLoginModule  
  2. kermit=thefrog  


Change 'kermit' to our new user name 'mywsuser' and change the password. For example, we'll change the password to it to 'MyWsPassword' as shown below:


  1. # A sample users.properties file for use with the UsersRolesLoginModule  
  2. mywsuser=MyWsPassword  



Step 11: Set JAVA_OPTS Memory Parameters


To set the memory limits for JBoss, go to: /usr/share/jboss-6.0.0.Final/bin

Open the run.sh file in a text editor.

Find the section below:


  1. # Setup JBoss specific properties  
  2. JAVA_OPTS="-Dprogram.name=$PROGNAME $JAVA_OPTS"  


Directly below this, add the desired parameters.


  1. # Setup JBoss specific properties  
  2. JAVA_OPTS="-Dprogram.name=$PROGNAME $JAVA_OPTS"  
  3. JAVA_OPTS="$JAVA_OPTS -Xms128m -Xmx256m"  


I'm installing this on a small VPS so I'm using JAVA_OPTS="$JAVA_OPTS -Xms128m -Xmx256m". You should set this to whatever is appropriate to your server and application.


Step 12: Running JBoss on Port 80.


To run services below port 1024 as user other than root, you can use port forwarding.

You can do this by adding the following to your IP tables:


  1. [root@sv2 ~]# iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080  
  2. [root@sv2 ~]# iptables -t nat -A PREROUTING -p udp -m udp --dport 80 -j REDIRECT --to-ports 8080  

Friday, July 6, 2012

Jboss Interview Questions & Answers

Q: - What is Jboss ?

JBoss is a popular open source application server based on JEE technology.
Being JEE based, the JBoss supports cross-platform java applications.
It was embedded with Apache Tomcat web server. It runs under any JVM of 1.3 or later versions. JBoss supports JNDI, Servlet/JSP (Tomcat or Jetty), EJB, JTS/JTA, JCA, JMS, Clustering (JavaGroups), Web Services (Axis), and IIOP integration (JacORB).

Q: - What is JBoss cache ?

JBoss cache is a product. Frequently accessed Java objects are cached by utilzing JBoss cache to improve the performance of e-business applications. JBoss decreases the network traffic and increases the scalability of applications by eliminating unnecessary database acces.Fully transactional features and highly configurable set of options which are to deal with concurrent data access, are provided by JBoss cache in an efficient manner possible for the applications.


Q: - What is JBoss JBPM?

JBoss JBPM is a workflow and BPM engine. Enabling the creation of business processes that coordinates between people, applications and services is the functionality of BPM engine. The combination of workflow applications development with process design is a feature of JBoss jBPM. The business process is graphically represented to facilitate a strong link between the business analyst and technical developer. This feature is provided by the JBoss jBPM process designer.


Q: - How do you monitor JBoss and detect the bottleneck of an application?

Different components of the application are to be measured. This step is to find where the degradation is, whether it is external or internal and where is the appliciation spending all the time. Using Joss JMX agents and monitoring the deployed components to the application server involves in the first step. After finding the most of the time spent by specific components or libraries or most of the resources, one can use Jprobe a specialized tool for examining the single object or the objects loaded in the memory.

Q: - Describe the use of "instanceof" keyword.

"instanceof" keyword is used to check what is the type of object.




Q: - What is an Applet?

An applet is a small server side application that can be loaded and controlled on the browser by the client application. An applet has limited access to resources in order to ensure security.



Q: - What's the difference between servlets and applets?

Servlets executes on Servers while Applets executes on browser, Unlike applets, servlets have no graphical user interface.



Q: - If you have defined a web service that needs to transfer quite a lot of information, how would you do ?

You might consider using an attachment to transfer the information.Jboss JAX-WS Web services provides Attachment support with MTOM (Message Transmission Optimization Mechanism) SOAP.



Q: - Does Seam run on other application servers besides JBoss ?

Seam runs beautifully on other application servers - just like everything else the Hibernate team does, this is not a JBoss-only thing.

Wednesday, July 4, 2012

How to configur JBoss mail service ?

how to use the Java Mail service from JBoss AS, either connecting to a local SMTP server or using Google SMTP server. The JBoss Mail subsystem configures a JavaMail session binding into JNDI.  Let's start at first with JBoss AS 7 configuration. Open your AS 7 configuration file (standalone.xml/domain.xml) and find the following line:



<subsystem xmlns="urn:jboss:domain:mail:1.0">
    <mail-session jndi-name="java:jboss/mail/Default">
          <smtp-server outbound-socket-binding-ref="mail-smtp"/>
    </mail-session>
</subsystem>
 
 
The Session is bound to the following host and port:
 
 
 
<outbound-socket-binding name="mail-smtp">
   <remote-destination host="localhost" port="25"/>
</outbound-socket-binding>
 
 
 

Adding support for User Authentication:

As most of mail servers requires user authentication we will at first add login information by adding the <login> element:




<subsystem xmlns="urn:jboss:domain:mail:1.0">
    <mail-session jndi-name="java:jboss/mail/Default">
         <smtp-server outbound-socket-binding-ref="mail-smtp">
              <login name="fmarchioni" password="fmarchioni"/>
        </smtp-server>
    </mail-session>
</subsystem>
 
 
 
 
 
 
Now let's configure a mail server which will deliver our mails. You can try Apache James
 which is an opensource mail server, pretty light and simple to get 
started with it. Download it. Next unzip it and launch the run script 
which will start the mail server.

At startup James server just contains an administrative root account, so we will use this to add an user account. Unfortunately James does not provide (as far as I know!) a GUI interface to add users, to do that, telnet to localhost on port 4555 with the command:
telnet localhost 4555

You can log in with the root user name and password. After the login, we'll add an user. The adduser command expects a username and password combination. After adding users, you can use the listusers command to verify the entries and then exit the remote manager by typing quit. The whole session should look like this:
jboss mail service jboss mail service
Now let's create a simple Servlet which uses the Java Mail session to send a mail:




package com.sample;
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.annotation.Resource;

@WebServlet(value="/mail")
public class SendMail extends HttpServlet
{
    @Resource(mappedName="java:jboss/mail/Default")
    private Session mailSession;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        {

            PrintWriter out=response.getWriter();
            try    {
                MimeMessage m = new MimeMessage(mailSession);
                Address from = new InternetAddress("senderemailaddress.com");
                Address[] to = new InternetAddress[] {new InternetAddress("receiveremailaddress.com") };

                m.setFrom(from);
                m.setRecipients(Message.RecipientType.TO, to);
                m.setSubject("JBoss AS 7 Mail");
                m.setSentDate(new java.util.Date());
                m.setContent("Mail sent from JBoss AS 7","text/plain");
                Transport.send(m);
                out.println("Mail sent!");
            }
            catch (javax.mail.MessagingException e)
            {
                e.printStackTrace();
                out.println("Error in Sending Mail: "+e);
            }
        }
    }
}
 
As you can see this Servlet injects the Java Mail Session using the Java EE @Resource annotation:
@Resource(mappedName="java:jboss/mail/Default")
private Session mailSession;

Fairly simple. Now test your servlet before moving to the next section.

Sending mail to a Remote GMail server

You can slighty change your configuration to use your GMail server account. The only tricky part of it is that it requires enabling the TLS/SSL transport, otherwise the GMail server will refuse to accept your connection.
In earlier JBoss AS version, you needed to set the mail.smtp.starttls.enable to true, in order to enable secure connection.
When using JBoss AS 7, you need to set the ssl property of the smtp server element. Here's a sample configuration:


<mail-session jndi-name="java:jboss/mail/Default">
    <smtp-server ssl="true" outbound-socket-binding-ref="mail-smtp">
                 <login name="yourusergmail.com" password="password"/>
    </smtp-server>
</mail-session>
. . . .
<outbound-socket-binding name="mail-smtp">
    <remote-destination host="smtp.gmail.com" port="465"/>
</outbound-socket-binding> 
 
 

JBoss AS 5/6 Mail configuration

In earlier releases of JBoss application server, you can configure the Java Mail service by dropping a mail-service.xml into the deploy folder.
Here's a sample configuration which uses an unauthenticated session:


<server>
  <mbean code="org.jboss.mail.MailService"
         name="jboss:service=Mail">
    <attribute name="JNDIName">java:/Mail</attribute>
    ...
    <attribute name="Configuration">
      <configuration>
        ...
        <property name="mail.smtp.host" value="localhost"/>
        <property name="mail.smtp.port" value="25"/>
        ...
      </configuration>
    </attribute>
    ...
  </mbean>
</server>
 
 

Adding support for user authentication:

You can follow the procedure we have exposed for AS 7 to create an user on your James server: the configuration would change to:


<server>
  <mbean code="org.jboss.mail.MailService"
         name="jboss:service=Mail">
    ...
       <attribute name="User">fmarchioni</attribute>
        <attribute name="Password">fmarchioni</attribute>   
        <attribute name="JNDIName">java:/Mail</attribute>
        <attribute name="Configuration">
      <configuration>
        ...
        <property name="mail.smtp.host" value="localhost"/>
         <property name="mail.smtp.port" value="25"/>
        <property name="mail.smtp.auth" value="true"/>
        <property name="mail.smtp.user" value="fmarchioni"/>
        ...
      </configuration>
    </attribute>
    ...
  </mbean>
</server>
 
 
 

Adding support for SSL/TSL:

Finally, if you want to enable SSL/TSL transport (as for GMail accounts) just add the following MBean configuration:



<server>
   <mbean code="org.jboss.mail.MailService"
          name="jboss:service=Mail">
     ...
     <attribute name="User">fmarchioni</attribute>
     <attribute name="Password">fmarchioni</attribute>
    <attribute name="JNDIName">java:/Mail</attribute>
     <attribute name="Configuration">
       <configuration>
         ...
        <property name="mail.smtp.host" value="smtp.gmail.com"/>
        <property name="mail.smtp.auth" value="true"/>
        <property name="mail.smtp.port" value="465"/>
        <property name="mail.smtp.starttls.enable" value="true"/>
        <property name="mail.smtp.socketFactory.class" value="javax.net.ssl.SSLSocketFactory"/>
        ...
      </configuration>
    </attribute>
    ...
  </mbean>
</server>
 
 
 
 

 

 

 

 

 

 

How do I configure a Queue/Topic to work in a cluster in JBoss?

JBoss AS 5
Just set the Clustered attribute to "true" in your Queue/Topic definition. Here's a Queue example: 


<mbean code="org.jboss.jms.server.destination.QueueService"
     name="jboss.messaging.destination:service=Queue,name=SampleQueue"
     xmbean-dd="xmdesc/Queue-xmbean.xml">
     <depends optional-attribute-name="ServerPeer">jboss.messaging:service=ServerPeer</depends>
     <depends>jboss.messaging:service=PostOffice</depends>
     <attribute name="Clustered">true</attribute>

  </mbean>

How to secur JBoss server?

Security is a fundamental part of any enterprise application .The JBoss component framework that handles security is the JBossSX extension framework. The JBossSX security extension provides support for both the role-based declarative J2EE security model as well as integration of custom security via a security proxy layer.

The default implementation of the declarative security model is based on Java Authentication and Authorization Service (JAAS) login modules and subjects.

JAAS delivers a framework for providing authentication and authorization for all the Java applications.

 
Authentication is a mechanism to verify the client
 

 
Authorization is a mechanism to ensure that the client has the permissions required to access a secured resource.
 


The four steps to enable JAAS:

1. Identify which resources needs to be secured: a Web Application ? an EJB ?

2. Identify a suitable Security Provider. In the case of JBOSS, the security is provided by the JBOSS security manager.

3. Use a Security Implementation to secure the identified resources.

4. Make the clients of the secured resources aware of the security implementation and usage mechanisms

The LoginModule


The JBOSS application server provides pluggable security managers. The Web and the EJB Containers use the security managers to perform authentication and authorization. The JAAS-based security manager is the default security manager provided with JBOSS

The LoginModule is the module is in charge to provide the security implementation that authenticates and authorizes the clients. A typical implementation involves validating the username/password combination

JBOSS provides some Login Modules out of the box :
  • UserRolesLoginModule: This is the default login module : it reads the username, password and role information from files that are packaged with the applications.
  • DatabaseServerLoginModule: This module reads the username, password and role information from the tables in a database. The database is accessed using JDBC and the JDBC driver needs to be available in the application classpath.
  • LDAPLoginModule: This module requires the username and password. This is used to connect to LDAP as a means of verification. If successful, the roles are based on the group memberships of the user. This module is not very configurable as it doesn’t expose enough configuration options to work with all LDAPs.
  • BaseCertLoginModule: This module uses client certificates to perform authentication. It cannot provide role information. This is typically used in conjunction with one of the other LoginModules to obtain the role memberships

Securing a Web Application with UserRolesLoginModule


In this first tutorial we'll explore how to secure a Web application and an EJB application using the UserRolesLoginModule
 
Step 1: Add the Security Policy to your conf/login-config.xml



<application-policy name = "jboss-secure">



   <authentication>
   <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
 flag = "required">
     <module-option name="usersProperties">users.properties</module-option>
     <module-option name="rolesProperties">roles.properties</module-option>
   </login-module>
   </authentication>
</application-policy>








This tells JBoss to associate the UserRolesLoginModules for the policy named "jboss-secure".
Note: Security domains are created on demand. Putting an entry in login config.xml doesn't have any effect until an application tries to use it.

Step 2: Add security constraints to web.xml 

<security-constraint>

   <web-resource-collection>
     <web-resource-name>Restricted to Secure role</web-resource-name>
     <description>Declarative security</description>
     <url-pattern>/*</url-pattern>
     <http-method>HEAD</http-method>
     <http-method>GET</http-method>
     <http-method>POST</http-method>
   </web-resource-collection>

   <auth-constraint>
     <role-name>Administrator</role-name>
   </auth-constraint>

 </security-constraint>

 <login-config>
   <auth-method>BASIC</auth-method>
   <realm-name>JBoss Secured Realm</realm-name>
 </login-config>

 <security-role>
   <role-name>Administrator</role-name>
 </security-role>
 



In this sample all resources of the web application are restricted to the "Administrator" role. Now you need only

Step 3: Add security domain to your jboss-web.xml




<jboss-web>

  <security-domain>java:/jaas/jboss-secure</security-domain>

</jboss-web>
 



Last configuration file is JBoss web's deployment descriptors. This file is by default under the WEB-INF folder. To link to a specific security domain, you need to set the security-domain element to the JNDI name of the security domain to link to. Security domains are bound under java:/jaas in JNDI, so the todo domain would be java:/jaas/jboss-secure.

Step 4: Add users.properties and roles.properties

Usernames and password are stored in users.properties file (you can place it anywhere JBoss classloader can reach it for example under WEB-INF/classes)

The minimalist user.properties file can be:

admin=admin

The roles.properties associate the usernames to Security Roles.

The minimalist roles.properties file can be:

admin=Administrator




Securing an EJB Application 


Securing the EJB tier is not much different: the server configuration stays the same, we need to group the EJB methods based on the roles that can access these methods.

Step 1: add <method-permission> tag in the ejb-jar.xml file. 





<method-permission> 
   <role-name>Administrator</role-name> 
   <method> 
     <ejb-name>SampleEJB</ejb-name> 
     <method-name>securedMethod</method-name> 
   </method> 
</method-permission> 
<method-permission> 
   <unchecked/> 
   <method> 
     <ejb-name>SampleEJB</ejb-name> 
     <method-name>unsecuredMethod</method-name> 
   </method> 
</method-permission> 
 
 
 
 
In the above example, the method “securedMethod” in the EJB “SampleEJB” is available only to the
client belonging to the “Secure” role. However, the method “unsecuredMethod” in the same bean is available to all the clients.

Step 2: Add security domain to your jboss.xml

During the application packaging, the administrator must choose the security domain used to protect
the application. This is exaclty the same as for the web tier except that the EJB tier uses another d.descriptor file called jboss.xml.
<jboss>
<security-domain>java:/jaas/jboss-secure</security-domain>
</jboss>
 
 




 

JBoss start up configuration - Setting Server properties using the Properties Service

Setting Server properties using the Properties Service


One cool way to add a list of System properties to JBoss is the Properties MBean Service.
In the deployment folder look for "properties-service.xml". (if you don't have it in your release you can create it at any time) :

Now add your properties either in the URLList Attribute or in the Properties Attribute:


<server>
    <mbean code="org.jboss.varia.property.SystemPropertiesService"
      name="jboss:type=Service,name=SystemProperties">

    <attribute name="URLList">
      http://somehost/some-location.properties,
        ./conf/somelocal.properties
    </attribute>

    <attribute name="Properties">
       property1=This is the value of my property
       property2=This is the value of my other property
    </attribute>

</server>



As you can see the The "URLList" is a comma-separated list of URL strings from which to load properties file-formatted content while the "Properties" is a specification of multiple property name=value pairs

Now you can access your properties with standard:

System.getProperty("property1");


Logging the startup process


JBoss uses the Log4jService (in JBoss AS 5.x and earlier) or the LoggingService (in JBoss AS 6.x and later) to configure logging.

However this service is not configured until after the bootstrap phase.

During the bootstrap the microkernel logs into log/boot.log using the configuration defined in log4j.properties (in 5.x and earlier) or logging.properties (in 6.x and later) contained in $JBOSS_HOME/bin/run.jar.


If you want to customize the boot loggin you have basically two options:
  • Change the configuration inside run.jar 
  • Use a system property to reference an outside configuration file.

The simplest strategy is to un-jar $JBOSS_HOME/bin/run.jar, change the appropriate properties file and re-jar. (We suggest you using the Open Source archiving software 7-zip which does a good job at editing files inside of archives).

Alternatively, you can also specify the boot log configuration at the command line, instead of editing run.bat/run.sh, for example:



run.bat -Dlog4j.configuration=file:./log4j.properties

or for the release 6.x :



run.bat -Dlogging.configuration=file:./logging.properties

How to set up JBoss start up configuration ?

you need to know about the startup process of JBoss AS, how to inject system properties in the application server and how to trace the logs of the start up activities.

How to start the JBoss AS


Starting the application server is just a matter of launching the start.cmd (Windows) or start.sh (Unix) script.

You can however customize the server startup using several parameters:


The option -b can be used to bind all server services to an IP Address.

For example:


run.sh -b 192.168.10.1        # Bind the server on the IP Address 192.168.10.1
run.sh -b 0.0.0.0                   # Bind the server on all network interfaces


The option -c can be used to choose which server configuration will be started. If not used the "default" will be chosen.

For example:


run.sh -c all                 # Starts the "all" server configuration


The options -B can be used to add an extra library to the front bootclasspath
This is equivalento to dropping a jar library into $JBOSS_HOME/lib.


The options -L can be used to add an extra library to the loaders classpath

This is equivalento to dropping a jar library into $JBOSS_HOME/common/lib.


You can set a system property through the
-D<name>=<value> option. You can also use the -P option to load the properties from a file.

Example:
Create a file named test.properties


jboss.bind.address=0.0.0.0
jboss.service.binding.set=ports-default

launch JBoss AS with:

run.cmd -P test.properties

Applications using JGroups library might benefit from the -m and -u option.

-m sets the UDP multicast port; only used by JGroups. -u sets the UDP multicast address



More about JBoss ?

What is JBoss ? JBoss Application Server (or JBoss AS) is a free software/open-source Java EE-based application server. An important distinction for this class of software is that it not only implements a server that runs on Java, but it actually implements the Java EE part of Java. Because it is Java-based, the JBoss application server operates cross-platform: usable on any operating system that supports Java. JBoss AS was developed by JBoss, now a division of Red Hat.

Important notice: This tutorial covers the releases 4-5-6 of the application server. If you want to check the latest AS 7 version, we suggest you looking at the following tutorial
JBoss application server can be freely downloaded from the Community site http://www.jboss.org/jbossas/downloads/
The installation of JBoss is simply a matter of extracting the compressed archive into a folder.

In order to start up JBoss correctly, you have to define the environment variable JAVA_HOME to the location where you have installed Java.

After you have installed JBoss, perform a simple startup test to validate that there are no problems with your Java VM/operating system combination. To test your installation, move to the bin directory of your JBOSS_HOME/bin directory and issue the following command:

run.bat    # Windows users
$ run.sh   # Linux/Unix users

JBoss AS 5-6 configuration:

Let's have a look at the application server folders for the releases 5 and 6:
what is jboss
Here's a description about the single folders:
bin This directory contains the scripts necessary to start-up and shutdown the server. This folder also contains some scripts (like twiddle) there are a few utilities for web services and server management
client This directory contains the client libraries needed to run client applications
common This directory contains the lib folder which is the new repository for the common libraries used by all application server configurations.
docs This folder contains the xml schemas used by the various xml configuration files and useful JMS, JTA and Datasource configuration examples which can be used as templates
lib This is the repository for all JBoss bootstrap libraries. Here is the new Micro-container along with earlier JMX  kernel
server This directory is the home of all server configurations. Here you can find the built-in server configurations (minimal, default, standard, web and all). Each server configuration contains the following directories in the next table
Place in the folder common/lib the libraries which are shared between all your server configuration

JBoss 5 and 6 available server configurations:


JBoss 5 and 6 ship with a set of pre-built server configurations. Most of the time you'll need to use the "default" configuration for single node applications and "all" for clustered applications. Here's anyway a description of each configuration:

The "default" configuration:

This is the basic JBoss configuration containing a default set of services. It has the most frequently used services required to deploy a JEE application. It does not include the JAXR service, the IIOP service, or any of the clustering services.

The "all" confuguration:

This configuration is a full JEE server profile with enterprise extensions such as Clustering and RMI/IIOP.
Inside each server configuration there's one more level containing the single server configuration and deployed artifacts. Here' s the next level:

The "standard" configuration:


The standard folder hosts the configuration that has been tested for Java EE 5.0 compliance. The major differences with the other server existing configurations is that call-by-value and deployment isolation are enabled by default, along with support for RMI-IIOP and jJUDDI. .

The "web" configuration

The "web" configuration is a new experimental lightweight configuration created around JBoss Web that will follow the developments of the Java EE 6 web profile. Besides being a servlet/jsp container (and this is the most relevant difference with a pure Ttomcat  Web Server), it provides support for JPA and JTA/JCA.

The "minimal" configuration

This is the has a minimal configuration—the bare minimum services required to start JBoss. It starts the logging service, a JNDI server and a URL deployment scanner to find new deployments. This is what you would use if you want to use JBoss to start your own services without any other JEE technologies. This is just the bare server. There is no web container, no EJB or JMS support. This is not a JEE compatible configuration.

Inside each server configuration there's one more level which contains the configuration folders, the deployment folder and others. Here's a table which resumes the server structure:

conf This is the configuration directory of the single server configurations.
data The data directory is a location available for use by services that want to store content in the file system
deploy The default location for deployment of JBoss services
deployers Contains all the JBoss AS services that are used to recognize and deploy different application and archive types
lib This folder used to contain the common libraries of all applications. You can use this directory for storing configuration-specific libraries
log The default directory into which the bootstrap logging service places its logs
tmp The location to which deployments are copied for local use
work Used by JBoss Web Server (the web container that comes prepackaged with JBoss AS) to store compiled JSP files and other temporary data.

JBoss AS 4 configuration

Let's have a look at the application server folders for the release 4:
what is jboss
Here's a description about the single folders:
bin This directory contains the scripts necessary to start-up and shutdown the server. This folder also contains some scripts (like twiddle) there are a few utilities for web services and server management
client The JARs that are required for clients that run outside of JBoss are located in this directory.
docs This folder contains the xml schemas used by the various xml configuration files and useful JMS, JTA and Datasource configuration examples which can be used as templates
lib This is the repository for all JBoss bootstrap libraries.
server The JBoss server configuration sets are located under the server directory. The default server configuration set is the server/default set. JBoss ships with minimal, default and all configuration sets.
Inside each server configuration there's one more level which contains the configuration folders, the deployment folder and others. Here's a table which resumes the server structure:
conf The conf directory contains the jboss-service.xml bootstrap descriptor file for a given server configuration. This defines the core services that are fixed for the lifetime of the server.
data The data directory is a location available for use by services that want to store content in the file system
deploy The default location for deployment of JBoss services
lib This is the default location for static Java libraries that should not be hot deployed. All JARs in this directory are loaded into the shared classpath at startup.
log The log directory is the directory log files are written to. This may be overridden through the conf/log4j.xml configuration file.
tmp The location to which deployments are copied for local use

How to configuration log4j to JBoss?

JBoss AS uses log4j as logging framework. This tutorial will show how to configure log4j service in your jBoss application server and also how to create a custom configuration which can be deployed along with your application.

Log4j is a flexible open source project from Apache. Using Log4j, we can replace the debugging print line statements with configurable logging statements.

The advantage in using Log4j is, if you do not want to print the debugging print lines in production application, you can easily switch them off using Log4j configuration file.

At first let's see where Log4j configuration file is located:
 
In the releases 4.x and 5.x it's located here:JBoss_HOME\server\default\conf\jboss-log4j.xml
Since the release 6.0.0 M1 it's located in the deploy folder: JBOSS_HOME\server\default\deploy\jboss-logging.xml
 

Let's have a look at a minimal configuration:
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">


<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

    <appender name="FILE" class="org.jboss.logging.appender.DailyRollingFileAppender">
        <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
        <param name="File" value="${jboss.server.log.dir}/server.log"/>
        <param name="Append" value="false"/>

        <param name="DatePattern" value="'.'yyyy-MM-dd"/>

        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
        </layout>
    </appender>


    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
        <param name="Target" value="System.out"/>
        <param name="Threshold" value="INFO"/>

        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>
        </layout>
    </appender>


    <category name="com.sample">
        <priority value="INFO"/>
    </category>


    <root>
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>

</log4j:configuration>


As you can see, the configuration file can be basically split in two areas:
Appender: this is the class file which directs the actual logging to a destination. It could be a simple Console appender which dumps the log messages to stdout (screen) or a file appender, which sends the log messages to a log file

Category: (formerly known as Logger) connects the classes from a package to one or more appenders.

In our example, we have defined 2 appenders: one which logs statements to the Server console (equivalent to the System.out) and another which uses a DailyRollingFileAppender to append logs to the file server.log.

We have also added a category definition (for the package com.sample) which specifies the minimum priority of messages that will be generated. The purpose of the categories is to limit the log messages produced by components to a level that makes sense. (Note In our example the message doesn't show up on the console since the threshold on the console is INFO)

The last part of the configuration is the Root logger. All loggers which are not defined through a category, inherit from the Root logger which collects messages from both the CONSOLE appender and the FILE appender.

JBoss's log4j specific configuration


Log4j configuration is handled by the MBean org.jboss.logging.Log4jService. You can configure it in the JBOSS_HOME/server/default/conf/jboss-service.xml file.
<mbean code="org.jboss.logging.Log4jService"
name="jboss.system:type=Log4jService,service=Logging"
xmbean-dd="resource:xmdesc/Log4jService-xmbean.xml">
<attribute name="ConfigurationURL">resource:jboss-log4j.xml</attribute>

<attribute name="Log4jQuietMode">true</attribute>
<attribute name="RefreshPeriod">60</attribute>
</mbean>
Here, you can configure the log4j resource name (jboss-log4j.xml) and the RefreshPeriod, which states how frequently in seconds the ConfigurationURL is checked for changes.

Using log4j in your application


Once you have configured the main log4j configuration file you don't need adding any library since log4j JBoss AS already ships with all the necessary libraries.

Just define a static org.apache.log4j.Logger instance and link it to your class. For example in an HelloWorld class you would log this way:
 import org.apache.log4j.Logger

public class HelloWorld {

 static Logger logger = Logger.getLogger(HelloWorld.class);
 // ...

  public void doSomething() {
   logger.debug("This is a debug statement");
  }
}

Creating a custom appender


The sample configuration can be furtherly expanded by defining new appenders or categories. For example, if you want to append your application specific logs to another file, you you can define a new File appender so that application logs don't mix the server-related File appender.
 <appender name="CUSTOM"
 class="org.jboss.logging.appender.DailyRollingFileAppender">
  <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
  <param name="File"        value="${jboss.server.home.dir}/log/custom.log"/>
  <param name="Append"      value="false"/>
  <param name="DatePattern" value="'.'yyyy-MM-dd"/>
  <layout class="org.apache.log4j.PatternLayout">
  <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
 </layout>
</appender>
This appender will be picked up by the Root category or by a custom defined category as in this sample:
<category name="com.sample">
  <priority value="DEBUG" />
  <appender-ref ref="CUSTOM"/>
</category>
Here, all logs emitted by the package com.sample with a priority DEBUG or higher will use the CUSTOM appender.

Using a custom log4j configuration file


The above configuration requires that you adapt the JBoss log4j file to your needs. This is not usually the best option because you should rather provide a custom configuration along with your application.

If you have already tried to pack log4j configuration along with your application, you might be disappointed that it doesn't emit any logging statement. Why ? since the log4j framework is already packed in the server lib and configuration you need to deploy your application in isolate classloader mode so that it doesn't conflict with the server logging system.

(If you want to read more about isolating classloader you might check this article: http://www.mastertheboss.com/en/jboss-application-server/141-jboss-classloader.html )

Isolating your application requires a simple three step process:

1) Add a jboss-web.xml (Web application) or jboss-app.xml (Enterprise App) declaring claassloader isolation
2) Add the log4j.jar along with your application ( because it will not be loaded anymore from the server lib )
3) Add the log4j.xml (or log4j.properties) to your application

Let's see how you need to pack your Web application in order to use a custom log4j configuration (ScreenShots from Eclipse)

jboss log4j tutorial logging configuration
As you can see we have packed the configuration file (jboss-log4j.xml) in the src folder, so that it will be moved to the WEB-INF/classes folder once we distribute the application.

The file log4j.jar is added in the Web application library.

Finally we need to add in the WEB-INF folder the jboss-web.xml declaring the classloader isolation. Here's an example:
<jboss-web>  
  <class-loading java2ClassLoadingCompliance="false">
   <loader-repository>org.myapp:loader=MyClassLoader
    <loader-repository-config>java2ParentDelegation=false</loader-repository-config>
   </loader-repository>
  </class-loading>
</jboss-web>
The same steps can be performed on an Enterprise Archive- the main difference will be that we need rather a jboss-app.xml file to declare classloader isolation. You also need to pack log4j.jar in the "lib" folder of your .ear and your configuration file in the root of your .ear.

Here's eclipse screenshot:

jboss log4j eclipse configuration
Here's a sample jboss-app.xml file:
<jboss-app>
<loader-repository>org.myapp:loader=MyClassLoader
<loader-repository-config>java2ParentDelegation=false</loader-repository-config>
</loader-repository>  
</jboss-app>
JBoss 5 Classloader issue

The AS5 deployers ignore the previous classloader configuration just defined. Instead, for a  scoped deployment, users will be required to create a META-INF/jboss-classloading.xml:
<classloading xmlns="urn:jboss:classloading:1.0" domain="simple-scoped"

parent-first="false" />