your excuse: It's those computer people in X {city of world}. They keep stuffing things up.
CoffMan Weblog Linux category Java category wiki Image thx to Chenchu Ricochet Robot J2MESimon Says J2ME gameCoffMan WeblogJava stuffLinux stuffImage thx to ChenchuWickleMarihuana Category
   Victor Fariña Infante , info about my own projects and thoughts.
 
login



.:¿?-_-¿?:.
Anton tiene




Powered by

 



Technology, Java, thoughts and projects of Coffman, host of wickle dot com. feel free to make comments.
[Jun 10, 2007]

Hay una cambio de época con la aparición de Appfuse. Antes, en la programacion Java para la web todo era oscuro, para iniciar un proyecto tardabas dias en establecer el esqueleto de la aplicacion, y para añadir funcionalidad, replicabas cientos de lineas que ya tenías en librerías o guardadas en algun archivo de texto.

Con appfuse crear el esqueleto de una aplicacion web con Java es extremadamente sencillo, vamos a ver lo facil que es crear una aplicacion java con las operaciones basicas CRUD .

Instalamos Maven 2, Java 5 y Mysql .(creo que esto no hace falta explicarlo)

Instalamos appfuse en la modalidad mas sencilla empleando para la presentacion JSF (el resto de combinaciones se pueden ver aquí):

mvn archetype:create -DarchetypeGroupId=org.appfuse -DarchetypeArtifactId=appfuse-basic-jsf -DremoteRepositories=http://static.appfuse.org/repository -DarchetypeVersion=2.0-m5 -DgroupId=com.mycompany.app -DartifactId=myproject


Sustituimos com.company.app por el paqquete que queramos y myproject igual.
Ahora generamos con maven todo lo necesario para empezar a desarrollar desde eclipse, nos situamos en el directorio myproject recien creado:

$ mvn integration-test (nos bajamos los jars necesarios y pasamos los tests)
$ mvn jetty:run-war (probamos la simple aplicacion accesible a través de http://localhost:8080)
$ mvn install eclipse:eclipse (instala lo necesario para que el eclipse se entere del proyecto .project y .classpath entre otros)
$ mvn -Declipse.workspace=<path-to-eclipse-workspace> eclipse:add-maven-repo  (para que el eclipse reconozca la variable M2 del appfuse, es necesario ejecutar esto indicando el workspace de nuestro eclipse ~/workspace).Mas aquí.


Ahora que tenemos la base instalada, ya desde el eclipse importamos el proyecto:
File > Import > Existing Projects into Workspace

Empezamos a desarrollar un nuevo POJO llamado Persona con todo lo que le rodea (Modelo, Servicio y Web):
Creamos el paquete com.mycompany.app.model y dentro de el la clase Persona que extiende BaseObject:

package com.mycompany.app.model;
 
import org.appfuse.model.BaseObject;
 
import javax.persistence.Entity;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Column;
 
public class Persona extends BaseObject {
    private Long id;
    private String firstName;
    private String lastName;
 
    /*
     Generate your getters and setters using your favorite IDE:
     In Eclipse:
     Right-click -> Source -> Generate Getters and Setters
    */
}


Sobre la persistencia tenemos toda la info aqui.
Añadimos anotaciones para Hibernate: Entity identifica la clase con la tabla:

@Entity
public class Persona extends BaseObject {

Ahora indicamos cual es la PK (Primary Key) y como se generará:

@Id @GeneratedValue(strategy = GenerationType.AUTO) 
public Long getId() {
    return this.id;
}


El resto de campos se declaran con la anotacion Column:

@Column(name="first_name", length=50)
public String getFirstName() {
    return this.firstName;
}
...
@Column(name="last_name", length=50)
public String getLastName() {
    return this.lastName;
}


Con esto ya tenemos creado nuestro Pojo Persona, ahora mapeamos esta clase dentro del archivo de configuracion de Hibernate (src/main/resources/hibernate.cfg.xml):

<mapping class="com.mycompany.app.model.Persona"/>


Ahora si ejecutamos el siguiente comando maven, genera la tabla de la base de datos asociada a este POJO:

$ mvn compile hibernate3:hbm2ddl


Finalmente para que se genere la capa de servicio y las paginas web ejecutamos:

$ mvn appfuse:gen -Dentity
$ mvn appfuse:install -Dentity

Y probamos la aplicacion en la pagina http://localhost:8080 publicando el resultado con Jetty:
$ mvn jetty:run-war


Como diría Matt Raible ...

Yeah Baby, Yeah:

BUILD SUCCESSFUL
Total time: 9 seconds



by coffman - 00:24:31 |

[Jul 06, 2006]

Interesantisimos son los ultimos documentos que estoy leyendo sobre AOP, una metodologia de trabajo que nos ayuda en un monton de tareas de las que ahora nos ocupabamos usando ñapas o malos hábitos de programación.

Problema

El problema es que la programacion orientada a objetos no escala con facilidad en cuanto se aumentan funcionalidades trasversales o requerimientos al desarrollo del programa. Me refiero a funcionalidades trasversales a funcionalidades que no son intrinsicas al modelo de nuestro desarrollo y que pueden ser externalizadas y aplicadas a multiples desarrollos, como por ejemplo Logging, la seguridad, la persistencia, ... Una clase desarrollada por nosotros a priori no tiene porqué saber como implementar la seguridad, como persistirse a si misma o como logear sus propias acciones.

Solución

La solucion viene de la mano de AOP. Nos permite establecer "puntos de ruptura" en los cuales "salta" la ejecucion de otras clases, realizan tareas y devuelven el control al punto de ruptura. Mediante la definicion en un archivo xml del punto de ruptura (que puede ser un patron en el nombre del metodo por ejemplo), le indicamos a nuestro "cargador de clases" ( tomcat, spring, ...) que ejecute otra clase y luego devuelva el control, todo ello sin necesidad de modificar la clase original por supuesto.

Implementaciones de AOP

Algunas implementaciones de AOP son AspectJ, Aspectwerkz, Jboss AOP, Spring AOP, ... . Aunque probablemente el mas potente (y el que yo uso) sea Spring AOP, quizás no sea el mas adecuado para aprender el funcionamiento de la Programacion Orientada a Aspectos. Yo creo que el mas adecuado para aprender es Aspectwerkz debido a la sencillez de su sintaxis y a que se centra exclusivamente en la AOP.

Conceptos Clave

Cross-cutting concerns:
Un problema cruzado es aquella funcionalidad que es trasversal a nuestra clase, de modo que se pueda implementar a varias clases o incluso programas, por ejemplo Logging
Advice:
Del inglés consejo, es el codigo adicional que queremos añadir a nuestro modelo, que puede ser codigo especifico de log, de persistencia, ...
Point-cut :
El punto de corte, es el punto determinado en la ejecucion de nuestro programa donde queremos aplicar el consejo o codigo adicional.

Articulos y Links Relacionados

http://www.programacion.com/java/articulo/jap_aop/
http://en.wikipedia.org/wiki/Aspect-oriented_programming
http://www.onjava.com/pub/a/onjava/2004/07/14/springaop.html



by coffman - 14:53:24 |

[May 30, 2006]

Esto no pretende ser un tutorial ni mucho menos, mas bien una pequeñas prueba de concepto para la tecnologia RMI.

Recientemente me ha tocado colaborar en un proyecto con una parte cliente y una parte servidor , ambas en entornos unix y separadas fisicamente por firewalls. De modo que para comunicar las 2 partes del software estoy evaluando varias posibilidades, y para cada una de ellas tendre un ejemplo basico de funcionamiento.

En esta primera parte la evaluacion será de RMI
Para la prueba construiremos el "Hola Mundo" en version cliente/servidor
Los archivos necesarios serán:

  • Hello.java (Una interface con lo basico)
  • HelloImpl.java (El Objeto servidor en si mismo, con metodo main para poder ejecutarse)
  • HelloClient.java (El cliente java)


Estos 3 archivos componen la parte servidora (objetos en el lado del servidor)
Hello.java

import java.rmi.Remote;
import java.rmi.RemoteException;
     public interface Hello extends Remote {
        String sayHello() throws RemoteException;
    }

 

 

HelloImpl.java

        import java.rmi.Naming;
        import java.rmi.RemoteException;
        import java.rmi.RMISecurityManager;
        import java.rmi.server.UnicastRemoteObject;

        public class HelloImpl extends UnicastRemoteObject implements Hello {

            public HelloImpl() throws RemoteException {
                super();
            }

            public String sayHello() {
                return "Hola, holita...";
            }

            public static void main(String args[]) {

                // Create and install a security manager
                if (System.getSecurityManager() == null) {
                    System.setSecurityManager(new RMISecurityManager());
                }

                try {
                    HelloImpl obj = new HelloImpl();

                    // Bind this object instance to the name "HelloServer"
                    Naming.rebind("//192.168.0.18/HelloServer", obj);

                    System.out.println("HelloServer bound in registry");
                } catch (Exception e) {
                    System.out.println("HelloImpl err: " + e.getMessage());

                    e.printStackTrace();
                }
            }
        }


policy

grant {
        // Allow everything for now
        permission java.security.AllPermission;
};


Este es para la parte cliente
HelloClient.java


import java.rmi.Naming;
import java.rmi.RemoteException;
public class HelloClient {
        static String message = "blank";
        static Hello obj = null;
        public static void main(String args[]) {
        try {
            obj = (Hello)Naming.lookup("//192.168.0.18" + "/HelloServer");
            message = obj.sayHello();
        } catch (Exception e) {
            System.out.println("HelloApplet exception: " + e.getMessage());
            e.printStackTrace();
        }
        System.out.println("MENSAJE:"+message);
        }

}


Una vez que tenemos y revisamos estos archivos, compilamos y generamos los proxys para que el cliente

remoto pueda acceder al objeto servidor (que simplemente devuelve un mensaje)

javac Hello.java HelloImpl.java
rmic HelloImpl

Lo cual nos genera los .class de Hello.java y HelloImpl.java . Ademas de esto, el comando rmic, genera unos proxys para copiar en el lado cliente son:
HelloImpl_Stub.class y HelloImpl_Skel.class

El archivo policy lo necesitamos en el lado del servidor para dar seguridad al acceso a nuestro objeto, el ejemplo es INSEGURO para un entorno de producción.
Ahora que tenemos toda la parte del servidor lista, ejecutamos el rmiregistry que levanta un servidor  escuchando en el puerto 1099, Este programa se encarga de recibir peticiones de Clientes que intentan localizar objetos servidores y les indica donde se encuentran fisicamente.

Una vez que tenemos levantado el rmiregisty , Levantamos nuestro objeto de lado del servidor:

java -Djava.security.policy=$HOME/Programacion/java/rmi/policy HelloImpl

haciendo referencia al archivo policy antes creado.

En el lado cliente compilamos HelloClient.java y copiamos el Stub y el Skel generados en el servidor, de modo que tengamos:

HelloClient.class
HelloImpl_Skel.class
HelloImpl_Stub.class

y ejecutamos : java HelloClient , que como resultado deberia dar :
vic@coffdeb:rmi$ java HelloClient
MENSAJE:Hola, holita...



by coffman - 12:27:38 |

[Feb 21, 2006]

On the process of learning new technologies, I started with JSF. To test it i try to develop an easy application with some modern IDE that implement this technology. The choosed was Sun Java Studio Creator 2 .
Starting a new application with JSC 2 is easy, just install the IDE, create a new JSF project, and start dragging components into the web page, you can manage the events just clicked on a button and typing the java code associated to the button.

The problems comes when you need to import an external generated code, for example we use appfuse to generate the skel of our apps. At the moment we import it on eclipse without problems. but JSC2 DON'T HAVE an import button ¿??¿¿? ... Wow impressive , i can't believe it. Well ... Them i try to import the code from the CVS repository, but oh oh, it doesn't work, the interface to connect to a repository is a lot of strange, it asks unnecesary questions and, well, we have spent 45 minutes. Trying to configure CVS was a time comsuption task.

Finally


1 hour and we can't start a project using JSC 2, two of the main features of an IDE was import and CVS access , and JSC 2 lacks of them.
I hope JSC 2 include this features in the future because starting a new project is easy and fun, writing web applications fast was a grat thing, and doing it visually was great.



by coffman - 10:28:03 |

[Dec 19, 2005]

Pasos basicos para poner a andar DWR en una aplicacion basada en APPFUSE (1.8.2)

1. Añadir DWR jar en /lib/dwr-1.0
2. Añadir a /lib/lib.properties:


#
# DWR - https://dwr.dev.java.net/ (Direct Web Remoting)
#
dwr.version=1.0
dwr.dir=${lib.dir}/dwr-${dwr.version}
dwr.jar=${dwr.dir}/dwr.jar




3. Añadir al /properties.xml:

<!-- Web -->
<path id="web.compile.classpath">
...
<pathelement location="${dwr.jar}"/>
</path>




=> Read more!



by coffman - 19:17:17 |

[Nov 30, 2005]

Problema
Recientemente tuvimos la necesidad de acceder a un servicio web que nos daba la autenticacion a una cantidad de servicios de un cliente. Este tenia todo centralizado en LDAP y no se permitia el acceso directo al servidor LDAP, solo a traves de un SW que te respondia OK o KO en funcion de si la combinacion login/password era correcta o no. Lo unico que nos dieron es un wsdl que describe el Servicio Web.

Solución
Para empezar con todo esto empezamos a buscar informacion sobre acceder a servicios web via java, y la verdad es que encontramos bastante poco, bastante menos de lo que a mi me gustaría (lo que encontré está en la zona de referencias)
Para poder reproducir todo esto, vamos a hacer un ejemplo.

Implementación
Como ejemplo nos vale el Servicio Web de Google al cual accederemos para que nos corriga las palabras que le introducimos.
El WSDL lo tenemos aqui : Google WSDL

=> Read more!



by coffman - 10:55:47 |

[Dec 20, 2004]

On the last months i start the development of another program, Its codename is JAdminUsers.

JAdminUsers is a Java program that uses SWT as a look and feel framework. Its main goal is administer and maintain LDAP users and groups on a distributed system.This days I am administering a large corporate where all users are maintained at hand . We started to migrate all systems (Solaris, Digital Unix and Linux) to use a central LDAP repository, but we need a tool to add/delete and modify users. The few applciations we can find on the web are useless. Thats the main reason i start the development of JAdminUsers.

Yo can view the project at his wiki There are a few screenshots too.
Current version is 0.3 and Webstartable.



by coffman - 00:17:50 |

[Jul 24, 2004]
The new tool from Maven takes me a headeache and a few days of configuration and learning about it, but in the end i think its a valuable tool and will be simplify my java developments. You can view my new JDiary home generated enterely with maven at the same time that I generate the JNLP to distribute.

What is Maven:
Maven is a Framework for ant. Its POM (project object model) based and with a couple of files you can build the application, generate test reports, and an entire site for the application.

Overview:

All round about one file : project.xml here we define the name of the application, the jars it depends on, where are the CVS, and more information. see sample at the end of the POST.
The sencond important file is project.properties. It store information about plugins properties for maven (as JNLP, SSH deployment, etc ...) again i post my sample file at the end.
The last file is maven.xml (rarely you must modify or create it) but on this case it store ant scripts we need (because maven does not do all ) and goals (on the ant style) to build the application with our own rules.

=> Read more!



by coffman - 17:39:58 |

[Jul 16, 2004]

network map
Page of the project

The problem I find at my work was the next :

The problem:


When you maintain and update a large number of unix (or windows) machines you must review if all machines are UP, and in case of failure you must do something (well it depends on admin ;) ), also you would like to review if all goes well before a weekend ( admins tends to me very vagues).

The solution:


The architecture of the application is simple:

you must rely on a machine (the central server or backup server) here you install NAGIOS (http://www.nagios.org/download/), this is a program in C that monitors the health of each server. You must configure a lot of archives (it takes a half day or so but its nice) in which indicate what servers to monitor and wich service offers each server, the alerts, the methos of communication and so on ...
Ths next step (when you install nagios and test it) is to install sendJabber ( only on CVS at the moment) configure it with a valid account on a jabber server and tell him the user/users to send alerts.

The next is configure again Nagios to send alerts throw sendJabber its so simpe sa adding a line to misccommands.cfg , then you must restart Nagios and all is OK.
Just sit in front your computer and if something fails you must receive an alert on your Jabber client (I recommend GAIM )


I will post a more extense howto on the next days.

TODO:


On future releases onf sendJabber you can intereact with NAGIOS server, send commands and receive status about servers.

and more ...



by coffman - 13:24:18 |

[Jun 09, 2004]

Unicraft is a new project from sourceforge in wich i get involved as developer. Is a pleasure to join this developers group that make use of java technology to port Warcraft 3 to Java environment.
Its a great idea.

The project are in a planning phase , and this is good becaouse is now when all people must contribute to this project, to make a better WarCraft 3 FREE and that runs on all operating systems.


Visit project web page at : http://unicraft.tk/



by coffman - 01:51:14 |

:: Next Page >>


CoffMan Site


Since July 2002
Victor Fariña Infante (aka CoffMan) creator of wIckle.com