Chrisrod's Weblog

enero 3, 2011

Los números de 2010

Filed under: Uncategorized — chrisrod @ 9:15 am

Los duendes de estadísticas de WordPress.com han analizado el desempeño de este blog en 2010 y te presentan un resumen de alto nivel de la salud de tu blog:

Healthy blog!

El Blog-Health-o-Meter™ indica: Minty-Fresh™.

Números crujientes

Featured image

Un duende de estadísticas ha creado esta pintura abstracta, inspirada en tus estadísticas.

Un Boeing 747-400 transporta hasta 416 pasajeros. Este blog fue visto cerca de 2,900 veces en 2010. Eso son alrededor de 7 Boeings 747-400.

En 2010, publicaste 3 entradas nueva, haciendo crecer el arquivo para 15 entradas. Subiste 11 imágenes, ocupando un total de 546kb. Eso es alrededor de una imagen por mes.

The busiest day of the year was 28 de octubre with 30 views. The most popular post that day was Creating a Selenium RC test case in 7 simple steps.

¿De dónde vienen?

Los sitios de referencia más populares en 2010 fueran facebook.com, es.wordpress.com, google.com.ar, google.cl y google.es.

Algunos visitantes buscan tu blog, sobre todo por tutorial seam, seam tutorial, jboss seam tutorial, jbpm seam y jbpm tutorial.

Lugares de interés en 2010

Estas son las entradas y páginas con más visitas en 2010.

1

Creating a Selenium RC test case in 7 simple steps febrero, 2010

2

jBPM + SEAM en 07 pasos (Un simple tutorial para ver la integracion del JBpm en SEAM) octubre, 2008
7 comentários

3

Instanciacion de WorkFlows del jBPM mediante Web Services octubre, 2008
3 comentários

4

Uso del LDAP para el modulo de autenticaciones en SEAM octubre, 2008
1 comentario

5

Uso del nodo Process State en jBPM octubre, 2008

febrero 21, 2010

Creating a Selenium RC test case in 7 simple steps

Filed under: Selenium Test — chrisrod @ 7:40 pm

In this little tutorial I will explain as clear as I can, how to create a test case using Selenium IDE, Selenium RC and JUnit, hope it will be useful for everybody.

01.   Download Selenium RC and after downloading Selenium IDE (http://seleniumhq.org/download/) install it in Firefox

Seleniumrc

Figure 01. Download page of Selenium IDE and RC.

 

02.   Open Selenium IDE in firefox, look for my blog in google and click on the first link that appears:

SeleniumIDE

Figure 02. Selenium IDE on firefox.

 

03.   Export the test case to JUnit clicking on Options à Format àjava JUnit

04.   Personally, I don’t want just to copy and paste the code that is just autogenerated  by Selenium IDE, you can do this, but it is more fun to create some classes and subclasses and then make run your test cases J. So you can check at the code that I generated from the help that I got from Selenium IDE.

package com.selenium.test;

 

import com.thoughtworks.selenium.SeleneseTestCase;

 

/**

 *

 * Abstract class that will setUp() and tearDown() all the test classes that

 * will extend this class.

 *

 * @author Christian Roman

 *

 */

abstract class SeleniumTestBase extends SeleneseTestCase {

      /**

       * Method that will open the web browser and redirect it to the main page of

       * google.

       */

      @Override

      public void setUp() throws Exception {

            setUp(http://www.google.com.bo/”, “*chrome”);

            selenium.open(“/webhp?hl=es”);

      }

 

      /**

       * Method that will close the session opened by the method setUp().

       */

      @Override

      public void tearDown() throws Exception {

            selenium.close();

            selenium.stop();

      }

     

      public void clickGoogleLink(String keyword, String link){

            selenium.type(“q”, keyword);

            selenium.click(“btnG”);

            selenium.waitForPageToLoad(“30000”);

            selenium.click(“link=”+link);

            selenium.waitForPageToLoad(“30000”);

      }

 

}

Listing 01. SeleniumTestBase.java

 package com.selenium.test;

 

import org.junit.Test;

 

public class GoogleSearchTest extends SeleniumTestBase {

     

      @Test

      public void testChrisrodWordpress() throws Exception {

 

            clickGoogleLink(“chrisrod wordpress”, “SEAM « Chrisrod’s Weblog”);

            assertTrue(selenium

                        .isTextPresent(“Uso del LDAP para el modulo de autenticaciones en SEAM”));

      }

     

      @Test

      public void testHowToDraw() throws Exception {

            clickGoogleLink(“how to draw faces”, “Portrait Drawing – Learn to Draw Faces”);

            assertTrue(selenium.isTextPresent(“Learn portrait drawing skills including face proportions”));

      }

}

Listing 02. GoogleSearchTest.java

05.   The structure of my code looks like this:

Figure 03. Code structure for running the test cases and libraries needed to accomplish this objective.

 

06.   Run selenium server, I mean double click over the jar file: selenium-server.jar, that comes with Selenium RC.

07.   Run your JUnit test case and enjoy watching how your web browser open, executes commands and close by itself (well actually controlled by Selenium Server)

CodeStructureRC

Figure 04. Running JUnit on GoogleSearchTest.

SeleniumRCinAction

Figure 05. Selenium Server in action.

febrero 16, 2010

A BRIEF EXPLANATION OF SELENIUM TEST

Filed under: Selenium Test — chrisrod @ 11:09 pm

Se

 01.                       What is selenium?

 

Selenium is a set of tools that is used to automate web application testing, across many platforms.

 

Between the biggest advantages of Selenium, we can mention:

          Runs in many browsers.

          Can be controlled with programming language like Java or PHP, that makes selenium very handy to integrate it to unit tests.

Selenium is usually used to have test cases that need to be run frequently,  with unlimited iterations and at the same time through this is possible to have a disciplined test documentation.

02.                       Components

Selenium-ide-logo

2.1 Selenium IDE

               Selenium IDE is a Firefox Add on, that can be easily download from this site:

http://seleniumhq.org/download/

               This tool is integrated with Firefox and the way to use it is very easy and friendly to use.   Selenium IDE works like a recorder, recording all the actions that one has on a specific website, like clicks, data typed in a form,  making it possible to reproduce all steps took, and by this way create a test suite, that can be easily run with this handy tool.

 

Another great feature of this IDE, is that one can have a well structured explanation of all the possible commands that can be recorded or executed by Selenium IDE. Talking about the commands, with Selenium IDE is possible to have assertion or verifications when they are needed, set some delays, wait a determined time to a page to load, etc, etc.

 

If there is a disadvantage on using Selenium IDE, is that all the test cases have to be recorded on Firefox.

 

Getting into the programming world, Selenium IDE make possible to export all the commands that were set or recorded to one or all these programming languages:

          Java (JUnit or TestNG)

          Groovie (JUnit)

          C#

          Perl

          PHP

          Python

          Ruby

                SeleniumIDE

Figure 01. Selenium IDE

 

Selenium-rc-logo

2.2 Selenium RC.

               Selenium Remote Control, gives Selenium all the flexibility that just a programming language can offer, making possible the development of test cases well structured, with programming logic (like iterations, control flow, etc), that at the end

 means a real automation of a suit of testing cases on an automated build environment.

Selenium-grid-logo

2.3 Selenium Grid.

               Selenium Grid is on my opinion, one of the most interesting technologies in the field of web application testing, because apart of the fact of flexibility that Selenium RC offer to the testing cases, with Selenium Grid, is possible to run as many tests as we want  in a parallel way, relying on the HW capabilities or number of computers available to run the test cases.

 

With the help of Selenium Grid, one can run test cases in different browsers at the same time, on different operating systems, and by this way, having at the end a report that tells how the web application is behaving with all the test cases that run on it.

 

  

03.                       Selenium RC

 

3.1. What is Selenium RC?

 

As was mentioned previously, Selenium RC allow the creation of more complex test cases, because now is possible to rely on all the facilities that a programming language can offer, like querying to a Data Base, reading files, sending e-mails, etc.

Is important to mention that Selenium RC is composed by these components:

          Selenium Server

          Selenium Core

          Client Libraries

 

 Selenium Server.

        The Selenium Server is the hearth of Selenium RC, because is on this place, where all the commands sent by the programming language and all the messages answered by the web browser, are processed, interpreted and sent to the corresponding party.

Other functions that take place in the Selenium Server, is launching and closing the web browser, as mentioned at the previous paragraph, running the Selenese Commands to be executed in the browser through the injection of Selenium Core in the browser, HTTP proxy from which all the HTTP messages pass.

The way Selenium Server accomplish all these tasks, is basically because Selenium Server works relying on GET/POST request, that makes possible to any programming language to send request to the Selenium Server.

 Selenium Core.

As was mentioned previously, Selenium Core is a chunk of JavaScript functions that interpret and run Selenese Commands in the browser where the test is executed.

Selenium Core resides into the Selenium  Server and when this opens the Web Browser, the Selenium Core is injected in it and by this way any Selenese Command can be executed in the browser.

Client Libraries.

The client libraries are the interface between the Selenium Server and a Programming language. For the very same reason Selenium provides many methods to interact with the Web Browser, there is even a method to execute JS commands directly in the browser.

SeleniumRC Squema 

Figure 02. Selenium RC

04.                       Selenium Grid

4.1 What is Selenium Grid?

Selenium Grid is the best thing that Selenium could ever develop (so far), and I say this because with Selenium Grid, as mentioned before, is possible to run test cases in a parallel way in one or many computers, and not just that, because is possible to run on different operate systems, different browsers, and all at the same time, fantastic, isn’t it?

The components of Selenium Grid, are:

          Selenium Hub

          Selenium RCs

Selenium Hub.

Basically the functions of the Selenium Hub are the functions of a network switch, because all the test cases are now addressed to the hub instead of the RC and  this hub allocates all the test cases on every RC that is connected to it.  This means that the main function of the Selenium Hub is redirect all the Selenese commands sent by the Test Cases, to the corresponding RC and at the same time keep track of the testing sessions.

To make possible to Selenium work on this way, it is necessary to implement test cases that have to be executed in a parallel mode. Talking about JUnit, there is an extra library called “Parallel JUnit” https://parallel-junit.dev.java.net/, and through this library is possible to execute more than one test case at the same time. The other possibility, that I personally recommend, is using TestNG http://testng.org that is a testing framework inspired in JUnit, and for this reason the logic of creating testing cases is basically the same, TestNG also includes many annotations to its framework, that make the life easier when creating test cases. To mention other advantages of TestNG, we can say that:

          TestNG has a configuration file (testing.xml) that makes possible to configure the way that we want to run the test cases, and between these possibilities, running test cases in parallel.

          TestNG has support of parameters.

          TestNG has an Eclipse plug-in.

           TestNG makes possible to classify test cases by groups and by this way control the order and priority of the execution of the test cases.

 Selenium Grid Setup

Figure 03. Selenium Grid

05.                       Conclusions

 

Selenium is a powerful tool that can be used in many ways, but is particularly interesting the way that Selenium can be used to run and automate test cases, what makes possible to have testing cases that can be executed periodically and with this to have at the same time a good documentation of all the test cases that were created for a web application.

 

With the use of Selenium RC and Selenium Grid, the automation and running of test cases takes a different perspective, making possible to have a very detailed coverage of all the possibilities available in a web application, reviewing as well the behavior of it on different Operating Systems and Web Browsers especially when cross browser compatibility is a must.

 

enero 9, 2010

Facebook Demographics Bolivia

Filed under: Uncategorized — chrisrod @ 1:07 am

A day of doing nothing interesting, I decided to check it out how many people of my country Bolivia has a Facebook account, and I came out with this results:

Total of users:   472 520

Below 18:           99 100
18 – 20:             98 060
20 – 25:            158 640
25 – 30:            103 760
30 – 35:             53 820
35 – 40:             28 620
40 – 45:             15 340
45 – 50:              9 840
50 – 55:              5 700
55 – 60:              3 480
Above 60:           1 540

One of the things that amaze me the most, was the fact that I found that almost 10000 people over 50 years old has a facebook account, that was more than I expected, considering that Bolivia has just 10E6 people and people born before the 60s were supposed to scared computers, well one thing is for sure… I was completly wrong :D.
Anyway, some times when you don’t have nothing to do, you find things that never passed through your mind, or at least mine :D… oh! by the way, I’m intending to take a JSCP certification on May, so I will be posting the most interenting stuff that I found to tackle this tricky test.

Facebook users distribution in BOLIVIA

agosto 7, 2009

A brief overview of EC2 and GigaSpaces

Filed under: GigaSpaces — chrisrod @ 1:21 pm

Elastic Compute Cloud

Elastic Compute Cloud (EC2) is an Amazon’s web service that provides resizable compute capacity in a cloud. One of the main characteristics of EC2, and at the same time one of its great advantage, is that it was designed to make web-scale computing easier for developers.

Amazon EC2’s simple web service interface allows to obtain and configure capacity with minimal friction. It provides as well a complete control of the computing resources and lets run on an Amazon’s computing environment.

Between the advantages that one can find using EC2, we could mention the reduction of time required to obtain and boot new server instances to minutes, allowing a quickly scale capacity, both up and down, as the change of computing requirements. Other advantages are the possibility to count with a diversity of Operating Systems, the possibility of run on multiple locations or utilize static IP endpoints.

To use EC2, it is necessary to sign up to the Amazon’s web page, and with this, get the two keys to use the web service; on of them is the Access Key ID, and the other one is the Secret Access Key, that can be generated as many times as one desire, depending on the security requirements that one has. With these two keys it is possible to access to all the web service’s facilities, depending on the type of account created.

To see EC2 in action, first it is needed to create an Amazon Machine Image (AMI) that will contain the application, libraries and the configuration settings. It is also possible to use one of the image templates to achieve the same objective, and one can do this using a firefox extension called “ElasticFox”, that can be download clicking on the next link: http://developer.amazonwebservices.com/connect/entry.jspa?externalID=609, once it is installed, you will see a GUI like the one is showed on the figure 01; once this extension is launched in firefox, it is possible to create the AMI, using the keys obtained on the Amazon web page, as it was explained on the previous paragraph. A really helpful tutorial to create a simple AMI can be found on the next link: http://www.youtube.com/watch?v=9QKnORsJKt4&annotation_id=annotation_297897&feature=iv, that explains how to create an Amazon account, the installation of the ElasticFox extension, and finally the creation and test of the new AMI. Once the AMI is created, the next step is to upload the web application to the Amazon Simple Storage Service (S3); between the tools used to accomplish this task, there is a firefox extension that can be smoothly installed on it, that is called “S3 Fox”, this extension can be downloaded clicking on the next link: https://addons.mozilla.org/en-US/firefox/addon/3247. Finally, it is possible to configure the security and network access, with the ElasticFox tool.


Figure 01. The ElasticFox extension

GigaSpaces XAP

GigaSpaces XAP (eXtreme Application Platform) is a scale-out application server. Among the advantages that one can find working with GigaSpaces, we can mention:

High-throughput

Low-latency

Scalability

and these advantages give the possibility to use GigaSpaces to build the next generation class of applications.

It can be said that a usual Web-Application that stores its data within the IMDG (In-Memory Data Grid) would basically have the next machines:

GSM Machine

Load-Balancer Machine

Database and Mirror Machines

GSC Machines – Running Web Application, IMDG and Services


Figura 02. A basic Web Application running on a cloud.

As can be seen in the last figure, the whole cloud is composed for many machines that can be created very easily editing a XML file and uploading it, with the aid of the GigaSpaces Cloud Console that can be found at the GigaSpaces web page (http://www.gigaspaces.com/mycloud), this console has many tools to create and manage all the clouds that one needs or have already been deployed. Comparing this tool, with the one that creates an Amazon’s AMI using the ElasticFirefox, this console is specially oriented to the creation and management of GigaSpaces clouds.

About the XML file that has to be edited for the creation of all the machines that one needs in a cloud, a basic template can be checked on the lines below this paragraph.

<cloud-config>

<cloud-name>my-data-grid</cloud-name>

<license>

Nov 16, 2009~CloudTestUser@bPS8NOufjXOuPNSYMWPO#PREMIUM^7.0XAPPremium%UNBOUND+UNLIMITED

</license>

<gigaspaces-build-location>

gigaspacesversions/gigaspaces-xap-premium-7.0.0-m9-b3496-87.zip

</gigaspaces-build-location>

<ami-id>ami-91db3cf8</ami-id>

<machines>

<!– Insert here –>

</machines>

<start-ui>admin-application</start-ui>

</cloud-config>

Between the “machine” tags one can create all the machines required for the Web Application; referring to the example of the figure 02, the XML file can be downloaded from the next link: http://cloud.gigaspaces.com/cloudtools/session-resources/demo/files/petclinic-mysql-example.xml

To upload this file, and by this way create the required machines, follow the next procedure:

01. Log into the Cloud Console using your GigaSpaces and Amazon Web Service (AWS) keys on this web page: http://www.gigaspaces.com/mycloud



Figure 03. Log into the Cloud Console

02. Upload the XML file that has all the information of the machines to be used in the cloud, filling the “Deployment Descriptor” field and clicking in the button “Deploy



Figure 04. Deploying the machines with the Cloud Console.

Now to upload the Web Application to the Amazon’s S3, an easy way to do this task is using the “S3Fox” extension, following the next procedure:

01. Start the S3Fox extension signing up with the Amazon’s Access Keys.



Figure 05. Signing up to the S3 through the S3Fox

02. Create a test folder at the root level of the S3 account by clicking the button at the right side panel.

03. Upload all the necessary files from the left side of the panel to the right side that, by the way, corresponds to the S3.

Finally for testing the web application, observe the link next to the “Load_Balancer” field in the Cloud Console and click on it, the application that you upload on the S3 should be displayed on the web browser.


Figure 06. Checking the Web Application deployed in the S3.

Conclusions

After reviewing the documentation found in the internet about GigaSpaces, I think that is a technology very promising for the future developments of applications that will need to be reliable and at the same time very flexible.

Talking about the service given by Amazon EC2, I think that the price they offer to have a cloud deployed on its servers is very reasonable, knowing that taking care of a Data Center needs people specialized on its maintenance and management.

octubre 10, 2008

Uso del nodo Process State en jBPM

Filed under: JBoss,JBPM — chrisrod @ 4:54 pm

Jbpm-logo

Este nodo es especialmente util para ir a un sub-flujo y luego volver al flujo original.

Dibujo-small

Figura 01.Nodo Process State 

El uso de este nodo se puede apreciar mejor en un flujo de ejemplo:

Dibujo-small1

Figura 02. Flujo principal

Dibujo-small2

Figura 03. Sub-flujo “Apellido”

Dibujo-small3

Figura 04. Sub-flujo “Edad”

Como se puede apreciar en las anteriores figuras, el flujo principal escala a dos sub-flujos en paralelo, los cuales pueden tener una estructura totalmente diferente del original, y una vez que ambos flujos terminen se procede a la impresion de las variables seteadas en ambos sub-flujos.

PASO DE VARIABLES ENTRE FLUJOS

 Para el paso de variables entre flujos realizar lo siguiente desde el IDE apuntandio al nodo “Sub Process”:

Dibujo-small4

 Figura 05. Paso de variables de un Flujo a un Sub-flujo

Donde:

01. Nombre del Sub-flujo

02. Version del sub-flujo

03. Variables de ida

04. Variables de vuelta

 

Como se puede ver en este pequenio tutorial del nodo “Process Sate”, no es necesario el uso de ningun codigo java, y los escalamientos y el paso de variables son transparentes para el usuario final.

Christian

octubre 6, 2008

Uso del LDAP para el modulo de autenticaciones en SEAM

Filed under: SEAM — chrisrod @ 7:46 pm

 Untitled

LDAP (Lightweight Directory Access Protocol), (Protocolo Ligero de Acceso a Directorios) es un protocolo a nivel de aplicacion que permite el acceso a un servicio de directorio ordenado y distribuido para buscar diversa información en un entorno de red. LDAP también es considerado una base de datos(aunque su sistema de almacenamiento puede ser diferente) a la que pueden realizarse consultas.

Habitualmente, almacena la información de login (usuario y contrasenia) y es utilizado para autenticarse aunque es posible almacenar otra información (datos de contacto del usuario, ubicación de diversos recursos de la red, permisos, certificados, etc).

En conclusión, LDAP es un protocolo de acceso unificado a un conjunto de información sobre una red.

Fuente: Wikipedia

Una ves dada esta pequenia introduccion de lo que es LDAP, ahora procedo a explicar como podemos aprovechar un servidor LDAP para el modulo de autenticacion en SEAM 

 Primeramente se necesitara realizar unas cuantas modificaciones al codigo de autenticacion “Authenticator.java” que viene por defecto cuando creamos un proyecto SEAM.

Dibujo-small5

Dibujo-small13

Figura 01. Codigo modificado del “Authenticator.java”

 

Una ves realizadas dichas “modificaciones” al codigo de autenticacion, se procede a la utilizacion de la pagina “login.xhtml” que ya viene por defecto cuando creamos un proyecto en SEAM:

Dibujo-small5

Figura 02. Pagina de autenticacion “login.xhtml”

Y listo

Una ves que hayas deployado tu proyecto y hayas seguido mis indicaciones al pie de la letra, veras lo siguiente cuando la autenticacion sea erronea:

Dibujo-small31

Figura 03. Contrasenia Incorrecta

Caso contrario podras ver lo siguiente

Dibujo-small41

Figura 04. Contrasenia Correcta

 

Espero que les haya servido

 

Christian

 

 

Tags:

Uso de programas java para la asignacion de usuarios en jBPM

Filed under: JBPM — chrisrod @ 7:45 pm

 

Jbpm+users

Utilizando la interfaz “org.jbpm.taskmgmt.def.AssignmentHandler” es posible asignar un usuario o un grupo de usuarios a una tarea especifica del jBPM.

Lo unico que se tiene que hacer en la opcion de “Assignment” de cada tarea, escoger la opcion “Handler”, tal como se puede apreciar en la siguiente figura:

Dibujo

Figura 01. Task Assignment

El codigo java que ha de asignar un usuario en funcion de una variable es el siguiente:

Dibujo

Figura 02. Codigo java que asigna un solo usuario a una tarea

El codigo java que ha de asignar un grupo de usuarios, es el siguiente:

Dibujo

Figura 03. Codigo java que asigna un grupo de usuarios

Como pueden apreciar, el anterior codigo asigna una tarea a un grupo de usuarios en funcion del grupo al que pertenecen, el cual es extraido de una Base de Datos.

De esta forma es posible asignar usuarios de forma dinamica y lo mas importante la actualizacion de los actores a los cuales es asignada una determinada tarea solo necesita ser actualizada desde una Base de Datos  sin variar el codigo.

Instanciacion de WorkFlows del jBPM mediante Web Services

Filed under: JBPM — chrisrod @ 7:44 pm

Como mucho de ustedes sabran, los Servicios Web son un conjunto de protocolos y estandares que permiten intercambiar datos entre aplicaciones, es de esta manera que de forma estandar podemos realizar la interconexion de diferentes equipos sin tener que preocuparnos de su tecnologia o su procedencia.

En pocas palabras, la definicion de “Web Services” segun la Wikipedia es la siguiente:

Un servicio web (en inglés Web service) es un conjunto de protocolos y estándares que sirven para intercambiar datos entre aplicaciones. Distintas aplicaciones de software desarrolladas en lenguajes de programación diferentes, y ejecutadas sobre cualquier plataforma, pueden utilizar los servicios web para intercambiar datos en redes de ordenadores como Internet. La interoperabilidad se consigue mediante la adopción de estandares abiertos. Las organizaciones OASIS y W3C son los comités responsables de la arquitectura y reglamentación de los servicios Web. Para mejorar la interoperabilidad entre distintas implementaciones de servicios Web se ha creado el organismo WS-I, encargado de desarrollar diversos perfiles para definir de manera más exhaustiva estos estándares.

 

Una ves dado el breve marco teorico, procedere a explicar la solucion de un problema que me tuvo pensando e investigando por mucho tiempo (al rededor de un mes aproximadamente), mediante el cual es posible instanciar flujos del jBPM desde una aplicacion externa simplemente utlizando Web Services.

Los IDEs que utilice para estas tareas fueron: NetBeans 6.1 (mi preferido) y Eclipse (al cual le estoy empezando a hallar el gustito).

Utilice Eclipse para la elaboracion de mi flujo jBPM y utilice NetBeans 6.1 para la elaboracion del EJB Module el cual sera el que alvergara el Web Services que escuchara nuestros requerimientos.

Este pequeño tutorial se enfocara principalmente en la elaboracion del EJB Module con el cual crearemos el Web Service que podra instanciar flujos de una manera externa al jBPM.

Creacion del EJB Module

En el NetBeans crea un nuevo proyecto de la categoria enterprise tal como se aprecia en la figura:

Dibujo

Figura 01. Creacion del EJB Module

Sigue los mismos pasos descritos en el libro “Building SOA-Based Composite Applications Using NetBeans IDE 6” acerca de la creacion de un “EJB Module”. Este libro es muy bueno si uno quiere meterse en el mundo de SOA tal como lo comente hace un tiempo atras en este mismo Blog.

Pienso que dos partes son muy importantes para que este Servicio Web funcione correctamente:

01) La configuracion correcta de los archivos xml: jbpm.cfg.xml y hibernate.cfg.xml

02) El codigo que instanciara remotamente el flujo

Empecemos por lo primero, es decir los archivos xml.

Los archivos XML

Tu archivo jbpm.cfg.xml debe tener la siguiente estructura:

<jbpm-configuration>

  <jbpm-context>
    <service name=”persistence”>
       <factory>
          <bean class=”org.jbpm.persistence.db.DbPersistenceServiceFactory”>
             <field name=”isTransactionEnabled”><false/></field>
          </bean>
       </factory>
    </service>
    <service name=”tx” factory=”org.jbpm.tx.TxServiceFactory” />
    <service name=”message” factory=”org.jbpm.msg.db.DbMessageServiceFactory” />
    <service name=”scheduler” factory=”org.jbpm.scheduler.db.DbSchedulerServiceFactory” />
    <service name=”logging” factory=”org.jbpm.logging.db.DbLoggingServiceFactory” />
    <service name=”authentication” factory=”org.jbpm.security.authentication.DefaultAuthenticationServiceFactory” />
  </jbpm-context>

</jbpm-configuration>

 y el archivo hibernate.cfg.xml la siguiente:

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN”
                                         “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd“>
<hibernate-configuration>
 <session-factory name=”Acceso”>
  <property name=”show_sql”>false</property>
  <property name=”connection.datasource”>java:/dvdDatasource</property>
  <property name=”transaction.factory_class”>org.hibernate.transaction.JTATransactionFactory</property>
  <property name=”transaction.manager_lookup_class”>org.hibernate.transaction.JBossTransactionManagerLookup</property>
  <property name=”cache.provider_class”>org.hibernate.cache.HashtableCacheProvider</property>
  <property name=”hbm2ddl.auto”>create-drop</property>
  <!–property name=”transaction.flush_before_completion”>true</property
 ############################################
 # mapping files with external dependencies #
 ############################################
 following mapping file has a dependendy on  
 ‘bsh-{version}.jar’.                        
 uncomment this if you don’t have bsh on your
 classpath.  you won’t be able to use the    
 script element in process definition files   –>
  <mapping resource=”org/jbpm/graph/action/Script.hbm.xml”/>
  <!– following mapping files have a dependendy on 
 ‘jbpm-identity.jar’, mapping files           
 of the pluggable jbpm identity component.    
 Uncomment the following 3 lines if you       
 want to use the jBPM identity mgmgt          
 component.                                   
 identity mappings (begin) ===
    <mapping resource=”org/jbpm/identity/User.hbm.xml”/>
    <mapping resource=”org/jbpm/identity/Group.hbm.xml”/>
    <mapping resource=”org/jbpm/identity/Membership.hbm.xml”/>
    ==== identity mappings (end)
 following mapping files have a dependendy on 
 the JCR API                                  
 jcr mappings (begin) ===
    <mapping resource=”org/jbpm/context/exe/variableinstance/JcrNodeInstance.hbm.xml”/>
    ==== jcr mappings (end)
 ######################
 # jbpm mapping files #
 ######################
 hql queries and type defs –>
  <mapping resource=”org/jbpm/db/hibernate.queries.hbm.xml”/>
  <!– graph.action mapping files –>
  <mapping resource=”org/jbpm/graph/action/MailAction.hbm.xml”/>
  <!– graph.def mapping files –>
  <mapping resource=”org/jbpm/graph/def/ProcessDefinition.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/def/Node.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/def/Transition.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/def/Event.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/def/Action.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/def/SuperState.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/def/ExceptionHandler.hbm.xml”/>
  <mapping resource=”org/jbpm/instantiation/Delegation.hbm.xml”/>
  <!– graph.node mapping files –>
  <mapping resource=”org/jbpm/graph/node/StartState.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/node/EndState.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/node/ProcessState.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/node/Decision.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/node/Fork.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/node/Join.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/node/MailNode.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/node/State.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/node/TaskNode.hbm.xml”/>
  <!– context.def mapping files –>
  <mapping resource=”org/jbpm/context/def/ContextDefinition.hbm.xml”/>
  <mapping resource=”org/jbpm/context/def/VariableAccess.hbm.xml”/>
  <!– taskmgmt.def mapping files –>
  <mapping resource=”org/jbpm/taskmgmt/def/TaskMgmtDefinition.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/def/Swimlane.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/def/Task.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/def/TaskController.hbm.xml”/>
  <!– module.def mapping files –>
  <mapping resource=”org/jbpm/module/def/ModuleDefinition.hbm.xml”/>
  <!– bytes mapping files –>
  <mapping resource=”org/jbpm/bytes/ByteArray.hbm.xml”/>
  <!– file.def mapping files –>
  <mapping resource=”org/jbpm/file/def/FileDefinition.hbm.xml”/>
  <!– scheduler.def mapping files –>
  <mapping resource=”org/jbpm/scheduler/def/CreateTimerAction.hbm.xml”/>
  <mapping resource=”org/jbpm/scheduler/def/CancelTimerAction.hbm.xml”/>
  <!– graph.exe mapping files –>
  <mapping resource=”org/jbpm/graph/exe/Comment.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/exe/ProcessInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/exe/Token.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/exe/RuntimeAction.hbm.xml”/>
  <!– module.exe mapping files –>
  <mapping resource=”org/jbpm/module/exe/ModuleInstance.hbm.xml”/>
  <!– context.exe mapping files –>
  <mapping resource=”org/jbpm/context/exe/ContextInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/TokenVariableMap.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/VariableInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/variableinstance/ByteArrayInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/variableinstance/DateInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/variableinstance/DoubleInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/variableinstance/HibernateLongInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/variableinstance/HibernateStringInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/variableinstance/LongInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/variableinstance/NullInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/context/exe/variableinstance/ StringInstance.hbm.xml”/>
  <!– job mapping files –>
  <mapping resource=”org/jbpm/job/Job.hbm.xml”/>
  <mapping resource=”org/jbpm/job/Timer.hbm.xml”/>
  <mapping resource=”org/jbpm/job/ExecuteNodeJob.hbm.xml”/>
  <mapping resource=”org/jbpm/job/ExecuteActionJob.hbm.xml”/>
  <!– taskmgmt.exe mapping files –>
  <mapping resource=”org/jbpm/taskmgmt/exe/TaskMgmtInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/exe/TaskInstance.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/exe/PooledActor.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/exe/SwimlaneInstance.hbm.xml”/>
  <!– logging mapping files –>
  <mapping resource=”org/jbpm/logging/log/ProcessLog.hbm.xml”/>
  <mapping resource=”org/jbpm/logging/log/MessageLog.hbm.xml”/>
  <mapping resource=”org/jbpm/logging/log/CompositeLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/ActionLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/NodeLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/ProcessInstanceCreateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/ProcessInstanceEndLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/ProcessStateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/SignalLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/TokenCreateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/TokenEndLog.hbm.xml”/>
  <mapping resource=”org/jbpm/graph/log/TransitionLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/VariableLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/VariableCreateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/VariableDeleteLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/VariableUpdateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/variableinstance/ByteArrayUpdateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/variableinstance/DateUpdateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/variableinstance/DoubleUpdateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/variableinstance/HibernateLongUpdateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/variableinstance/HibernateStringUpdateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/variableinstance/LongUpdateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/context/log/variableinstance/StringUpdateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/log/TaskLog.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/log/TaskCreateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/log/TaskAssignLog.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/log/TaskEndLog.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/log/SwimlaneLog.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/log/SwimlaneCreateLog.hbm.xml”/>
  <mapping resource=”org/jbpm/taskmgmt/log/SwimlaneAssignLog.hbm.xml”/>
 </session-factory>
</hibernate-configuration>

 

Ambos archivos debes localizarlos en el directorio “Source Packages” de tu EJB Module

Dibujo

Figura 02. Ubicacion de los archivos xml

El Codigo

El codigo que permitira que tu Servicio Web instancie un flujo remotamente es el siguiente:

Dibujo

Figura 03. Codigo que instancia flujos remotamente

 

Para concluir en el anterior codigo utilice el exelente Tutorial “jbpm3.2.2-handsontutorial” el cual te lo puedes descargar de la Wiki de jBoss, el cual es tremendamente recomendable si quieres entender la logica de funcionamiento de jBPM.

Y listo, deploya este EJB Module en tu servidor jBoss, y testea el Servicio Web con cualquier programa que realice esto, el que YO utlizo es: “SOAP UI” el cual tambien te lo puedes descargar de la red

El resultado que obtuve fue el siguiente:

Dibujo

Figura 04. Web Service deployado (http://127.0.0.1:8080/jbossws/services)

Dibujo

Figura 05. Resultado del Servicio Web consumido

 

Espero que les haya servido

 

Christian

 

 

 

 

Importante TIP para utilizar variables de los beans del SEAM con las clases del jBPM

Filed under: JBoss,JBPM,SEAM — chrisrod @ 4:49 pm

Jbpm_logo9

 

Uno de las grandes posibilidades que nos da SEAM es la posibilidad de integrarlo con el jBPM, es de esta forma que encotre un camino para utilizar las variables seteadas en un Bean del SEAM dentro de una clase del jBPM.

La forma es la siguiente:

01. Seteamos una variable del SEAM a traves de un bean utilizando la siguiente notacion:

@Out(value=variableX”,scope=ScopeType.BUSINESS_PROCESS)

private boolean valorDeVariableX;

De esta forma “variableX” a de ser el nombre de la variable a ser almacenada en la base de datos del jBPM (Especificamente hablando, esta variable es almacenada en la tabla “jbpm_variableinstance”) y “valorDeVariableX” ha de ser el valor de esa variable.

Dibujo

Figura 01. Tabla de almacenamiento de variables del jBPM

 

02.  Obtener “variableX” utilizando clases del jBPM.

Estas clases pueden ser “DecisionHandler (que en realidad es una interfaz utilizada en el nodo de toma de decisiones)” o la clase “ActionHandler” (que tambien es otra interfaz utlizada para ejecutar una accion en cualquier nodo del jBBPM)

La forma de obtener esta “variableX” sera la siguiente:

boolean decide=(Boolean)Contexts.getBusinessProcessContext().get(variableX);

 

Como pueden apreciar esta no es una forma muy elegante de darle uso al SEAM, pero puesto que soy un Ingeniero Electronico al que principalmente le importa que las cosas funcionen, para mi es una solucion que me quita un problema de la cabeza .

Espero que les sirva

 

Christian

 

Página siguiente »

Crea un blog o un sitio web gratuitos con WordPress.com.