Run JBoss AS 7 as a service in Ubuntu

rsisto's avatarKreitech

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"/>
</client-config>

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í:

<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>5.1.0</version>
<exclusions>
    <exclusion>
      <groupId>bouncycastle</groupId>
      <artifactId>bcprov-jdk14</artifactId>
    </exclusion>
    <exclusion>
      <groupId>org.bouncycastle</groupId>
      <artifactId>bcprov-jdk14</artifactId>
    </exclusion>
  </exclusions>
</dependency>
 
Saluditos!

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: logger.info("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">
       <formatter>
         <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
       </formatter>
       <file relative-to="jboss.server.log.dir" path="myappfile.log"/>
       <suffix value=".yyyy-MM-dd"/>
       <append value="true"/>
     </periodic-rotating-file-handler>
  • 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"/>
         <handlers>
             <handler name="CONSOLE"/>
             <handler name="FILETWO"/>
         </handlers>
     </logger>

Restart the server and you should see the new myappfile.log in the folder. Make sure your app logs something, for example, adding logger.info(“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="org.jboss.security.plugins.JaasSecurityDomain"
      name="jboss.security:service=JaasSecurityDomain,domain=jmx-console">
      <constructor>
         <arg type="java.lang.String" value="jmx-console"></arg>
      </constructor>
      <attribute name="KeyStorePass">some_password</attribute>
      <attribute name="Salt">abcdefgh</attribute>
      <attribute name="IterationCount">66</attribute>
   </mbean>

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

On the org.jboss.security.plugins.JaasSecurityDomain 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">jboss.security:service=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: https://community.jboss.org/wiki/JBossAS7SecuringPasswords

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">
   <authentication>
   <login-module code="org.jboss.security.auth.spi.LdapExtLoginModule" 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="java.naming.security.authentication">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>
   </login-module>
   </authentication>
  </application-policy>

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"
    "http://www.jboss.org/j2ee/dtd/jboss-web_3_2.dtd">

<jboss-web>
  <security-domain>java:/jaas/ApacheDS</security-domain>
</jboss-web>

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="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
  <servlet-name>AServlet</servlet-name>
  <servlet-class>com.app.AServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>AServlet</servlet-name>
  <url-pattern>/AServlet</url-pattern> 
 </servlet-mapping>
 
 <!-- ... more servlets and config ...-->
 
 <security-constraint>
  <display-name>All resources</display-name>
  <web-resource-collection>
   <web-resource-name>All resources</web-resource-name>
   <url-pattern>/*</url-pattern>
  </web-resource-collection>
  <auth-constraint>
   <role-name>HMS Bounty</role-name>
  </auth-constraint>
 </security-constraint>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>

</web-app>

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.directory.SearchControls;
import javax.naming.directory.SearchResult;
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 javax.naming.directory.SearchControls();
      constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); // SUBTREE_SCOPE means recursive search

      NamingEnumeration<SearchResult> search = ctx.search(contextName,
            filterExpr, filterArgs, constraints);
      while (search.hasMoreElements()) {
         System.out.println(search.next().getName());
      }
   }

   private static InitialLdapContext constructInitialLdapContext()
         throws NamingException {
      Properties env = new Properties();
      env.put("java.naming.factory.initial",
            "com.sun.jndi.ldap.LdapCtxFactory");
      // LDAP url
      env.put("java.naming.provider.url", "ldap://localhost:10389");
      // ldap login
      env.put("java.naming.security.principal", "uid=admin,ou=system");
      env.put("java.naming.security.credentials", "secret");

      return new InitialLdapContext(env, null);
   }

}

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

cn=HMS Bounty,ou=crews

Pattern detection with the camera | Detección de patrones con la cámara

(— Español al final —)

Multi pattern detection project

This time I’m presenting a software developed with my team for the Butiá project, which is a plugin for TurtleBlocks for pattern recognition using the XO camera (for example, traffic signs). The program was developed detached from TurtleBlocks, so it can be used as a library from any other software developed in C or python.

The project was developed in C and ported to python using a binding. The plugin adds a palette to TurtleBlocks for pattern recognition with blocks such as “Is the pattern Visible?” and all the blocks of the possible marks (Traffic signs).

The wiki of the project (in spanish) can be found here, in the Butiá wiki, where you can read more about the internals and how to use it:
http://www.fing.edu.uy/inco/proyectos/butia/mediawiki/index.php/Butia_reconocimiento_marcas

At the end of this article there are videos showing the project and the video of the presentation in the Sumo.UY event.

Proyecto Reconocimiento de marcas

Esta vez estoy presentando un software desarrollado con mi equipo para el proyecto Butiá, que es un plugin para TurtleBlocks para el reconocimiento de marcas con la cámara de la computadora XO (por ejemplo, señales de tráfico). El programa fue desarrollado independiente de TurtleBlocks, así que puede ser utilizado como una biblioteca de cualquier otro software desarrollado en C o python.

El proyecto fue desarrollado en C y se creó un binding para Python. El plugin añade una paleta para TurtleBlocks para el reconocimiento de patrones con bloques tales como “¿Está el patrón visible?” y todos los bloques de las posibles marcas (señales de tráfico) que sirven como parámetros para el bloque anterior.

La wiki del proyecto se puede encontrar aquí, en la wiki del proyecto Butiá. En ella podrán leer más sobre como utilizarlo y el funcionamiento interno:
http://www.fing.edu.uy/inco/proyectos/butia/mediawiki/index.php/Butia_reconocimiento_marcas

Al final de este artículo hay videos mostrando el proyecto y el video de la presentación en el evento del Sumo.UY edición 2012.



Experience at the LARC 2012 – Fortaleza, Brazil.

(— Español más abajo —)

English

Last week we participated with my team (MonsterButiá) at the LARC (Latin American Robotics Competicion) 2012, in Fortaleza Brazil.

We participated in the IEEE Open category, which involves the creation of a Sand cleaning Robot. The objective is to collect black painted soda cans from the sand, and deposit them in the trash (a red cylinder), always avoiding running into a maniqui and a chair, and avoiding stepping into the water.

There were 31 teams from all Latin America. We started devoloping our robot in June of 2012 and the competition was from 17 to 22 october 2012.

The experience was really good, and we managed to get the Third place!

We had 2 best rounds, one at the qualifier rounds and one at the final rounds.
In the last qualifier round we managed to pick up 5 cans, and the final round we managed to pick up 4 cans.

There are a lot of things to improve, but this competition helped us to test our knowledge in Computer Vision and object recognition, interaction with kinect devices, robot behaviors, etc.

The MonsterButia in the news

http://www.cromo.com.uy/2012/11/monster-butia-subio-al-podio-en-brasil/
http://www.lr21.com.uy/enredados/1069737-uruguay-obtuvo-el-tercer-puesto-en-el-concurso-latinoamericano-de-robotica

Project presentation

Slides presenting the work (spanish)

At the end of the posts you can watch the videos of the 2 best rounds and some pictures.

—————————————

Español

La semana pasada participamos con mi equipo MonsterButiá en el LARC (Latin American Robotics Competition) 2012, en Fortaleza, Brasil.

Participamos en la categoría IEEE Open, que implica la creación de un robot de limpieza de playas. El objetivo es recoger las latas de refrescos pintadas de negro de la arena, para finalmente depositarlas en la basura (un cilindro rojo), siempre evitando toparse con un maniqui y una silla, además de evitar entrar en el agua.

Hubo 31 equipos inscriptos de América Latina. Empezamos a desarrollar nuestro robot en junio de 2012 y la competencia fue 17-22 octubre de 2012.

La experiencia fue muy buena, y logramos un excelente resultado, consiguiendo el tercer puesto!

Teníamos dos mejores rondas, una en las rondas eliminatorias y una en las rondas finales.
En la última ronda de clasificación nos las arreglamos para recoger latas de 5 y la ronda final, nos las arreglamos para recoger 4 latas.

Hay muchas cosas que mejorar, pero este concurso nos ayudó a poner a prueba nuestros conocimientos en Visión por computador y reconocimiento de objetos, la interacción con los dispositivos Kinect, comportamientos de robot, etc.

El MonsterButiá en las noticias

http://www.cromo.com.uy/2012/11/monster-butia-subio-al-podio-en-brasil/
http://www.lr21.com.uy/enredados/1069737-uruguay-obtuvo-el-tercer-puesto-en-el-concurso-latinoamericano-de-robotica

Presentación del proyecto

Diapositivas de presentación del proyecto

Pictures and videos

This slideshow requires JavaScript.

Second qualifier round / Segunda ronda de clasificación

First Final Round / Primer ronda final

Robotic Football player

This time I’m going to present the Football player we had to developed for the embedded robotics course, as a part of my MsC in Computer science.

The objective was to create a two wheeled robot with a single camera which would work autonomously to find the ball and score a goal.

Here are the hardware and software specifications, a link to the source and some documentation if you want to learn a bit more.
Hardware:

Software:

  • Ubuntu 11.04 installed in the Beagleboard
  • video4linux for video capturing from the USB camera
  • source code (developed using lua 5.1 and some c from the v4l binding for lua)

The whole source code can be found here: https://github.com/rsisto/luaRoboEmb. The lua file to run to start the robot is penaltyKicker/subsumptionKicker.lua

The robot behavior was developed as a reactive paradigm, using a subsumption architecture .
The whole documentation can be found here (they are in Spanish, so if you have trouble reading using a translator, just ask):
Part 1, Building the wheeled robot and an ax12 API for lua
Part 2, Developing the kicker behavior

Some images and videos

This slideshow requires JavaScript.

Here is a video of the robot scoring a goal 🙂