Translate

Mostrando entradas con la etiqueta Java. Mostrar todas las entradas
Mostrando entradas con la etiqueta Java. Mostrar todas las entradas

jueves, 6 de marzo de 2025

Distintas opciones de parseo de XML con JAVA



Hoy me he encontrado con el viejo clásico de como parsear en Java un XML y poco a poco los tiempos han ido cambiado y las técnicas de parseo también haciendo todo más eficiente. Hemos pasado desde la lectura de directamente del xml entero, pasando por leerlo linea al línea, hasta terminar mappeando cada uno de los objetos del XML en POJOS de Java.

Las distintas librerías son SAX, DOM, SIAX y JAXB, simplemente porque quede aquí como referencia, este artículo me parece bastante bueno respecto a las distintas librerías y técnicas para hacerlo.

Cada una tiene sus virtudes en ser eficiente en memoria, poder navegar por el XML, manupular el XML para quitar o poner datos, y hacer un data biding con objetos de Java (Plain Java Objects)


Este artículo me parece bastante bueno y puede ser una gran referencia.


https://www.baeldung.com/java-xml-libraries


Y además hay repositorio de código con muchos ejemplos y opciones:


https://github.com/eugenp/tutorials/tree/master/xml


Referencia para parsear en child nodes con DOM

https://coderanch.com/t/129317/languages/child-elements-DOM-parsing



miércoles, 18 de enero de 2017

Jboss datasources: how to set autocommit to false by default with example

Como cambiar el valor de autocommit  en los data sources de JBOSS  EAP 6.4 con ejemplo práctico:

In this post i´m going to resolve a problem with the jboss datasources, when you open a connection and get it throught a jboss datasource the autocommit mode is setted to true by default.

When you develop a new application where you can control all your code it is not a problem, but when you have  inherited code that you cant change it, for example in a migration from a weblogic to a jboss server it could be a real problem


In my case I had java code inherited from weblogic and in some place of the code i was suffering problems with the autocommit state of my jdbc connection. I could not do commit or rollback becasuse the autocommit was setted to true, and it throw the next exception

java.slq.SQLException: you cannot rollback with autocommit set!

This is because in weblogic 10.3 the jdbc connections have a extrange behavior because if you try to do a rollback with autocommit = true it has no effect butit doesn´t thow an exception. When you migrate this code to Jboss is a real problem that you have to handle.

In order to find a solution I have debugged the inherited code to looking for the classes that has been used to get the datasource connection. I found that the datasource class is WrapperDataSource 



In my case the solution was to create a Wrapper of the class WrapperDataSource in order to add the code to setAutoCommit(false) in the  getConnetion methods, in order to get the connection with autocommit setted to false by default, when the application instace a jdbc connection from Jboss server.


To do this we need to create a java project with the sources and the compiled classes of the this jar: ironjacamar-jdbc-1.0.31.Final-redhat-1.jar in order to modify and compile the WrapperDataSource class. This is the class that Jboss uses to create a new JDBC connection.

You can find this sources in the nex  link or in my github repository in the lib folder.

https://maven.repository.redhat.com/techpreview/all/org/jboss/ironjacamar/ironjacamar-jdbc/1.0.31.Final-redhat-1/

Also we need some jars in order to compile the WrapperDataSource class, the jars are those:

  • ironjacamar-core-api-1.0.31.Final-redhat-1.jar
  • ironjacamar-jdbc-1.0.31.Final-redhat-1.jar
  • jboss-connector-api_1.6_spec-1.0.1.Final-redhat-3.jar
  • jboss-logging-3.1.4.GA-redhat-2.jar
  • jboss-transaction-api_1.1_spec-1.0.1.Final-redhat-3.jar


All jars are in the Jbos EAP 6.4 distribution or in my github repository code too.

https://developers.redhat.com/products/eap/download/



Now in the java project with all the jars (added to the poject build path) and the source files we can make the modification that we need. We only need to create the package org.jboss.jca.adapters.jdbc and copy the class WrapperDataSource.java from the source files into it. If you need to modify more classes take it from the source code, copy in the project and modify it.



Next step is to look up the getConnection Methods and add the setAutocommit(false), after the connection creation,


Be carefull because in this version exists two getConnection methods and i have to modify both.

In next step you have to compile this class and mix with the original classes and create the new jar with my changes. In order to do this i have create an ant script (buidl.xml) into the ant folder which unzip the orginal, jar, compile the modified class and add to the new jar.

--

<?xml version="1.0"?>

<project name="WrapperDataSource" default="build" basedir=".">

 <property file="build.properties"/>
 
 
 <target name="clean" description="Deletes compiled and generated code">
         <delete dir="${build.dir}" />
 </target>
 
 <target name="build" depends="clean" description="build Wrapper">
  <mkdir dir="${build.dir}" />
  <unzip src="${build.dir}/../lib/ironjacamar-jdbc-1.0.31.Final-redhat-1.jar" dest="${build.dir}"/>
  <path id="lib.path.ref">
      <fileset dir="${lib.path.ref}" includes="*.jar"/>
  </path> 
  <javac srcdir="${source.dir}" destdir="${build.dir}" classpathref="lib.path.ref" target="1.6" 
 source="1.6" debug="true"/> <jar   destfile="${jar.dir}/${jar.name}"
         basedir="${build.dir}"         
  />
 </target></project>
--

To build the JAR with the new modified class, be sure to have Apache Ant installed, go to ant directory and execute the "ant" command.

The result shoud be:


The result is in the target/dist foder where you can find the new MyJbossWrapperDataSource.jar



Finally the last step consists in change the original ironjacamar-jdbc-1.0.31.Final-redhat-1.jar by the new MyJbossWrapperDataSource.jar modifiying the Jboss libray module.

To do this action you have to go to your JBOSS EAP6 installation and locate the next path:

[JBOSS_HOME]\modules\system\layers\base\org\jboss\ironjacamar\jdbcadapters\main\

Copy the new MyJbossWrapperDataSource.jar to this location



and modify the module.xml commenting the old jar file and adding the new MyJbossWrapperDataSource.jar

--
<module xmlns="urn:jboss:module:1.1" name="org.jboss.ironjacamar.jdbcadapters">
    <properties>
        <property name="jboss.api" value="private"/>
    </properties>

    <resources>
        <!--resource-root path="ironjacamar-jdbc-1.0.31.Final-redhat-1.jar"/>-->
        <resource-root path="MyJbossWrapperDataSource.jar"/>
        <!-- Insert resources here -->
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="javax.resource.api"/>
        <module name="javax.validation.api"/>
        <module name="org.hibernate.validator"/>
        <module name="org.jboss.as.naming"/>
        <module name="org.jboss.as.transactions"/>
        <module name="org.jboss.common-core"/>
        <module name="org.jboss.jboss-transaction-spi"/>
        <module name="org.jboss.ironjacamar.api"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.threads"/>
        <module name="javax.xml.stream.api"/>
    </dependencies>
</module>

--

You can download my eclipse project from github in the next link, if you want to get the code with this change appied, or make more changes in your jboss datasource.

https://github.com/antuansoft/MyJbossWrapperDataSource

Happy Wrapping!!!


jueves, 15 de diciembre de 2016

Weblogic Jboss Migration issue 1: javax.naming.NameNotFoundException: env/jmx/runtime



Migración Weblogic - Jboss problema 1: obtener el Servidor MBeans


I my new job, we have to migrate original web applications deployed in a Weblogic 10.6.3 Application Server to Jboss EAP6 (Jboss AS7).

This post is about the first problem that i have found. The problem is how to instantate the MBeanServer object that containts all my beans.


The slice of code that instantate a the MBeanServer in weblogic is like that:

//Weblogic way
InitialContext ctx = new InitialContext();
this.mbs = ((MBeanServer)ctx.lookup("java:comp/env/jmx/runtime"));

If you deploy this code in a JBoss, the common error that appears in log is the next one:
javax.naming.NameNotFoundException: env/jmx/runtime

The way to solve this issue is change the context lookup for a FactoryManager 
to get the right MBeanServer.

//JBoss way
import java.lang.management.ManagementFactory;
//another code
//another code
//.....
this.mbs=ManagementFactory.getPlatformMBeanServer();

The good news is that this way works both in Jboss and Weblogic.


viernes, 24 de julio de 2015

X11 connection rejected because of wrong authentication

Esta vez me está tocando trabajar con sistemas un poco antiguos, aquí estamos utilizando un aplicación que WEB que está compilada con JDK1.5, y realizada con Spring y iBatis.

El servidor de aplicaciones es un JBOSS (jboss-4.2.3.GA) donde se carga el war de la aplicación, todo el frontal está hecho con jsf y richfaces. La aplicación está corriendo sobre Linux.¡

El problema que me ha pasado es que una vez delplegada la aplicación en el servidor JBOSS, todo ha ido perfectamente pero al poner en el navegador la URL de acceso a la aplicación esta no cargaba porque de repente el proceso java asociado al servidor de aplicaciones desaparecía.

El proceso de repente no estaba en el listado de procesos activos, y he intentado arreglarlo en principio comprobado que la memoria del proceso no era excesiva, y después ampliándola pero el proceso seguía igual.

Revisando los LOGS la única traza visible era:


18:51:15,521 INFO  [STDOUT] 16/07/2015 18:51:15 DEBUG (es.mi.sd.xxxxx.aspect.ServiceLoggerAspect)  - <<<<<<<<<<<<<<<<<
X11 connection rejected because of wrong authentication.

X connection to localhost:11.0 broken (explicit kill or server shutdown).


La manera de solucionarlo ha sido poner esta línea en los parámetros de arranque de JBOSS,

-Djava.awt.headless=true

Nuestro arranque ha quedado así:

JAVA_OPTS="-Xms512m -Xmx512m -XX:MaxPermSize=1024m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.awt.headless=true"


Ahora el procedimiento sigue vivo y no muere al cargar la primera página de la aplicación.

Referencias:

- Referencia 1

lunes, 9 de febrero de 2015

WSO2: add log4j traces for your service

When you are using WSO2 application server to create your web services, you may want to log debug traces in your web services, but by default the log4j WSO2 configuration doesn't show this kind of debug traces.

In order to show this debug messages you only need to consider your webservice implementation package and add it to log4j WSO2 configuration.

Imagine that your application or webservice package is com.antuansoft.myapp you have to add this lines:

#MY APP DEBUG TRACES:
log4j.logger.com.antuansoft.myapp=DEBUG


at the end of the log4j.properties file that is situated in the next path:

[WSO2-Intallation-path]/repository/conf/log4j.properties

viernes, 2 de enero de 2015

Webservice Example with axis2 part 3: How to define the web services operations in a template class

This is the third post to show how to create a web service with a simple operation and a complex operation based on Axis2.

In this series of posts we are going to show this points:












Now we are going to learn how to create a complete webservice based on a template class. This class is going to be a template with the name of the webservice, the operations (one simple, and one complex) and the input and output paramaters of each operation.

You can see in the picture the first steps that we need to create the webservice. To do this 

  1. Create a Java class (an abstract class) with the operations and specify:
    1. Operation name
    2. Operation input parameters 
    3. Operation output parameters 
We are going to create two operations, one simple operations with basic data types and a second operation with a complex data type in the input and output parameters.

The result is this class

--- Axis2ServiceExample.java

---


viernes, 28 de noviembre de 2014

Webservice Example with axis2 part 2: Understanding a webservice

This is the second post to show how to create a web service with a simple operation and a complex operation based on Axis2.

In this series of posts we are going to show this points:









Now we are going to learn how a webservice works and the main concepts.

The main part of a webservice is the WSDL file that describes the webservice interface. This interface describes the available operations in the webservice and the input and output parameters of all operations. This file will be the defined using a template java class and the java2wsld java tool that transform a java class in a WSDL file.

Another important concept of the webservice is the endpoint, the endpoint is an URL that you have to know in order to use the webservice. This endpoint is where the server are listening for your requests and where the server code are executed when a webservice operation is called. Finally an output is returned to the client in order to response to the request, this is the server part of the webservice.

The WSDL file is always public and you can access it via URL to see the available operations and mainly to build a client using the wsdl2code java tool that can create a collection of java classes based on a WSDL file in order to use the webservice. With this client you can invoke the available operation of the webservice, this is the client part of the webservice.

This comunication bettwen the client and the server part of the webservice is made by the soap protocol (Simple Object Access Protocol). 




Example:

We have the webservice named Axis2ServiceExample  with the next operation:

Name: simpleOperation
Input Parameters: number1: Integer, number2: Integer
Output Parameters: Integer - Return the add of the input numbers.

WSDL File: http://localhost:9763/services/Axis2ServiceExample?wsdl
endpoint:  http://localhost:9763/services/Axis2ServiceExample/

All of this things are defined in the WSDL file, in the next sections we will see how to the create all parts of the webservice and call to the operation.

References:





domingo, 9 de noviembre de 2014

Webservice Example with axis2 part1: Setting environtment

This is the first post to show how to create a web service with a simple operation and a complex operation based on Axis2.

In this series of posts we are going to show this points:

The first thing to do is set up the necesary environtment to create the web service. Download the next sofware and configure the environment variables:

•    Java SDK version 1.6.0_45 or later.
•    Windows environment variable JAVA_HOME pointing to Java location (C:\Program Files\Java\jdk1.6.0_45)
•    Eclipse IDE version 4.3 Kepler or later.
•    Apache Maven version 3.1.1 (Embedded in IDE or installed in local machine to use it in command line console).
•    Add the apache Maven bin directory path to the Windows environment variable Path
•    Apache Ant version 1.9.4, installed in your local machine.
•    Add the apache Ant bin directory path to the Windows environment variable Path
•    Apache axis2 version 1.6.0  (binary distribution). Libraries XMLBeans version 2.3.0 and axiom version 1.2.11 are included in axis2.
•    Windows environment variable AXIS2_HOME pointing to Axis2 location (C:\axis2-1.6.0)
•    WSO2 application server version 4.0.1 to deploy Web services.  (you have to download the version 5.0.0 in the download page)

The next step is check if all the elements are properly installed.

JAVA
Open a dos command window and execute java -version





ECLIPSE
Execute the eclipse.exe in your eclipse installation



APACHE MAVEN

Open a dos command window and execute mvn -version





ANT
Open a dos command window and execute ant -version



AXIS2
Open a dos command and execute echo %AXIS2_HOME% and check that path y correct.



WSO2 - Application Server
Open a dos windows and run the server using this command.
[WSO2-Installation-folder]/bin/wso2server.bat



Open browser and copy the url that appears in the last line of the output

Enter user admin and password admin





If you are here everything has going ok.



    martes, 7 de enero de 2014

    Oracle JDBC: Como usar una secuencia en un INSERT y recuperar el valor generado

    La problemática de hoy surge cuando tengo que hacer un INSERT en mi tabla de notificaciones y necesito que la clave primaria de mi notificación se una valor único.

    Lo primero que se te ocurre y en lo que puedes caer en la tentación es en coger el valor más alto de las que ya hay insertadas y sumarle 1.


    String strSQL="select max(notif_id) from notifications";
    pstmt = conn.prepareStatement(strSQL);
    ResultSet rs = pstmt.executeQuery();            
    int uniqueId = (rs!=null && rs.next())?rs.getInt(1)+1:0;
    


    Pero inmediatamente te das cuenta de que eso puede llevar a conflictos si hay muchas inserciones a la vez y alguno puede duplicar la clave.

    Así que lo mejor es crear una secuencia en Oracle y usarla en nuestro INSERT.

    Con TOAD podemos crear una secuencia fácilmente llamada NOTIF_ID_SEQ con los siguientes parámetros




    Y utilizar la en nuestra INSERT llamando al operador NOTIF_ID_SEQ.nextval


    String strSQL="insert INTO NOTIFICATIONS " +
                  "(USER_ID,PROVIDER_ID,NOTIF_ID) " +                 
                  "VALUES (?,?,NOTIF_ID_SEQ.nextval)";
                                                                                         
    pstmt = conn.prepareStatement(strSQL);
    pstmt.setString(1, userId);               
    pstmt.setInt(2, providerId); 
    pstmt.executeUpdate(); 
    


    Con esto garantizamos que el valor de nuestro identificador es único y es el dado por nuestra secuencia.

    Otra problemática que nos surge inmediatamente en esta casuistica es que podemos querer recuperar el valor generado por la secuencia para usarlo en otro lugar.

    Para ello utilizamos el método getGeneratedKeys() del PrepareStatement pero debemos decirle al PreparedStatement que columnas son las que se autogeneran en un Array de Strings en nuestro caso "NOTIF_ID"

    Veamos un ejemplo:


    String generatedColumns[] = {"NOTIF_ID"};                                               
    pstmt = conn.prepareStatement(strSQL,generatedColumns);
    
    String strSQL="insert INTO NOTIFICATIONS " +
                  "(USER_ID,PROVIDER_ID,NOTIF_ID) " +                 
                  "VALUES (?,?,NOTIF_ID_SEQ.nextval)";
                                                                                         
    pstmt = conn.prepareStatement(strSQL);
    pstmt.setString(1, userId);               
    pstmt.setInt(2, providerId); 
    pstmt.executeUpdate(); 
    
    //Get the generated key
    ResultSet generatedKeys = pstmt.getGeneratedKeys();
    if (null != generatedKeys && generatedKeys.next()) {
      int primaryKey = generatedKeys.getInt(1);
      System.out.println(primaryKey);
    }
    



    Referencias:

    how to get the inserted row primary key with out  using select statement

    getGeneratedKeys()

    How to use Oracle sequence in preparedstatement

    Oracle Java JDBC: Get Primary Key Of Inserted Record




    jueves, 2 de enero de 2014

    Oracle: Query para restar minutos a la fecha del sistema

    Oracle: Query to subtract minutes from system date

    La problemática de hoy viene dada por la necesidad de recuperar en una base de datos Oracle los usuarios que han tenido interacción con la aplicación en los últimos 15 minutos.

    En mi caso tengo un campo en mi tabla de usuarios que registra cuando ha sido la última actualización o acceso de este usuario a la aplicación.

    La query a realizar se la siguiente:

    SELECT * FROM users WHERE LAST_UPDATED_DATE > SYSTIMESTAMP - (?/1440)

    Donde ? tenemos que sustituirlo por el número de minutos que queremos restar a la fecha del sistema.

    SYSTIMESTAMP nos devuelve la fecha del sistema incluyendo hora minutos y segundos con el TimeZone de la base de datos.

    El valor de 1440 es porque un día tiene 1440 minutos 24 x 60. Y usamos minutos en este formato ya que lo que se resta normalmente a SYSTIMESTAMP son días.

    Por lo tanto mi query final es la siguiente:

    PreparedStatement pstmt = null;       
    ResultSet rSet = null;
    Connection conn = null;        
    int minutes = 15;
    ........
    ........
    String strSQL="select from users where LAST_UPDATED_DATE > SYSTIMESTAMP-(?/1440)";
    
    pstmt = conn.prepareStatement(strSQL);
    pstmt.setInt(1, minutes);                     
    rSet = pstmt.executeQuery();
    
    
    Referencias:
    
    
    Time Aritmetic with Oracle
    SYSTIMESTAMP 

    lunes, 25 de marzo de 2013

    java -classpath alternativa a java -jar

    Este post que o pongo hoy es debido a la guerra que me está dando la generación de un archivo JAR ejecutable de tal modo que todas las librerías de las que depende para funcionar estén dentro del JAR.

    El programa es un método public static void main() de toda la vida que queremos que se arranque por línea de comandos para realizar una serie de operaciones como un daemon ejecutándose cada cierta periodicidad.

    El programa lazado en eclipse se lanza perfectamente y funciona, pero una vez empaquetado con eclipse para ejecutarse como Jar no funciona.

    La manera en la que he intentado ejecutarlo es la siguiente:


    java -jar DaemonBatch-1.1.0.jar

    JAR

    y dentro del Jar tenemos su correspondiente archivo de Manifest.MF con todo lo necesario para la ejecución, la clase a ejecutar  las dependencias y el classpath.


    Manifest-Version: 1.0
    Rsrc-Class-Path:  aspectj-1.6.12.jar
     spring-security-3.1.0.RELEASE-ldap.jar spring-security-3.1.0.RELEASE-
     config.jar httpcore-4.1.jar aopalliance-1.0.jar spring-security-3.1.0
     .RELEASE-core.jar org.springframework-3.1.1.RELEASE-transaction.jar j
     stl-1.2-api.jar blazeds-4.0.0.14931-rds-server.jar javamail-1.4.5.jar
      org.springframework-3.1.1.RELEASE-instrument.jar spring-security-3.1
     .0.RELEASE-acl.jar spring-security-3.1.0.RELEASE-web.jar .............
    Class-Path: .
    Rsrc-Main-Class: com.antuansoft.batch.main.Main
    Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader


    Lo he exportado de diferentes formas pero siempre me ha dado el mismo error


    java.io.FileNotFoundException: URL [rsrc:com/antuansoft/batch/task/] cannot be resolv
    ed to absolute file path because it does not reside in the file system: rsrc:com
    /antuansoft/batch/task/


    Así que he optado por descomprimir el JAR, poner todas las librerias .jar en un directorio lib y ejecutar el siguiente comando para que funcione sin problemas.


    java -classpath .;lib/* com.gniux.batch.main.Main

    Y ha arrancado sin ningún problema.

    Así que si en tu programa no es necesario que este se empaquete todo en un JAR, una alternativa es la que os acabo de proponer.

    De todas formas seguiremos investigando.










    jueves, 21 de febrero de 2013

    Configuración de Log4j para un proyecto WEB con un archivo de properties

    Log4j web Project configuration

    El post de hoy surge por la necesidad de configurar correctamente los logs que salen por consola en nuestros proyectos WEB.

    Se acabó el utilizar el el System.out.println.



    La configuración es muy variada:

    1 - Configuración por programación: Desde un public void Main:
    2 - Configuración desde un XML
    3 - Configuración desde un archivo de properties.

    pero aquí me voy a centrar en mi caso particular que es la configuración de log4j en un proyecto WEB a través de un archivo de properties.

    1 - Lo primero que necesitamos tener es la última versión de nuestra librería favorita log4j.

    2 - Configuramos un proyecto WEB en nuestro IDE favorito, eclipse en mi caso.

    3 - Ponemos la librería (log4j-1.2.17.jar) en el directorio WEB-INF/lib

    4 - Creamos y configuramos un servlet para poder realizar las pruebas, en mi caso con Spring Framework.

    Una vez que tenemos el proyecto correctamente configurado vamos a lo que nos interesa

    5 - Creamos el archivo log4j.properties en el raíz del directorio src para que esté en la raíz de nuestras clases, con la siguiente configuración

    --
    # log4j.properties for 
    
    # Set root category priority to DEBUG and its only appender to Console.
    log4j.rootLogger=debug,stdout
    
    
    #appender definition
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.Target=System.out
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern= linea %L %c %d %m  %n
    
    
    --

    Con estos pasos ya sería suficiente para que aparecieran trazas pero vamos a ver como configurar, pero vamos a entender un poco como funciona.

    Tenemos que diferencias entre loggers, appenders y layouts

    Un logger es el elemento que se encarga de recopilar y generar los logs en base a una configuración de un appender y un patternlayout. En nuestro ejemplo el logger es stdout

    Un appender es donde se almacenan los logs generados por los loggers, hay muchos tipos lo más usados el org.apache.log4j.ConsoleAppender para mostrarlo por consola. Para ampliar información en las referencias hay un montón de tipos.

    Un layout es la manera en que se imprime la traza, es decir que información escribirá el logger en el appender.

    El rootLogger = Es el padre de todos los appenders y la cong

    Con el código que hemos puesto en la clase log4jtest.java y con la configuración de log4j.properties en debug nuestras trazas que aparecerían en la consola serian las siguientes:


    linea 22 org.antuansoft.mvc.log4jtest 2013-02-16 02:48:15,057 debug
    linea 23 org.antuansoft.mvc.log4jtest 2013-02-16 02:48:15,058 error
    linea 24 org.antuansoft.mvc.log4jtest 2013-02-16 02:48:15,058 info
    linea 25 org.antuansoft.mvc.log4jtest 2013-02-16 02:48:15,058 fatal
    linea 26 org.antuansoft.mvc.log4jtest 2013-02-16 02:48:15,058 trace  Esta no debe de salir

    Modificando la línea:


    log4j.rootLogger=debug,stdout

    podemos modificar el nivel de nuestros logs para que aparezcan o no las trazas que queremos.




    Si pongo

    log4j.rootLogger=error,stdout

    al configurarlo para que salgan las trazas de error, las dos únicas líneas que aparecerían serían:



    linea 24 org.antuansoft.mvc.log4jtest 2013-02-16 02:48:15,058 info
    linea 25 org.antuansoft.mvc.log4jtest 2013-02-16 02:48:15,058 fatal


    UPDATE:

    Si lo que quieres es modificar el nivel de log de uno de los paquetes de tu proyecto nada más, lo que tienes que hacer es añadir la siguiente línea al log4j.properties

    log4j.category.com.mypackage=LEVEL
    Por ejemplo:
    log4j.category.org.antuansoft.mvc=info
    Eso haría que sólo las trazas que contengan ese paquete se muestren en modo info y el resto en el modo que hayamos especificado el rootlogger.



    Aquí dejo un enlace con el de código y información ampliada  en los enlaces.

    Código en githup, ejemplo MVC con SpringFramework y log4j

    Para acceder sólo hay que ponerlo en un servidor de aplicaciones tomcat y ejecutar la siguiente url

    http://localhost:8080/AntuanSoft_BASE_WEB_SPRING_PROJECT/log4jtest





    Referencias: Para más información este tutorial cubre todos los casos http://www.javatutoriales.com/2011/04/log4j-para-creacion-de-eventos-de-log.html
    http://www.arquitecturajava.com/log4j-y-pattern-layouts/
    http://stackoverflow.com/questions/1725958/how-do-you-change-a-packages-log-level-using-log4j

    martes, 22 de enero de 2013

    Generación de IDs únicos en ActionsScript y en Java

    Para la generación de IDS únicos tanto en Java tenemos dos librerías incluidas dentro de las SDK de Java y de Flex que nos ayudan mucho a realizar esta tarea.

    Java:

    String uuid =  java.util.UUID.randomUUID().toString();

    ActionScript:

    var uuid:String  = UIDUtil.createUID();


    lunes, 19 de noviembre de 2012

    Java: Formato de Fecha en español

    Este problema me ha surgido porque tengo que formatear la fecha al siguiente formato "11 de noviembre de 2012" pero con el formato strandar lo que nos devuelve es "11 de November de 2012".

    Para conseguir esto lo que hay que hacer es poner el Locale al SimpleDateFormat que se encarga de formatear de la fecha.

     SimpleDateFormat format = new SimpleDateFormat("dd 'de' MMMM 'de' yyyy",new Locale("es"));
    

    Referencia:

    SimpleDateFormat en Java 7

    jueves, 30 de agosto de 2012

    SpringSecurity: Truco para securizar URLS de tu aplicación

    El parámetro "<sec:http pattern=" de Spring Security sirve para mapear las URL que atacan a nuestra aplicación y poderles aplicar seguridad a cada uno de ellos.

    La experiencia aculada en nuestros proyectos nos ha llevado a la conclusión de que para configurar correctamente la seguridad de la aplicación y no tener problemas con las URL lo mejor es agrupar los patrones.

    Nuestro sistema de seguridad consistía en que nosotros hacemos login contra un CAS server y una vez obtenida la autenticación este debía de redirigirnos a la aplicación a la que tenemos acceso. El problema era que aleatoriamente nos daba el acceso o no, generalmente nada más hacer log-in no nos daba acceso pero si recargábamos la página si nos daba acceso.

    Nuestra configuración, erronea e incial era la siguiente:

     <sec:http pattern="/messagebroker/**" security="none"/>
     <sec:http pattern="*.swf" security="none"/>
     <sec:http pattern="*.html" security="none"/>  
     
     
     
     <sec:http entry-point-ref="entryPoint" auto-config="false" pattern="/*">
      <sec:intercept-url pattern="/**" access="ROLE_AUTHENTICATED"/>
     </sec:http>
    
    
    


    La solución a este problema fue juntar los patrones e incluso segregarlos un poco más y diferenciar la distintas URLs

     <sec:http pattern="*.swf" security="none"/>
     <sec:http pattern="*.html" security="none"/>  
     
     <sec:http pattern="/**">
      <sec:anonymous enabled="true"/>
      <sec:intercept-url pattern="/messagebroker/**" access="ROLE_ANONYMOUS"/>
      <sec:intercept-url pattern="/access/login" access="ROLE_ANONYMOUS"/>
      <sec:intercept-url pattern="/access/loginsuccess" access="ROLE_AUTHENTICATED"/>
      <sec:form-login login-page="/access/login"/>  
     </sec:http>
    
    
    
    

    miércoles, 11 de julio de 2012

    Spring Data y QueryDSL operador like

    QueryDSL like operator

    Prerrequisitos: Conocimientos medios de QueryDsl.

    El problema que resolvemos a continuación es el operador like usando QueryDSL. Si no quieres leerte todo el rollo te adelanto que el operador que buscas es containsIgnoreCase en vez de like pero tiene alguna pega que expongo a continuación.

    Si has llegado hasta aquí buscando por google supongo que ya tendrás configurado tu entorno y QueryDsl para realizar tus consultas. Como ya sabemos la ventaja que te da QueryDsl es nos permite construir una query directamente sobre el código java de nuestro service.

    Imaginemos que tenemos  el siguiente pojo

    ----
    @Entity
    @Document
    public class Course implements Serializable {
     
     
     private static final long serialVersionUID = -7251789829032925885L;
     
     
     @Id
     private String id = UUID.randomUUID().toString();
     private String name; 
     private String description;
     private String companyOwner;
     private String metodology;
    
    ---
    

    Una vez configurado QueryDsl automáticamente nos lo transforma nuestro pojo en el siguiente código.

    ----
    /**
     * QCourse is a Querydsl query type for Course
     */
    @Generated("com.mysema.query.codegen.EntitySerializer")
    public class QCourse extends EntityPathBase<Course> {
    
        private static final long serialVersionUID = 430564814;
    
        public static final QCourse course = new QCourse("course");
    
        public final StringPath companyOwner = createString("companyOwner");
    
        public final StringPath description = createString("description");
    
        public final StringPath id = createString("id");
    
        public final StringPath metodology = createString("metodology");
    
    
        public QCourse(String variable) {
            super(Course.class, forVariable(variable));
        }
    
        public QCourse(Path<? extends Course> entity) {
            super(entity.getType(), entity.getMetadata());
        }
    
        public QCourse(PathMetadata<?> metadata) {
            super(Course.class, metadata);
        }
    
    
    ---
    

    Esto nos permite hacer queries directamente con código java

    ----
    BooleanBuilder builder = new BooleanBuilder();
       
       builder.and(QCourse.course.id.eq("id1"));
       builder.and(QCourse.course.name.like("Matematica"));
    
    List<Course> data = (List<Course>) courseDao.findAll(builder.getValue()); 
          
       return data;
    
    ---
    


    El problema es cuando queremos hacer una búsqueda sobre un campo String con lo que en SQL sería el operador LIKE, como por ejemplo Name like %Matematica% 

    QueryDsl tiene el operador like pero su lo utilizamos nos da el siguiente error:
     
     
    ----
    java.lang.UnsupportedOperationException: Illegal operation course.name like Matemáticas
     at com.mysema.query.mongodb.MongodbSerializer.visit(MongodbSerializer.java:225)
     at com.mysema.query.mongodb.MongodbSerializer.visit(MongodbSerializer.java:34)
     at com.mysema.query.types.expr.BooleanOperation.accept(BooleanOperation.java:52)
     at com.mysema.query.mongodb.MongodbSerializer.handle(MongodbSerializer.java:39)
     at com.mysema.query.mongodb.MongodbSerializer.visit(MongodbSerializer.java:98)
     at com.mysema.query.mongodb.MongodbSerializer.visit(MongodbSerializer.java:34)
     at com.mysema.query.types.OperationImpl.accept(OperationImpl.java:81)
     at com.mysema.query.mongodb.MongodbSerializer.handle(MongodbSerializer.java:39)
     at com.mysema.query.mongodb.MongodbQuery.createQuery(MongodbQuery.java:330)
     at com.mysema.query.mongodb.MongodbQuery.createCursor(MongodbQuery.java:240)
     at com.mysema.query.mongodb.MongodbQuery.createCursor(MongodbQuery.java:235)
     at com.mysema.query.mongodb.MongodbQuery.list(MongodbQuery.java:221)
     at org.springframework.data.mongodb.repository.support.QueryDslMongoRepository.findAll(QueryDslMongoRepository.java:113)
    
    
    ---
    
     
       
      La alternativa para que la operación sea la que deseamos es containsIgnoreCase


    ----
    
    builder.and(QCourse.course.name.containsIgnoreCase("Matemati"));
    
    ---
    
     
      
      Esta búsqueda recuperará cualquier palabra en el nombre que contenga Matemati como por ejemplo, Matematica, Matematico, Matematicas ya esté en mayúsculas o minúsculas.


    Lo que no encontrará este tipo de búsqueda son acentos, por ejemplo Matemáticas, así que no es una búsqueda full text pero se aproxima bastante.




    lunes, 30 de abril de 2012

    MongoDB Error: java.lang.NoSuchFieldError: socketKeepAlive

    Realizando unos tests de Junit con ANT, usando la tarea , sobre la aplicación que estamos creando que utiliza MongoDB nos apareció el siguiente error poco descriptivo:

     
    
        [junit] Grave: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1c81b84] to prepare test instance [com.xxxxx.xxxx.integration.ContentTemplateIntegrationTest@7c329d]
        [junit] java.lang.IllegalStateException: Failed to load ApplicationContext
        [junit]  at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
        [junit]  at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
        [junit]  at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
        [junit]  at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
        [junit]  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
        [junit]  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
        [junit]  at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
        [junit]  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
        [junit]  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
        [junit]  at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
        [junit]  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
        [junit]  at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
        [junit]  at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
        [junit]  at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
        [junit]  at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
        [junit]  at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        [junit]  at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
        [junit]  at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
        [junit]  at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
        [junit]  at junit.framework.JUnit4TestAdapter.run(JUnit4TestAdapter.java:39)
        [junit]  at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:518)
        [junit]  at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1052)
        [junit]  at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:906)
        [junit] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo': Cannot create inner bean '(inner bean)' of type [org.springframework.data.mongodb.core.MongoOptionsFactoryBean] while setting bean property 'mongoOptions'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.data.mongodb.core.MongoOptionsFactoryBean]: Constructor threw exception; nested exception is java.lang.NoSuchFieldError: socketKeepAlive
        [junit]  at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:281)
        [junit]  at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125)
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
        [junit]  at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
        [junit]  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
        [junit]  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
        [junit]  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        [junit]  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
        [junit]  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
        [junit]  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
        [junit]  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:103)
        [junit]  at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
        [junit]  at org.springframework.test.context.support.DelegatingSmartContextLoader.loadContext(DelegatingSmartContextLoader.java:228)
        [junit]  at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
        [junit]  at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
        [junit]  ... 22 more
        [junit] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.data.mongodb.core.MongoOptionsFactoryBean]: Constructor threw exception; nested exception is java.lang.NoSuchFieldError: socketKeepAlive
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
        [junit]  at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:270)
        [junit]  ... 39 more
        [junit] Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.data.mongodb.core.MongoOptionsFactoryBean]: Constructor threw exception; nested exception is java.lang.NoSuchFieldError: socketKeepAlive
        [junit]  at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
        [junit]  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
        [junit]  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
        [junit]  ... 43 more
        [junit] Caused by: java.lang.NoSuchFieldError: socketKeepAlive
        [junit]  at org.springframework.data.mongodb.core.MongoOptionsFactoryBean.(MongoOptionsFactoryBean.java:64)
        [junit]  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        [junit]  at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        [junit]  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        [junit]  at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
        [junit]  at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
        [junit]  ... 45 more
        [junit] Tests run: 2, Failures: 0, Errors: 2, Time elapsed: 1,098 sec
    
    
    
    Esto se debe a la configuración de la conexión de la aplicación con MongoDB en la que no detecta el parámetro socket-keep-alive
     
    
     <mongo:options connections-per-host="8"
                        threads-allowed-to-block-for-connection-multiplier="4"
                        connect-timeout="1000"
                        max-wait-time="1500"
                        auto-connect-retry="true"
                        socket-keep-alive="true"
                        socket-timeout="1500"
                        slave-ok="true"
                        write-number="1"
                        write-timeout="0"
                        write-fsync="true"/>
    
    
    El error es poco descriptivo porque al principio creíamos que era un problema de versiones de los distintas librerías de MongoDB y de Spring Data JPA, pero en realidad el error se produjo porque la librería JAR de conexión de con MongoDB no estaba correctamente importada en el POM del proyecto.

     Una vez importado el jar mongo-2.7.3.jar todo funcionó correctamente y los tests pasaron correctamente.