viernes, 18 de mayo de 2012

UTILWS PARA JAXWS


Hola en esta oportunidad mostrar les hablare y les compartiré un Utilitario que normalmente manejo para el manejo de Servicios Web y Proxys con el Framework JAXWS.
El utilitario es un clase JAVA que le llamo: UtilWS,java y soporta el manejo lo siguiente:

- setEndpointURL: Permite el seteo de una nueva URL que contenga el WSDL del WS expuesta en el navegador..
- getEndpointURL:
Permite obtener la URL (EndPoint) que el servicio actualmente esta soportando.
- validaUrl:
Valida la URL si esta actualmente activa o no. Esto para ser aplicado antes de la consulta desde un Proxy WS.
- setTimeOutProxyWS:
Setea un tiempo determinado (TimeOut) para las consultas a WS desde un Proxy en base al Binding.
- setLoginProxyWS:
  Setea el Login para la autenticación de acceso a un WS externo.

El utilitario se usa de esta manera:

ESCENARIO:

1. Supongamos que tenemos un Servicio Web desplegado en un SERVER XXX a este para efecto del Dummy le puesto en la operación un: 

public static void main( String[] args ){
           
//------------ PARA TEST [TIMEOUT] ------------//
   long tiempo = (5 * 1000); //5 SEGUNDOS

   try{
       Thread.sleep( tiempo );
   }
   catch( InterruptedException e ){
          e.printStackTrace();
   }
//---------------------------------------------// 
}                                                
}

2. Este SERVER supongamos que generara un WSDL expuesto asi:

http://localhost:8090/GestionDatosUsuarioWS/GestionDatosUsuarioWSService?wsdl

3. Ahora para consumirlo tendré que manejar un PROXY Client y para crearlo usare la IDE:  Oracle Enterprise Pack for Eclipse, ya que viene un unos muy buenos PLUGINs y sobre todo con el de JAXWS.

4. Creamos el APP WS:  file/web/other/weblogic Services/Web Service Project
damos el nombre al Proxy y listo. Ya tenemos nuestro proyecto de tipo WS.

5. Creamos el PROXY Client:   file/new/other/weblogic Services/ Web Service Client, nos mostrara un Wizar donde nos dará la opción para generar los Objetos y Clases .JAVA en base a un WSDL o una URL. Luego, nos pedira que le designemos un nombre al .JAR (Ya que estas librerías las meterá un un .JAR dentro de la carpeta .lib, para su mejor manejo ya que no se deben de modificar dichas clases).

6. Dentro de SRC creamos una Clases Test por ejemplo llamada:  TestGestionDatos.java, en donde crearemos el PROXY en si, en base al JAR generado y apoyándonos en nuestro UtilWS.java.
IMPORTANTE: VALIDAR YA QUE HAY 2 [BindingProperties]:
                             com.sun.xml.internal.ws.client.BindingProperties
                             com.sun.xml.ws.client.BindingProperties


UtilWS.java:

/**
 * UtilWS  IMPORTANTE: VALIDAR YA QUE HAY 2 [BindingProperties y BindingProvider]:
 *                     com.sun.xml.ws.client.BindingProperties          [SI FUNCIONA]
 *                     com.sun.xml.internal.ws.client.BindingProperties [NO FUNCIONA]
 *                    
 * @author cguerra
 */ public class UtilWS{
   
    private Logger logger = Logger.getLogger( this.getClass().getName() );
   
    //Constructor ...
    public UtilWS(){       
    }
        
   /**
    * EndpointURL
    * @param  objBinding
    * @return actual_URL
    */
    public String getEndpointURL( Object objBinding ){
           String actual_URL = (String)((BindingProvider)objBinding).getRequestContext().get( BindingProvider.ENDPOINT_ADDRESS_PROPERTY );
           return actual_URL;
    }   
   
   /**
    * setEndpointURL
    * @param  URL
    * @param  objBinding
    * @return new_URL
    */
    public String setEndpointURL( String URL, Object objBinding ){
           String new_URL = (String)((BindingProvider)objBinding).getRequestContext().put( BindingProvider.ENDPOINT_ADDRESS_PROPERTY, URL );  
           return new_URL;
    }
   
   /**
    * validaUrl valida la existencia de la 'URL'.
    * @param  cadenaUrl
    * @return int
    * @throws MalformedURLExceptionWS
    * @throws IOExceptionWS
    */
    public int validaUrl( String cadenaUrl ) throws MalformedURLExceptionWS, IOExceptionWS{

        int respuestaURL = 0;

        try{
            URL url = new URL( cadenaUrl );
            URLConnection urlConexion = url.openConnection();

            urlConexion.setDoOutput( true );
            urlConexion.setDoInput(  true );

            if( urlConexion instanceof HttpURLConnection ){

                this.logger.debug( "" );
                this.logger.debug( "====> URL:            " + urlConexion.getURL() );
                this.logger.debug( "====> TIPO CONTENIDO: " + urlConexion.getContentType() );
                this.logger.debug( "" );

                HttpURLConnection httpConexion = (HttpURLConnection)urlConexion;
                httpConexion.connect();

                respuestaURL = httpConexion.getResponseCode(); // 200 = OK
                this.logger.debug( "Respuesta 'URL': " + respuestaURL );

                if( respuestaURL == 200 ){
                    this.logger.debug( "Conexion Exitosa con la 'URL': " + url );
                }
            }
        }
        catch( MalformedURLException e ){
               //this.logger.error( "Error en el Fomato de la 'URL': " + e.getMessage() );
               throw new MalformedURLExceptionWS( "ERROR: [Fomato de la 'URL'] " + e.getMessage(), e );
        }
        catch( IOException e ){
               //this.logger.error( "Error en la conexion con el Servidor: " + e.getMessage() );
               throw new IOExceptionWS( "ERROR: [Conexion con el Servidor] " + e.getMessage(), e );
        }

        return respuestaURL;
    }
   
   /**
    * setTimeOutProxyWS
    * @param objBinding
    * @param requestTimeout
    * @param connectTimeout
    */
    public void setTimeOutProxyWS( Object objBinding, int requestTimeout, int connectTimeout ){          
           Map contextoRequest = ((BindingProvider)objBinding).getRequestContext();
         
           //FORMA #1:
           contextoRequest.put( BindingProviderProperties.CONNECT_TIMEOUT, connectTimeout );
           contextoRequest.put( BindingProviderProperties.REQUEST_TIMEOUT, requestTimeout );
         
           //FORMA #2:
           //contextoRequest.put( "com.sun.xml.ws.connect.timeout", connectTimeout );
           //contextoRequest.put( "com.sun.xml.ws.request.timeout", requestTimeout );
    }
   
   /**
    * setLoginProxyWS
    * @param objBinding
    * @param usuarioParam
    * @param passwParam
    */
    public void setLoginProxyWS( Object objBinding, String usuarioParam, String passwParam ){          
           Map contextoRequest = ((BindingProvider)objBinding).getRequestContext();
           contextoRequest.put (BindingProvider.USERNAME_PROPERTY, usuarioParam );
           contextoRequest.put (BindingProvider.PASSWORD_PROPERTY, passwParam   );
    }
   
 }

Dentro de esta clase manejaremos el control de TIMEOUT y ENDPOINT accediento al UtilWS.java:

TestGestionDatos.java
  
/**
 * @author cguerra.
 * @clase: TestGestionDatos.java
 * @versión 1.0
 */
public class TestGestionDatos{
   
    private Logger logger = Logger.getLogger( this.getClass().getName() );
   
    private UtilWS objUtilWS = null;
   
    /**
     * @param argumentos
     * @throws ServiceException
     * @throws RemoteException
     * @throws MalformedURLException
     */
    public static void main( String... argumentos ){
       
        TestGestionDatos objTest = null;
       
        try{              
            objTest = new TestGestionDatos(); 
            objTest.procesarConsultaUsuarioProxy();
           }
           catch( Exception e ){
                  objTest.logger.error( "ERROR: ", e );
           }          
    }   
  
   /**
    * procesarConsultaUsuarioProxy
    * @throws TimeOutExceptionWS
    * @throws WSException
    * @throws GenericExceptionWS
    * @throws MalformedURLExceptionWS
    * @throws IOExceptionWS
    */
    public void procesarConsultaUsuarioProxy() throws TimeOutExceptionWS, WSException, GenericExceptionWS, MalformedURLExceptionWS, IOExceptionWS{
       
       GestionDatosUsuarioWSSoapImplService objGestionDatosUsuario = new GestionDatosUsuarioWSSoapImplService();
       GestionDatosUsuarioWSSoapImpl        objServicioWS          = objGestionDatosUsuario.getGestionDatosUsuarioWSSoapImplPort();
      
       this.objUtilWS = new UtilWS();       
       int validaURL  = this.objUtilWS.validaUrl( ConstantesWS.URL_WSDL_GESTION_DATOS_USUARIO_WS );
      
       if( validaURL == ConstantesWS.COD_ENDPOINT_OK ){   
          
           //---------- ENDPOINT ----------//
           this.objUtilWS.setEndpointURL( ConstantesWS.URL_WSDL_GESTION_DATOS_USUARIO_WS, objServicioWS );
           //---------- ENDPOINT ----------//
          
           try{
               ConsultarUsuarioInput  objConsultaInput  = new ConsultarUsuarioInput();
               ConsultarUsuarioOutput objConsultaOutPut = new ConsultarUsuarioOutput();
               Usuario                objUsuario        = new Usuario();
               Generico               objGenerico       = null;
               Arg0                   objArgumento      = null;
               StringBuffer           objCadena         = null;           
               String                 saltoLine         = new String( "\n" ); 
                             
               objUsuario.setCodigo( 1 );       
               this.logger.debug( "[DATOS REQUEST]: " );
               this.logger.debug( "CODIGO: [" + objUsuario.getCodigo() + "]" );   
              
               objConsultaInput.setConsultarUsuarioInput( objUsuario );
              
               objArgumento = new Arg0();
               objArgumento.setConsultarUsuarioInput( objConsultaInput );
              
               //---------- TIMEOUT ----------//
               this.objUtilWS.setTimeOutProxyWS( objServicioWS, ConstantesWS.REQUEST_TIMEOUT_GESTION_DATOS_USUARIO,
                                                                ConstantesWS.CONECTION_TIMEOUT_GESTION_DATOS_USUARIO );
               //---------- TIMEOUT ----------//
              
               objConsultaOutPut = objServicioWS.consultarUsuario( objArgumento );
              
               objUsuario  = objConsultaOutPut.getConsultarUsuarioOutput();
               objGenerico = objConsultaOutPut.getMensajeGenericoOutput();
              
               String   codigoGene     = objGenerico.getCodigo();
               String   mensajeGene    = objGenerico.getMensaje();
               Integer  codigo         = objUsuario.getCodigo();
               String   nombres        = objUsuario.getNombres();
               String   apellidos      = objUsuario.getApellidos();
               String   nombreApellido = objUsuario.getNombreApellido();
               String   dni            = objUsuario.getDni();
               String   telefono       = objUsuario.getTelefono();
               String   email          = objUsuario.getEmail();
               XMLGregorianCalendar cumpleanos     = objUsuario.getCumpleanos();
               XMLGregorianCalendar fecRegDateTime = objUsuario.getFecRegDateTime();
               String   fecRegString   = objUsuario.getFecRegString();
              
               this.logger.debug( "[DATOS RESPONSE]: " );
              
               objCadena = new StringBuffer();
               objCadena.append( "- CODIGO GENERICO:  ["  + codigoGene + "]" + saltoLine );
               objCadena.append( "- MENSAJE GENERICO: [" + mensajeGene + "]" + saltoLine );
               objCadena.append( "- CODIGO: ["       + codigo      + "]" + saltoLine );
               objCadena.append( "- NOMBRES: ["      + nombres     + "]" + saltoLine );
               objCadena.append( "- APELLIDOS: ["    + apellidos   + "]" + saltoLine );
               objCadena.append( "- NOMBRES-APELLIDOS: [" + nombreApellido + "]" + saltoLine );
               objCadena.append( "- DNI: ["          + dni         + "]" + saltoLine );
               objCadena.append( "- TELEFONO: ["     + telefono    + "]" + saltoLine );
               objCadena.append( "- EMAIL: ["        + email       + "]" + saltoLine );
               objCadena.append( "- CUMPLEANIOS: ["  + cumpleanos  + "]" + saltoLine );
               objCadena.append( "- FECHA DATETIME: [" + fecRegDateTime + "]" + saltoLine );
               objCadena.append( "- FECHA STRING: ["   + fecRegString   + "]" + saltoLine );
              
               this.logger.debug( objCadena.toString() );              
           }
           catch( Exception e ){
                  if( (e instanceof java.net.SocketTimeoutException) ){
                throw new TimeOutExceptionWS( "ERROR: [SocketTimeoutException] " + e.getMessage(), e );
                  }
                  else if( (e instanceof javax.xml.ws.WebServiceException) ){
                            throw new WSException( "ERROR: [WebServiceException] " + e.getMessage(), e );
                  }
                  else{
                       throw new GenericExceptionWS( "ERROR: " + e.getMessage(), e );
                  }
           }          
       }
   }    
 }

Si en la constante:  REQUEST_TIMEOUT_GESTION_DATOS_USUARIO, le seteamos un tiempo de 6 segundos (6000 milisegundos) se obtendría un resultado OK ya que el SERVER dará 5 segundos de espera:

[2012-05-18 | 22:53:24] [pe.com.javaman.services.jaxws.util.UtilWS] [DEBUG]:
[2012-05-18 | 22:53:24] [pe.com.javaman.services.jaxws.util.UtilWS] [DEBUG]: ====> URL:            http://127.0.0.1:8090/GestionDatosUsuarioWS/GestionDatosUsuarioWSService?wsdl
[2012-05-18 | 22:53:24] [pe.com.javaman.services.jaxws.util.UtilWS] [DEBUG]: ====> TIPO CONTENIDO: text/xml;charset="utf-8"
[2012-05-18 | 22:53:24] [pe.com.javaman.services.jaxws.util.UtilWS] [DEBUG]:
[2012-05-18 | 22:53:24] [pe.com.javaman.services.jaxws.util.UtilWS] [DEBUG]: Respuesta 'URL': 200
[2012-05-18 | 22:53:24] [pe.com.javaman.services.jaxws.util.UtilWS] [DEBUG]: Conexion Exitosa con la 'URL': http://127.0.0.1:8090/GestionDatosUsuarioWS/GestionDatosUsuarioWSService?wsdl
[2012-05-18 | 22:53:24] [pe.com.javaman.services.jaxws.dummy.proxy.TestGestionDatos] [DEBUG]: [DATOS REQUEST]:
[2012-05-18 | 22:53:24] [pe.com.javaman.services.jaxws.dummy.proxy.TestGestionDatos] [DEBUG]: CODIGO: [1]
[2012-05-18 | 22:53:29] [pe.com.javaman.services.jaxws.dummy.proxy.TestGestionDatos] [DEBUG]: [DATOS RESPONSE]:
[2012-05-18 | 22:53:29] [pe.com.javaman.services.jaxws.dummy.proxy.TestGestionDatos] [DEBUG]: - CODIGO GENERICO:  [1]
- MENSAJE GENERICO: [PROCESO EXITOSO]
- CODIGO: [1]
- NOMBRES: [Cesar Ricardo]
- APELLIDOS: [Guerra Arnaiz]
- NOMBRES-APELLIDOS: [null]
- DNI: [41816133]
- TELEFONO: [5214952]
- EMAIL: [null]
- CUMPLEANIOS: [null]
- FECHA DATETIME: [null]
- FECHA STRING: [null]

Pero si en la constante:  REQUEST_TIMEOUT_GESTION_DATOS_USUARIO, le seteamos un tiempo de 4 segundos (4000 milisegundos) se obtendría un resultado NOK ya es MENOR al tiempo del SERVER de 5 segundos de espera. El ERROR será de tipo TIMEOUT:

pe.com.javaman.services.jaxws.exceptions.WSException: ERROR: [WebServiceException] java.net.SocketTimeoutException: Read timed out
    at pe.com.javaman.services.jaxws.dummy.proxy.TestGestionDatos.procesarConsultaUsuarioProxy(TestGestionDatos.java:139)
    at pe.com.javaman.services.jaxws.dummy.proxy.TestGestionDatos.main(TestGestionDatos.java:46)

Para descargar UtilWS.java, pulsar:  AQUI 

Espero que el post les sea de utilidad ..!

jueves, 17 de mayo de 2012

GENERADOR DE OBJETOS JAVA DESDE WSDL [MAVEN]


Hola chicos en esta oportunidad postearé, sobre un utilitario que manejo para el manejo de WebService. Todos sabrán que ahora el manejo de los Servicios Web esta muy de moda, sobre todo como una fuerte modalidad de INTEGRACION de sistemas legacy con otros tipos de sistemas, en IDEs de INTEGRACION como IBM Websphere Message Broker o el OSB de ORACLE. La cuestión es que en el mercado existen muchos Frameworks para la generación de WebService y Proxys (Clientes WS) tales como: AXIS, AXIS2, JAXRPC, JAXWS, uno mas antiguos que otros y otros mejores que otros. Por motivos de trabajo he tenido la necesidad que trabajar con todos y los conozco bien pero particularmente prefiero por motivos de mejor generación de objetos, mantenibilidad, etc JAXWS.

Una cosa que no me gusta es que por ejemplo las IDES como ECLIPSE, JDEVELOPER, etc no tienen el soporte a todas estos Frameworks y constantemente uno tiene que bajar un plugin o sino manejar varias herramientas por ejemplo ECLIPSE soporta WS embebido con AXIS solamente y si quiero trabajar con JAXWS me tengo que apoyar en por ejemplo el WID de IBM que lo tiene embebido y si quiero AXIS2 bajarme un plugin adicional. Algo similar pasa con JDeveloper. Por otro lado, el manejo de Wizards como que nunca me gusto mucho así que para mi la modalidad compartida a continuación es la mas optima.

Lo que manejo es un proyecto de tipo MAVEN, que solo lo utilizo como Generador de Objetos y clases JAVA en base al WSDL (en FISICO o URL) respectivamente. Esto lo hago mediante Plugins de MAVEN para cada tipo diferente de FRAMEWORK.

ESCENARIO #1:  "Tengo un WSDL y requiero hacer un WS o un PROXY". Que necesito GENERAR el WS o el PROXY (Independientemente de lo que necesite) en base al WSDL (esto es lo mejor osea tener ya creado el WSDL).

SOLUCION #1: Apoyarnos en una o varias IDEs dependiendo de que Framework querer usar y realizar dicha generación.
SOLUCION #2: Bajarnos los comprimidos de cada Framework, mapearlos en variables de entorno y ejecutar los comandos respectivos por tipo de Framework desde consola.
SOLUCION #3: Trabajar con la solución  planteada  WSDL_MavenGenerator_JaxWs_Axis1_Axis2.zip. Ya que solo requiere 2 cosas: Que tengas tu MAVEN configurado y cambiar el plugin del POM.xml en base al framework deseado, de donde de: resources/IMPORTANTE.txt y listo se genera el paquete de clases y objetos requeridos para que los cortes y lo lleves a tu proyecto JAVA donde trabajaras. Ya no necesitaras varias IDES ni nada en un PROYECTO MAVEN lo tienes todo para generar con: AXIS, AXIS2 y JAXWS.

Aqui les comparto los PLUGINs manejados (Por Motivos del BLOG, he cambiado los simbolos de MAYOR / MEJOR por corchetes):

  
     //------------------------------------------------------------------------//
     //----------------------- PLUGIN: JAXWS -----------------------//
     //------------------------------------------------------------------------//

     [!-- GENERACION DE CLASES .JAVA (JAXWS), EN BASE AL [.WSDL] --]
     [plugin]
        [groupId]:[/groupId]
        [artifactId]jaxws-maven-plugin[/artifactId]
        [executions]
           [execution]
              [goals]
                 [goal]wsimport[/goal]
              [/goals]
           [/execution]
        [/executions]
        [configuration]
           [!-- ASIGNACION DE [PAQUETE] DE CLASES GENERADAS --]
           [packageName]pe.com.javaman.dummy.jaxws[/packageName]
           [wsdlDirectory]src/main/webapp/wsdl[/wsdlDirectory]
           [sourceDestDir]src/main/java[/sourceDestDir]
           [!-- keep=true: MAVEN mantiene FUENTES. keep=false: MAVEN regenera FUENTES. --]
           [keep]false[/keep]
           [verbose]true[/verbose]
        [/configuration]
     [/plugin]
   
   
     [!-- GENERACION DE CLASES .JAVA (MAPPING JAXWS), EN BASE A LA [URL]  --]
     [plugin]
        [groupId]org.codehaus.mojo[/groupId]
        [artifactId]jaxws-maven-plugin[/artifactId]
        [executions]
            [execution]
                [goals]
                   [goal]wsimport[/goal]
                [/goals]
                [configuration]
                    [!-- ASIGNACION DE [PAQUETE] DE CLASES GENERADAS --]
                    [packageName]pe.com.javaman.dummy.jaxws[/packageName]
                    [wsdlUrls]
                      [wsdlUrl]http://localhost:8090/GestionDatosUsuarioWS/GestionDatosUsuarioWSService?wsdl[/wsdlUrl]
                    [/wsdlUrls]
                    [sourceDestDir]src/main/java[/sourceDestDir]
                    [!-- keep=true: MAVEN mantiene FUENTES. keep=false: MAVEN regenera FUENTES. --]
                    [keep]false[/keep]
                    [verbose]true[/verbose]
                [/configuration]
            [/execution]
        [/executions]
     [/plugin]

     //----------------------------------------------------------------------//
     //----------------------- PLUGIN: AXIS1 -----------------------//
     //----------------------------------------------------------------------//

     [!-- GENERACION DE CLASES .JAVA (AXIS1), EN BASE AL [.WSDL] --]
     [plugin]
        [groupId]org.codehaus.mojo[/groupId]
        [artifactId]axistools-maven-plugin[/artifactId]
        [version]1.4[/version]
        [executions]
          [execution]
            [goals]
              [goal]wsdl2java[/goal]
            [/goals]
          [/execution]
        [/executions]
        [configuration]
           [!-- ASIGNACION DE [PAQUETE] DE CLASES GENERADAS --]
           [packageSpace]pe.com.javaman.dummy.axis1[/packageSpace]
           [sourceDirectory]src/main/webapp/wsdl/[/sourceDirectory]
           [outputDirectory]src/main/java[/outputDirectory]
           [helperGen]true[/helperGen]
           [verbose]true[/verbose]
        [/configuration]
     [/plugin]
   
     [!-- GENERACION DE CLASES .JAVA (AXIS1), EN BASE AL [.URL] --]
     [plugin]
        [groupId]org.codehaus.mojo[/groupId]
        [artifactId]axistools-maven-plugin[/artifactId]
        [version]1.4[/version]
        [executions]
          [execution]
            [goals]
              [goal]wsdl2java[/goal]
            [/goals]
          [/execution]
        [/executions]
        [configuration]
           [!-- ASIGNACION DE [PAQUETE] DE CLASES GENERADAS --]
           [packageSpace]pe.com.javaman.dummy.axis1[/packageSpace]       
           [urls]
             [url]http://localhost:8090/GestionDatosUsuarioWS/GestionDatosUsuarioWSService?wsdl[/url]
           [/urls]
           [outputDirectory]src/main/java[/outputDirectory]
           [helperGen]true[/helperGen]
           [verbose]true[/verbose]
        [/configuration]
     [/plugin]

     //-----------------------------------------------------------------------//
     //----------------------- PLUGIN: AXIS2 -----------------------//
     //----------------------------------------------------------------------//
   
     [!-- GENERACION DE CLASES .JAVA (AXIS2), EN BASE AL [.WSDL] --]
     [plugin]
        [groupId]org.apache.axis2[/groupId]
        [artifactId]axis2-wsdl2code-maven-plugin[/artifactId]
        [version]1.5.4[/version]
        [executions]
            [execution]
                [goals]
                    [goal]wsdl2code[/goal]
                [/goals]
            [/execution]
        [/executions]
        [configuration]
            [!-- ASIGNACION DE [PAQUETE] DE CLASES GENERADAS --]
            [packageName]pe.com.javaman.generate.axis2[/packageName]
            [wsdlFile]src/main/webapp/wsdl/GestionDatosUsuarioWSService.wsdl[/wsdlFile]
            [outputDirectory]src/main/[/outputDirectory]
            [targetSourceFolderLocation]java[/targetSourceFolderLocation]
            [databindingName]xmlbeans[/databindingName] 
            [unpackClasses]true[/unpackClasses]
            [verbose]true[/verbose]     
            [options]
               [uwc]true[/uwc]
            [/options]        
        [/configuration]          
     [/plugin]

     [!-- GENERACION DE CLASES .JAVA (AXIS2), EN BASE AL [.URL] --]
     [plugin]
        [groupId]org.apache.axis2[/groupId]
        [artifactId]axis2-wsdl2code-maven-plugin[/artifactId]
        [version]1.5.4[/version]
        [executions]
            [execution]
                [goals]
                    [goal]wsdl2code[/goal]
                [/goals]
            [/execution]
        [/executions]
        [configuration]
            [!-- ASIGNACION DE [PAQUETE] DE CLASES GENERADAS --]
            [packageName]pe.com.javaman.generate.axis2[/packageName]
            [wsdlFile]http://localhost:8090/GestionDatosUsuarioWS/GestionDatosUsuarioWSService?wsdl[/wsdlFile]
            [outputDirectory]src/main/[/outputDirectory]
            [targetSourceFolderLocation]java[/targetSourceFolderLocation]
            [databindingName]xmlbeans[/databindingName] 
            [unpackClasses]true[/unpackClasses]
            [verbose]true[/verbose]     
            [options]
               [uwc]true[/uwc]
            [/options]        
        [/configuration]          
     [/plugin]


Para poder descargar el generador de WSDL pulsar: WSDL_MavenGenerator_JaxWs_Axis1_Axis2.zip


Saludos.



LOG4J EN .PROPERTIES

Hola como están en esta oportunidad compartiré la configuración que manejo para el manejo de los diferentes niveles de LOG, mediante el uso de la API: Apache log4j. La configuración de Log4j es fácil y uno la puede manejar desde JAVA como en un fichero de configuración de tipo XML o .PROPERTIES (recomiendo este último).

El texto que presentare es el que contenido de mi fichero:  log4j.properties y a mi gusto es lo mas configurable posible:

 1. Soporta los la generación de los 3 niveles de LOG:  debug, info, error, generando independientemente un fichero de log por cada uno de ellos.
 2. Si uno desea que se generen todos los niveles simplemente debe poner:  og4j.rootLogger=ALL.
 3.Si uno desea que se generen solo algún nivel especifico debe poner:  og4j.rootLogger=debug o info o error.
4. Si uno desea que se genere
LOG en consola de la IDE se debe de poner:  og4j.rootLogger=pantalla.
5. Si uno desea que se genere LOG en archivos externos se debe de poner:  og4j.rootLogger=archivo.
6. Si uno desea que se genero absolutamente todo lo anterior se debe de poner:  log4j.rootLogger=ALL, archivo, pantalla.

Contenido de:  log4j.properties

#########################################################################
################## CONFIGURACION LOGGER: 'Root logger' ##################
#########################################################################

### Configuracion de los 'Niveles' de los Mensajes que se mostraran ###
### ALL                = 'No se toca' ###
### pantalla           = 'Genera LOG en CONSOLA [Todos los niveles]' ###
### archivo            = 'Genera LOG en ARCHIVO EXTERNO [Todos los niveles]' ###
### debug, info, error = 'Genera LOG en ARCHIVO EXTERNO [Todos los niveles]' ###
log4j.rootLogger=ALL, archivo, pantalla 

### Configuracion Mensajes Nivel 'DEBUG' ###
log4j.appender.debug=org.apache.log4j.FileAppender
log4j.appender.debug.file=/logDebug.log
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=[%d{yyyy-MM-dd | HH:mm:ss}] [%c] [%p]: %m%n
log4j.appender.debug.Threshold=DEBUG

### Configuracion Mensajes Nivel 'INFO' ###
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.file=/logInfo.log
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=[%d{yyyy-MM-dd | HH:mm:ss}] [%c] [%p]: %m%n
log4j.appender.info.Threshold=INFO

### Configuracion Mensajes Nivel 'ERROR' ###
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.file=/logError.log
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=[%d{yyyy-MM-dd | HH:mm:ss}] [%c] [%p]: %m%n
log4j.appender.error.Threshold=ERROR

### Configuracion Mensajes para ser mostrados en 'CONSOLA' ###
log4j.appender.pantalla=org.apache.log4j.ConsoleAppender
log4j.appender.pantalla.layout=org.apache.log4j.PatternLayout
log4j.appender.pantalla.layout.ConversionPattern=[%d{yyyy-MM-dd | HH:mm:ss}] [%c] [%p]: %m%n

### Configuracion Mensajes Niveles 'DEBUG, INFO, ERROR, FATAL' ###
log4j.appender.archivo=org.apache.log4j.FileAppender
log4j.appender.archivo.File=/logDebug.log
log4j.appender.archivo.layout=org.apache.log4j.PatternLayout
log4j.appender.archivo.layout.ConversionPattern=[%d{yyyy-MM-dd | HH:mm:ss}] [%c] [%p]: %m%n


jueves, 10 de mayo de 2012

MANEJO DE JMS.

En esta oportunidad mostrare el manejo de la API de JMS para el manejo de mensajería y colas.

El manejo de mensajería es utilizado normalmente por los sistemas de tipo Legacy , debido a la rapidez en la transmisión de datos, como por la facilidad de integración. El formato de los mensajes normalmente enviados (tramas) pueden ser de distintos tipos:

- TRAMAS LINEALES: 01cesar ricardoguerra arnaiz4181613329masculino 
- TRAMAS LINEALES (SEPARADOR): 01|cesar ricardo|guerra arnaiz|41816133|29|masculino|  
- TRAMAS XML:  [usuario] [codigo] 01 [/codigo] [nombres] cesar ricardo [/nombres] [apellidos] guerra arnaiz [/apellidos] [dni] 41816133 [/dni] [edad] 29 [/edad] [sexo] masculino [/sexo] [/usuario]

El ejemplo preparado mostrara una clase utilitaria que facilitara el ENVIO y CONSULTA a una cola JMS.

Para poder probar este ejemplo es necesario que se tenga configurado e iniciado el Servidor de Aplicaciones. Para ello es requerimiento primordial que se desarrolle primero este post: CONFIGURACION-JMS-EN-ORACLE-WEBLOGIC

La clase utilitaria JMS lista para utilizar es la siguiente: 
 
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

/**
 * UtilJMS Util creado para el manejo de JMS. Enviar y Obtener mensajes de tipo:
 *         PUNTO a PUNTO.
 * @author CGUERRA
 */
 public class UtilJMS{

    private Context                      objContexto          = null;
    private QueueConnectionFactory objQueueFactory  = null;
    private QueueConnection     objQueueConexion        = null;
    private QueueSession           objQueueSesion   = null;
    private Queue                       objQueue               = null;
    private QueueSender            objQueueSender   = null;
    private QueueReceiver        objQueueReciver  = null;
    private TextMessage           objTextMensaje    = null;
    private Message                   objMensaje           = null;
  
    private String JNDI_QUEUE_FACTORY = null;   //IMPORTANTE 
    private String JDNI_QUEUE        = null;                //IMPORTANTE 
    private String MENSAJE_JMS    = null;   
  
    private static final String CONTEXTO = "weblogic.jndi.WLInitialContextFactory";     
    private static final String URL               = "t3://localhost:7001";
    private static final String USUARIO     = "javaman";
    private static final String PASSWORD = "12345678";
   
    //Constructores ...
    public UtilJMS( String JNDI_QUEUE_FACTORY, String JDNI_QUEUE ){
           this.JNDI_QUEUE_FACTORY = JNDI_QUEUE_FACTORY;
           this.JDNI_QUEUE         = JDNI_QUEUE;
    }
   
   /**
    * enviarMensajeJMS_punto_a_punto
    * @param mensajeParam
    */
    public void enviarMensajeJMS_punto_a_punto( String mensajeParam ){
      System.out.println( "******** DENTRO DE: [enviarMensajeJMS_punto_a_punto] ********" );
      
      this.MENSAJE_JMS = mensajeParam;
       
      try{
          if( (this.JNDI_QUEUE_FACTORY != null) &&
              (this.JDNI_QUEUE != null) ){

              //---------------- CONFIGURACION [INICIO] ----------------//     
              Hashtable objProperties = new Hashtable();
             
              objProperties.put( Context.INITIAL_CONTEXT_FACTORY, CONTEXTO );
              objProperties.put( Context.PROVIDER_URL,            URL      );
              objProperties.put( Context.SECURITY_PRINCIPAL,      USUARIO  );
              objProperties.put( Context.SECURITY_CREDENTIALS,    PASSWORD );
              //---------------- CONFIGURACION [FINAL] -----------------//
             
              this.objContexto      = new InitialContext( objProperties );
              this.objQueueFactory  = (QueueConnectionFactory)this.objContexto.lookup( this.JNDI_QUEUE_FACTORY );
              this.objQueueConexion = objQueueFactory.createQueueConnection();
              this.objQueueSesion   = this.objQueueConexion.createQueueSession( false, 0 );
              this.objQueue         = (Queue)this.objContexto.lookup( this.JDNI_QUEUE );
              this.objQueueSender   = this.objQueueSesion.createSender( this.objQueue );
             
              //SETEANDO MENSAJE:
              this.objTextMensaje   = this.objQueueSesion.createTextMessage();
              this.objTextMensaje.setText( mensajeParam );
              this.objTextMensaje.setStringProperty( "id_01", mensajeParam ) ;
             
              System.out.println( "- MENSAJE SETEADO: " + this.objTextMensaje.toString() );
              System.out.println( "- OBTENIENDO [TEXT MENSAJE]:   " + this.objTextMensaje.toString() );
             
//ENVIANDO MENSAJE:
              this.objQueueSender.send( this.objTextMensaje );
              System.out.println( "- MENSAJE ENVIADO ...!!!" );
             
//LIMPIANDO & CERRAR CONEXIONES:
              this.limpiarCerrarConexiones(); 
          }
      }
      catch( JMSException e ){
             e.printStackTrace();
      }
      catch( Exception e ){
             e.printStackTrace();
      }  
    }
   
   /**
    * obtenerMensajeJMS_punto_a_punto
    */
    public void obtenerMensajeJMS_punto_a_punto(){
        System.out.println( "******** DENTRO DE: [obtenerMensajeJMS_punto_a_punto] ********" );
      
        try{
            if( (this.JNDI_QUEUE_FACTORY != null) &&
                (this.JDNI_QUEUE != null) ){
               
                //---------------- CONFIGURACION [INICIO] ----------------//     
                Hashtable objProperties = new Hashtable();
               
                objProperties.put( Context.INITIAL_CONTEXT_FACTORY, CONTEXTO );
                objProperties.put( Context.PROVIDER_URL,            URL      );
                objProperties.put( Context.SECURITY_PRINCIPAL,      USUARIO  );
                objProperties.put( Context.SECURITY_CREDENTIALS,    PASSWORD );
                //---------------- CONFIGURACION [FINAL] -----------------//
               
                this.objContexto      = new InitialContext( objProperties );
                this.objQueueFactory  = (QueueConnectionFactory)this.objContexto.lookup( this.JNDI_QUEUE_FACTORY );
                this.objQueue         = (Queue)this.objContexto.lookup( this.JDNI_QUEUE );    
                this.objQueueConexion = this.objQueueFactory.createQueueConnection();
                this.objQueueSesion   = this.objQueueConexion.createQueueSession( false,objQueueSesion.AUTO_ACKNOWLEDGE );  
                this.objQueueReciver  = this.objQueueSesion.createReceiver( this.objQueue );
               
//INICIAR LA OBTENCION DE LOS DATOS DE LA [COLA JMS]:
                this.objQueueConexion.start();
               
                long tiempoEspera = 1000;  //[1 SEG = 1000 MILISEGUNDOS].
               
                for( ;true; ){
                    
//OBTENEMOS TODOS LOS TIPOS DE MENSAJES DE LA [COLA JMS]. 
                     this.objMensaje  = this.objQueueReciver.receive( tiempoEspera );
                   
                     if( this.objMensaje != null){
                         if( this.objMensaje instanceof TextMessage ){
                            
                             //OBTENER LOS MENSAJES DE TIPO TEXTO DE LA [COLA JMS]:
                             this.objTextMensaje = (TextMessage)this.objMensaje;
                             System.out.println( "MENSAJES ENCONTRADO EN [COLA JMS]: " + this.objTextMensaje .getText() );
                            
                             System.out.println( "getJMSCorrelationID: " + this.objMensaje.getJMSCorrelationID() );
                             System.out.println( "getJMSReplyTo:       " + this.objMensaje.getJMSReplyTo()    );
                             System.out.println( "getJMSMessageID:     " + this.objMensaje.getJMSMessageID()  );
                             System.out.println( "getJMSType:          " + this.objMensaje.getJMSType()       );
                            
                             this.objTextMensaje.acknowledge();
                         }
                     }
                     else{
                          System.out.println( "NO HAY MENSAJES EN LA [COLA JMS]" );
                          break;
                   }
                }
               
 //LIMPIAMOS Y CERRAMOS CONEXIONES:
                this.limpiarCerrarConexiones();
            } 
     }
     catch( JMSException e ){
            e.printStackTrace();
     }
     catch( Exception e ){
            e.printStackTrace();
     }          
   }
      
   /**
    * limpiarCerrarConexiones
    */
    public void limpiarCerrarConexiones(){
         
       try{
           if( this.objQueueSender != null ){
               this.objQueueSender.close();
           }
           if( this.objQueueReciver != null ){
               this.objQueueReciver.close();
           }
           if( this.objQueueSesion != null ){
               this.objQueueSesion.close();
           }
           if( this.objQueueConexion != null ){
               this.objQueueConexion.close();
           }
          
           this.objMensaje       = null;
           this.objTextMensaje   = null;            
           this.objQueueSender   = null;
           this.objQueueReciver  = null;
           this.objQueue         = null;
           this.objQueueSesion   = null;
           this.objQueueConexion = null;
           this.objQueueFactory  = null;
           this.objContexto      = null;
          
           System.out.println( "- LIMPIANDO CONFIGURACION ...!!!" );
       }
       catch( JMSException e ){
                  e.printStackTrace();
       }
       catch( Exception e ){
                  e.printStackTrace();
       }       
    }  
  }


Para poder probar este mensaje es necesario setear el USUARIO/PASSWORD del SERVIDOR de APLICACIONES en las variables: USUARIO, PASSWORD y configurar el CONTEXTO y URL. Luego de ellos vasta con hacer lo siguiente:

UtilJMS utilJMS = new UtilJMS( "jms/crgaQueueConexionFactory", "jms/crgaTestQueue" );  

//ENVIAR JMS:
utilJMS.enviarMensajeJMS_punto_a_punto( “TRAMA_CREADA” );

//OBTENER JMS:
utilJMS.obtenerMensajeJMS_punto_a_punto();

Es todo el resultado será mostrado en consola.

Saludos.


CONFIGURACION JMS EN ORACLE WEBLOGIC v11

En esta oportunidad mostrare de una forma detallada y paso a paso, la forma como podemos configurar el Servidor de Aplicaciones ORACLE WEBLOGIC v11 para poder trabajar con cola JMS. La necesidad de hacer este tutorial fue que en su momento cuando requerí en mi trabajo realizar esto no conseguí por ningún lado un tutorial que de manera completa y detallada me ayudara a realizar todo lo que requería. Axial que pensé en desarrollar yo uno mismo de manera mas adecuada y completa.

La API (Java Message Service) , también conocida por sus siglas JMS, es la solución creada por Sun Microsystems para el uso de colas de mensajes. Este es un estándar de mensajería que permite a los componentes de aplicaciones basados en la plataforma Java2 crear, enviar, recibir y leer mensajes. También hace posible la comunicación confiable de manera Síncrona y Asíncrona.

Para trabajar con JMS lo primero que se tiene que hacer es configurar el Servidor de Aplicaciones, en esta oportunidad el ORACLE WEBLOGIC 11. Debemos de crear el Factory, las Colas, etc. Ya que por medio de JNDI creado accederemos a dicha configuración en el servidor.

El RESUMEN de los que vamos a crear y configurar en el servidor es lo siguiente con dichos nombres:

- ALMACENAMIENTO PERSISTENTE [ARCHIVO]: crgaAlmacenPersistenteJMS
- ALMACENAMIENTO PERSISTENTE [JDBC]: crgaAlmacenPersistenteJDBC
- SERVIDOR JMS: crgaJMSServidor
- MODULO JMS: crgaJMSModulo
- SUB DESPLIEGUE: crgaSubDespliegue
- FÁBRICA DE COLAS: crgaQueueConexionFactory
- JNDI FABRICA COLAS: jms/crgaQueueConexionFactory
- COLA JMS: jms/crgaTestQueue
- JNDI COLA JMS: jms/crgaTestQueue

En realidad para la configuración completa son bastantes pasos y la manera mas amigable de entender es a modo visual, para hello he adjuntado el tutorial compledo con mas capturas de pantalla respectivas.

Para descargar el tutorial paso a paso pulsar: AQUI.

En un próximo tutorial, una vez ya configurado el servidor de aplicaciones, mostrare una manera muy fácil de ENVIAR y OBTENER mensajes de una cola JMS con JAVA.