Run JBoss AS 7 as a service in Ubuntu


Hi, today I’m going to present a few simple steps to configure and run JBossAS 7 as a sevice.

This was tested with JBossAS 7 on Ubuntu 14.04, but it should work in other versions also.

First of all, create a file in /etc/init.d/, which is the script for the service. This folder contains all the scripts that should run on startup of a linux instance.

After that, insert the following code, which defines the start and stop commands for the service.
You should replace the variable JBOSS_HOME with your local jboss install folder.
This will run the jboss as a service using the root user, you can change the commands accordingly to run as a different user.

After this, the only thing remaining is to define when the service will start and shutdown.
Simply run the following two lines

The first line enables execution of the created file. The…

View original post 29 more words

Disable response schema validation CXF on JBoss 7.1

JBoss 7.1 ships with a new framework for Web services from Apache, called CXF.
This framework, when consuming SOAP web services, validates by default all responses against the provided wsdl.

Sometimes that behavior is not required because of several reasons. For example, the WSDL may change from time to time, adding attributes to the response, which won’t affect the current behavior of the application, or maybe from a performance perspective, since this validation requires an additional step in each request.

Making a long story short, to disable the schema validation for all SOAP responses, the standalone.xml should be edited, adding the following tag inside

<client-config name="Standard-Client-Config">
  <property name="set-jaxb-validation-event-handler" value="false"/>

This configuration disables the validation for all web service clients deployed in the server.

If this is too much for you, you can disable validation programatically only for the clients you need, adding the following line before calling the web service:

((BindingProvider) wsClient).getRequestContext().put("set-jaxb-validation-event-handler", "false");

Maven y conflictos entre dependencias

Compañeros, compañeras:

Comparto mi experiencia con maven para que nadie vuelva a sufrir lo que he sufrido yo..

Resulta que el maven me estaba generando un paquete y al ejecutarlo, me daba error porque no encontraba una clase. Mirando el ear generado, efectivamente veía en la carpeta lib, el jar con la clase que no estaba pudiendo encontrar.
Hete aquí, que no entendía por qué no la veía!
Mirando un poco más, vi que me estaba agregando también una librería con nombre distinto, pero se correspondía a una versión anterior, a nombrar, me estaba trayendo las librerías bcprov-jdk14 y bcprov-jdk15.
Primero, se ve que jboss cargaba la 14 y no le daba bolilla a la 15. Después que me di cuenta de eso, supe que tenía que eliminar la 14.
Ahora, cómo hago para saber quién estaba trayendo esa versión!? Yo estaba agregando a mano la 15 como dependencia, pero la otra.. ni idea.
Para eso, maven tiene un target mágico… ejecutando:
mvn dependency:tree
Te dice clarito qué dependencias tenés y el árbol de dependencias de cada uno de esos.
Pude identificar el que me estaba trayendo (era jasperreports). Luego de eso, solo falta agregar la regla de exclusión para que no traiga las librerías que dan conflicto, y listo!
La dependencia de jasperreports quedó así:


How to use Log4J in ejb module in Jboss7.1

JBoss 7.1 already ships with Log4J, but the config is somehow different from previous versions of the server.
The same Log4J architecture applies, you have appenders and categories, but the config files are different, so I’ll explain how to configure a new category and appender for this.

When developing your EJB you need to:

  1. import the Logger class: import org.apache.log4j.Logger;
  2. If the import does not resolve, add this jar to the path: %JBOSS_HOME%\modules\org\apache\log4j\main\log4j-1.2.16.jar
  3. create a field with the logger: private static Logger logger = Logger.getLogger(YourEJBClass.class);
  4. use the logger in any method:"my log");

JBoss already comes with a configuration file under %JBOSS_FOLDER%/standalone/configuration/standalone.xml. By default, your logger will output to server.log and console, but you can add some appender to output your app logs to another file.

Here is an example, edit that file and add the following snippets (following the definition of the file):

  • This one is to add an appender to the file myappfile.log inside the logs folder (add this right after the already defined under name=”FILE”):
     <periodic-rotating-file-handler name="FILETWO">
         <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
       <file relative-to="jboss.server.log.dir" path="myappfile.log"/>
       <suffix value=".yyyy-MM-dd"/>
       <append value="true"/>
  • Add this snippet tells log4j to send all logs from “com.mypackage” category to the previously created appender (copy this right after other defined logger in the file, but before the root-logger):
     <logger category="com.mypackage">
         <level name="DEBUG"/>
             <handler name="CONSOLE"/>
             <handler name="FILETWO"/>

Restart the server and you should see the new myappfile.log in the folder. Make sure your app logs something, for example, adding“my servlet info log”) in some servlet and call it from the browser. You’ll also see this log in the console

If you need further customization, have a look at log4j help.

Using LdapExtLoginModule with JaasSecurityDomain (securing passwords)

In my last post I wrote about how to connect a JBoss to LDAP defining an LdapExtLoginModule. Clearly, as suggested by the comment of Terry, the password in the xml is in plain text. In this post I’ll explain how to secure this password.

This is really easy to do as suggested in the JBoss docs, just add the following xml to the file $JBOSS_HOME/server/$PROFILE/conf/jboss-service.xml, which will add a JaasSecurityDomain bean to the jmx-console, which will be available for encrypting passwords in Base64:

  <mbean code=""
         <arg type="java.lang.String" value="jmx-console"></arg>
      <attribute name="KeyStorePass">some_password</attribute>
      <attribute name="Salt">abcdefgh</attribute>
      <attribute name="IterationCount">66</attribute>

After this, start the JBoss server and navigate to the JMX Console (http://localhost:8080/jmx-console/ by default) and select the MBean.

On the page, look for the encode64(String password) method. Pass the plain text version of the password being used by the LdapExtLoginModule to this method, and invoke it. The return value will be the encrypted version of the password encoded as Base64.

After this, open login-config.xml, edit the LdapExtLoginModule created previously, replacing the password with the encrypted one and tell the module that the password is in encrypted form. The policy should look have the following lines (adding the jaasSecurityDomain option and editing the bindCredential):

   <module-option name="jaasSecurityDomain">,domain=jmx-console</module-option>
   <module-option name="bindCredential">6gf.s7eQiJi</module-option> <!-- LDAP password:  -->

Restart the server and that’s it!

As we see, in this case, the keystore password is still as plain text in the jboss-service.xml file, but this password can be stored in a secure location, for example, using a keystore, as suggested in:

Authenticate JBoss application using JAAS and LDAP

It is very easy to connect a JBoss to an LDAP server and creating Java EE applications that use the LDAP information for authorization and authentication. Following these simple steps you will be able to configure your JBoss and a web application (configuring an ejb deployment is similar, just read the Java EE API to map the attributes from web.xml to ejb annotations).

For this example I already have an Apache Directory Server running locally, with the sample LDIF with the sevenSeas company imported. You can find the file and tutorial in the Apache DS documentation.

There are two main steps to be able to use LDAP as an authentication mechanism:

  1. Configure JBoss to connect to LDAP server
  2. Configure the application to use the application policy

Configure JBoss to connect to LDAP server

The JBoss connects to the LDAP server using an application-policy, which is configured in %server_path%/conf/login-config.xml
Just add the following entry in the login-config.xml. You can see the description of the important attributes:

  <application-policy name="ApacheDS">
   <login-module code="" flag="required" >
   <module-option name="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</module-option>
   <module-option name="java.naming.provider.url">ldap://localhost:10389</module-option> <!-- LDAP url-->
   <module-option name="">simple</module-option>
   <module-option name="bindDN">uid=admin,ou=system</module-option> <!-- LDAP user to connect -->
   <module-option name="bindCredential">secret</module-option> <!-- LDAP password -->
   <module-option name="baseCtxDN">ou=people,o=sevenSeas</module-option>
   <module-option name="baseFilter">(uid={0})</module-option>

   <module-option name="rolesCtxDN">ou=groups,o=sevenSeas</module-option> <!-- context where to search for groups -->
   <module-option name="roleFilter">(uniquemember={1})</module-option> <!-- filter, this searches for groups which have the user set in the attribute 'uniquemember' -->
   <module-option name="roleAttributeID">cn</module-option>
   <module-option name="searchScope">SUBTREE_SCOPE</module-option> <!-- Search for groups in all subtrees -->
   <module-option name="roleRecursion">0</module-option> <!-- how many levels to search recursively inside a group for a user  -->
   <module-option name="allowEmptyPasswords">true</module-option>

As you can see, the bindCredential is not encrypted. In order to do so, you can check out my post about securing the LdapExtLoginModule

Configure the web application to use the application policy

First, we need to connect the java web application to the application policy defined in JBoss. In order to do this, you need to create the file jboss-web.xml in the WEB-INF folder, the same folder where the web.xml resides.
Here is the content of the file (this works for JBoss 5 in a windows machine, you may need to change the header of the file):

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE jboss-web
    PUBLIC "-//JBoss//DTD Web Application 2.3V2//EN"


This will tell the container to use the ApacheDS application-policy we defined previously in JBoss.

After this, we only need to restrict the specific urls or servlets to certain roles. In this example, we will only allow access for users in the group “HMS Bounty”, otherwise a 403 (forbidden) will be issued.
In order to do this, we need to edit the web.xml file, adding the following configuration:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
 xmlns:xsi="" xsi:schemaLocation="">
 <!-- ... more servlets and config ...-->
  <display-name>All resources</display-name>
   <web-resource-name>All resources</web-resource-name>
   <role-name>HMS Bounty</role-name>


Following this example, you can restrict access to different resources to other roles.

Configure an EJB based WS to use the application policy

If, in turn, you want to secure an EJB based WS, just adding these annotations at the start of the implementing class will do:

@org.jboss.wsf.spi.annotation.WebContext(contextRoot="MyCtxRoot" , authMethod = "BASIC", secureWSDLAccess = false)
@org.jboss.ejb3.annotation.SecurityDomain( "java:/jaas/ApacheDS" )
@RolesAllowed("HMS Bounty")
public class MyWSImplementation implements MyWSInterface{

Search LDAP from Java

This post explains how to connect to an LDAP server (in my case Apache DS) and retrieve elements which match a certain filter.

I have deployed an Apache Directory Server version 2.0 and imported the demo LDIF containing users and groups for the “sevenSeas” organization. You can download the file from the apache DS documentation.

This java code connects to the Apache DS deployed locally using the default port and user, and searches the context “ou=groups,o=sevenSeas” for groups the user “Fletcher Christian” belongs to.

import java.util.Properties;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;

public class LdapSearch {
   public static void main(String[] args) throws NamingException {
      InitialLdapContext ctx = constructInitialLdapContext();
      // the name of the context to search
      String contextName = "ou=groups,o=sevenSeas";
      // Filter expression
      String filterExpr = "(uniquemember={0})"; // selects the groups a user belongs to.

      // Filter parameters (name of the user)
      String userDN = "cn=Fletcher Christian,ou=people,o=sevenSeas";
      Object[] filterArgs = { userDN };

      SearchControls constraints = new;
      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); // SUBTREE_SCOPE means recursive search

      NamingEnumeration<SearchResult> search =,
            filterExpr, filterArgs, constraints);
      while (search.hasMoreElements()) {

   private static InitialLdapContext constructInitialLdapContext()
         throws NamingException {
      Properties env = new Properties();
      // LDAP url
      env.put("java.naming.provider.url", "ldap://localhost:10389");
      // ldap login
      env.put("", "uid=admin,ou=system");
      env.put("", "secret");

      return new InitialLdapContext(env, null);


With the demo LDIF imported in Apache DS the output will be:

cn=HMS Bounty,ou=crews