Anotaciones y Decoradores en Java

Las anotaciones o decoradores sobre el código se han vuelto muy comunes en los últimos tiempos. Permiten al programador añadir información útil extra ya sea para comentar mejor el código o para modificar la forma de compilar/ejecutar una clase concreta. Son una extensión a Java para permitir la programación orientada a aspectos.

We have three types of annotations based on the moment of usage:

Información para el Compilador

Estas anotaciones permiten al compilador indicar si debe o no omitir errores y warnings o qué hacer con ellos. A nada que se haya trabajado con un IDE Java (como eclipse) probably you would have used this type of annotations. For example, you can use usando @Override on a function to indicate that you are overwriting a method defined on a parent class. 

This annotation is completely optional, but allows both the compiler and the developer to check that they are indeed overwriting existing hierarchical functionality.

Por ejemplo:

public class Parent {     
    public void do(){
        System.out.println("Parent");
     }
}

public class Son extends Parent{     
    usando @Override
    public void do(){
        System.out.println("Son");
     }
}
Anotaciones en Tiempo de Compilación y Despliegue

These annotations allow the compiler to add extra information about how to generate the code. By adding or modifying functionality from that in the source code you can alter how a class behaves. Also to create new classes (based on a file descriptor), etc …

These annotations will only be visible at this point. They are not compiled to the .class files. Therefore they are not available at runtime.

Anotaciones en Tiempo de Ejecución

You can use this annotations on runtime and they work on a very similar way as an interface.

Veamos directamente un ejemplo de cómo crear una anotación Runtime y cómo se puede utilizar. La anotación MyAnnotation se podrá aplicar a elementos de tipo field, es decir, a atributos de una clase:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
     public @interface MyAnnotation {
}

Ahora podemos crear una clase que esté anotada con esta anotación:

public class myObject
 {
 @MyAnnotation
 public String field;
 }

De esta forma, en cualquier otra parte del código, podemos comprobar mediante reflexión si un objeto tiene un campo marcado con la anotación:

Class<?> res = objeto.getClass();
for (Field f : res.getFields()) {
     if (f.isAnnotationPresent(MyAnnotation.class)) {
          System.out.println("OK");
      }
}

Más información:

Notes on the GeoServer Workshop

These are the notes I took on the GeoServer workshop at the last gvSIG Conference.

Data Directory

It is important to change the settings of the geoserver_data_dir in the web.xml file to keep the data each time you restart the application container (like Tomcat). It is also good to check out the other settings as it contains interesting facts such as the type of projections to be used or the size of the cache. There are configurable data on the fly and data not configurable on the fly.

Let’s try adding some data sources to generate the layers. To add a shapefile, you have to copy the file in the same physical server machine. To include the shapefile in GeoServer, look for the option of adding a new shapefile datastore type. If you use the location “file: data /…” you use a relative uri to geoserver. You can also search using the “Browse” and use absolute paths.

Warning: Do not you give permission to any user on the configuration interface because they can see all the physical hard disk in this type of dialog.

Memory Mapped Buffers

It is best to use memory mapped buffers (unless you use Windows) if you have enough RAM, then you will avoid continuous access to physical disk. Also, it is best to reproject from native to declared projection. If the shapefile is very big, calculate the bounding box take some time. This does not happen in real databases where spatial indexes.

GeoServer allows you to insert watermarks in your data (for example to use OpenStreetMap).

When you use database connections, you should check the validate connection option, because you never know when the connection is going to crash.

GeoWebCache

GeoWebCache allows, on the latest version of GeoServer, to set up easily which layers will be cached.

You can use data which varies through time, for example for storms and hurricanes. On the database table, you will have a column for time. You can also use elevation data, but then you have to use it with Google Earth. The interesting thing is that, once you have the data, some hipothetical free visor can be used to support it…

Notes of the gvSIG 2.0 workshop

Estos son los apuntes que tomé sobre gvSIG 2.0 en las últimas Jornadas GvSIG.

Pre-Requisitos

  • Java
  • Eclipse
  • Ant (opcional)
  • Maven (opcional)
  • gvSIG (esto es recursivo :))

La principal ventaja de gvSIG 2.0 es que puedes crear un plugin sin saber cómo funciona gvSIG ni tener que compilarlo. Tenemos una instalación de gvSIG que despliega unos binarios que genera el workspace.. But we don’t have to change the source code. Unless, of course, something doesn’t work (bugs) or we have to add some new functionality to the core. Better if you don’t touch it, ask the developers and they will take care.

Creating the workspace

With the binary, there is a wizard which creates an Eclipse workspace with a default template. That leaves all set up but to compile our extension. It also includes a wizard to easily generate installables. These wizards are accessible through the application, at the application menu.

Org.gvsig.tools is the basic infrastructure library to develop plugins. The main functionality is focused on the registration of extension points, utilities to separate API, implementations, SPI (service provider), and monitoring tasks (which in version 1.0 used to freeze the application). This library also supports events, persistence, etc …

gvSIG Plugins

Una biblioteca es un fichero jar. Cuando nuestra aplicación contiene el archivo jar, org.gvsig.tools prepara e inicializa esta biblioteca dentro del núcleo. Las clases en la biblioteca implementan la interfaz Library (AbstractLibrary).

Los managers (PluginsManager) son el punto de entrada a las funcionalidades. Son como factorías (singletons) (al menos uno por librería) que levanta instancias de las funcionalidades incluídas dentro de la librería. También guarda la configuración del módulo.

Los locators (PluginsLocator) permiten registrar implementaciones de managers. Nos permiten recuperar la implementación de manager de un API en concreto. "Dame el manager de esta librería."

Un plugin es una pieza que aporta una funcionalidad: botones y barras de herramientas, opciones de menús, proveedores de datos y tipos de documentos. Andami no ha evolucionado mucho desde la versión 1.x. Andami es el marco para los complementos.

El plugin siempre tendrá al menos dos ficheros:

  • config.xml que indica las clases que implementan el plugin, las dependencias y los menús
  • package.info que indica la versión, el nombre, el build,... del plugin.

gvSIG Extensions

Una extensión (IExtension) es un conjunto de herramientas asociadas con un complemento dentro de una barra de herramientas o menú y funcionan en conjunto. Un grupo de plugins, puedes decir. La extensión que implementa ExclusiveUIExtension especifica qué herramientas son o no visibles, sin tocar el código del núcleo.

Para crear un nuevo complemento, utilizamos la herramienta de generación de menús de complementos disponibles en la versión de desarrollo. Esto genera el espacio de trabajo automáticamente e instala el complemento desde el cual generamos el complemento. Si no tienes una versión de desarrollo, tendrás que compilar gvSIG de los fuentes..

Conviene ir haciéndolo mientras se leen estos apuntes o puedes perderte.

440/5000 El complemento consta de dos proyectos de maven: org.gvsig.plugin y org.gvsig.plugin.app. org.gvsig.plugin proporciona la funcionalidad de la biblioteca independientemente de gvSIG (lógica de negocios). Puede tener dependencias de biblioteca, pero debe poder operar sin tener que abrir la aplicación. Es decir, no requiere nada de Andami, por ejemplo. En org.gvsig.plugin.app.mainplugin (dentro de org.gvsig.plugin.app) implementaremos la funcionalidad.

Los paquetes "api" deben contener interfaces y los paquetes "impl" deben contener implementaciones.

Ahora el espacio de trabajo está listo para trabajar con Eclipse si importamos el proyecto con el complemento de Maven. Si tomamos una plantilla adecuada para generar las fuentes de los complementos, se realiza casi todo el trabajo (excepto la lógica de negocios exacta de nuestro complemento).

Consejos Finales

Es importante tener un proyecto java para probar nuestro plugin con su propio main, sin tener que iniciar gvSIG. También se recomienda que la biblioteca tenga pruebas unitarias. Es decir, podemos hacer una aplicación con todo el poder de gvSIG, pero sin usar gvSIG en sí, es decir, como si fuera una poderosa biblioteca GIS. Conclusión: si lo hacemos bien, incluso podríamos usar nuestro complemento en otra aplicación sin aplicación ... como GoFleet.

Each plugin contains own installer, which created by a wizard inside the application.

es_ESEspañol