Using more than one property file in Spring MVC

Spring is one of the most important, powerful and also complex frameworks in the actual Java panorama.

»
Author's profile picture acanimal

Symfony2, Doctrine, FOSUserBundle and fixtures for functional testing

I have an application built with Symfony2 framework which uses the Doctrine2 ORM for persistence. The issue is I need to make functional tests allowing to purge and initialize the database with doctrine fixtures.

Before to start

In the project I have used the FosUserBundle, to allow better user login, registration, etc and DoctrineFixturesBundle, which allow to fill a database with fixtures based on our Doctrine entities.

To load doctrine fixtures into database you need to execute the command line:

php app/console doctrine:fixtures:load

That means for each test you need to clean up the database and load the fixtures manually.

Our objective is the automate this process before executing each test.

Doctrine fixtures and the creation of FOSUserBundle users

Because we are using Doctrine fixtures we need a class that implements FixtureInterface interface (see documentation). The problem is we want to create FOSUserBundle user instances and that requires we have access to the container to get a reference to the user management service, so we need to set access to the container too. Nothing we can't find in the documentation:

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyFixtures implements FixtureInterface, ContainerAwareInterface {

    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null) {
        $this->container = $container;
    }

    public function load(ObjectManager $manager) {

        $userManager = $this->container->get('fos_user.user_manager');

        // Create a new user
        $user = $userManager->createUser();
        $user->setUsername('user');
        $user->setEmail('user@domain.com');
        $user->setPlainPassword('user_password');
        $user->setEnabled(true);

        $manager->persist($user);
        $manager->flush();

The test class

In your test class you need to define the setUp method that is responsible to prepare the database fixtures.
The setup method makes two important things, first purge the tables on the database to remove any previous changes make by previous tests and, second, initialize the database with a set of fixtures.

class YourTestClass extends WebTestCase {

    private $em;

    /**
     * Set up database and fixtures before each test
     */
    public function setUp() {

        $client = self::createClient();
        $container = $client->getKernel()->getContainer();
        $em = $container->get('doctrine')->getManager();

        // Purge tables
        $purger = new \Doctrine\Common\DataFixtures\Purger\ORMPurger($em);
        $executor = new \Doctrine\Common\DataFixtures\Executor\ORMExecutor($em, $purger);
        $executor->purge();

        // Load fixtures
        $loader = new \Doctrine\Common\DataFixtures\Loader;
        $fixtures = new \Path\To\Your\Fixtures\MyFixtures();
        $fixtures->setContainer($container);
        $loader->addFixture($fixtures);
        $executor->execute($loader->getFixtures());
    }

    ...
}

Note how

we need to inject a reference to the container in the fixtures class.

It is necessary to make it by hand. The dependency isn't injected automatically because we are running a PHPUnit test, not a Symfony2 application.

»
Author's profile picture acanimal

A visual exploration of the Nobel Prize history

After some time in mind, finally I have got some free time to spend creating a web page to show the information related to Nobel Prizes.

»
Author's profile picture acanimal

The OpenLayers fallen and Leaflet arise... sure???

I wrote this post some months ago, before I publish the OpenLayers Cookbook, but I never published it thinking it could start a flame war instead a constructive thread.

Today, after a twitter conversation (thanks @Starefossen @brymcbride @erilem @mourner and @LeafletJS) I think it is time to publish it.

»
Author's profile picture acanimal

SimplyWrite, a free web distraction writing tool

I like to write and I like programming so the obvious consequence were to write some tool to write. More or less this is the history of SimplyWrite.

»
Author's profile picture acanimal

The Book: GeoServer Beginner's Guide

GeoServer is one of the most importants open source geospatial servers nowadays. Implemented in Java, based on the powerful GeoTools libraries, GeoServer offers a great degree of interporability publishing data from major spatial data sources using Open Geospatial Consortium (OGC) standards.

»
Author's profile picture acanimal

Things I learned creating a jQuery Plugin (Part II)

This post is the continuation of the series Things I learned creating a jQuery Plugin.

In the first part we have seen how the structure of a jQuery plugin must be, the plugin entry point (so called wrapper function) and how we can control the behavior of a method as a getter or setter.

Define default options

Your plugin more probably will accept different set of options to allow some configuration. For these reason it is important to define a set of default options which will be applied in cases where no options are specified by the user. Place it within the jQuery wrapper function is a good practice:

//
// Default options
//
$.fn[pluginName].defaults = {
    opt_A: ""
};

Encapsulate your plugin code

A good practice is to encapsulate the logic of our plugin within a function, this way our plugin's entry point function can easily initialize or call the right method.

For example, in a really simple wrapper function, that simply initializes a plugin's instance on each selected element, we could write something like:

$.fn[pluginName] = function(options) {
    return this.each(function() {
        new Plugin(this, options);
    });
}

The plugin constructor

The main part of your plugin is the constructor function. Usually this function is responsible to initialize the plugin, store a reference to the selected element or merge the passed options with the default ones:

function Plugin(element, options) {
    // Store references to the selected element
    this.el = element;
    this.$el = $(element);

    // Merge passes options with defaults
    this.options = $.extend({}, $.fn[pluginName].defaults, options);

    // ...other code here...

    // Initialize the plugin instance
    this.init();
}

Prototype your plugin

Once the Plugin function is defined we can modify its prototype adding all the desired methods we want for our plugin.

There are a couple of methods are a good practice to implement:

  • A init method, which initializes each plugins instance: creating new DOM elements, registering listeners, etc
  • A destroy method, responsible to free any resource used by the plugin: extra elements, unregister listeners, etc.

Other methods can be created within your plugin's prototype but remember the convention: Use method names starting with underscore for those methods we want to be private.

If you remember the first part of this series, what really happens is when you call a plugin's method, the wrapper function of our plugin checks if the method's name starts with underscore and if so then avoids the call.

//
// Plugin prototype
//
Plugin.prototype = {

    //
    // Initialize the plugin instance
    //
    init: function() {
        ...
    },

    //
    // Free resources
    //
    destroy: function() {
        ...
    },

    //
    // Public method
    //
    publicMethod: function() {
        ...
    },

    //
    // Private method (it starts with an underscore)
    //
    _privateMethod: function() {
        ...
    }

}

A note on the destroy method

As we have commented, the destroy method must free any resource used by the plugin instance, like extra created elements, unregister listeners, etc

If you remember the first article, you will notice that the plugin's instance is stored within the selected DOM element where the plugin is applied:

$.fn[pluginName] = function(options) {
    var args = arguments;

    if (options === undefined || typeof options === 'object') {
        // Creates a new plugin instance, for each selected element, and
        // stores a reference withint the element's data
        return this.each(function() {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
            }
        });
    }

    ...
};

That occurs in the line:

$.data(this, 'plugin_' + pluginName, new Plugin(this, options));

So, the last action in your destroy method must be always remove the plugin's instance reference from the element's data. This can easily done using the reference to the DOM element stored in the plugin instance:

//
// Free resources
//
destroy: function() {

    // Remove elements, unregister listerners, etc

    // Remove data
    this.$el.removeData();
}

Allow the use of callbacks in our plugin

It is common jQuery plugins allows to register callback functions to be called when an event or action is generated by the plugins. For example, in the tagger plugin the user can be notified when a new tag is added, removed, clicked, etc.

Next lines shows the initialization of the tagger plugin setting the parameter fieldSeparator to a value different from the default options value and registering a callback function for the onTagAdded event:

$('#inputID').tagger({
  fieldSeparator: '|'
  onTagsAdded: function(tags) {
    console.log('Added new tag: '+tags+'\n');
  }
});

To achieve this we need to make to main steps:

  1. Define a default and empty callback function in the plugins default options.
  2. At some place of our plugin's code make a call to the callback function.

Continuing with the sample of the tagger plugin, its default options looks like:

//
// Default options
//
$.fn[pluginName].defaults = {
    fieldSeparator: ",",
    readOnly: false,
    // Callback invoked when user calls the 'tags' method
    onTagsAdded: function() {
    },
    // Callback invoked when user calls the 'remove' method
    onTagsRemoved: function() {
    },
    // Callback invoked when user calls the 'clear' method.
    // Note: Internally the 'clear' method uses the 'remove'.
    onClear: function() {
    },
    // Callback invoked when the user click a tag label
    onClick: function() {
    }
};

Later, in the method responsible to add new tags to the tag list, a call is made to the onTagsAdded function:

// Adds one or more tags
// ...
//
tags: function(tags) {
      ...
      // Call the callback
      this.options.onTagsAdded.call(this, tags);
      ...
    }
},

Note how we have forced to set the this object and passed the value of the new added tag to the callback function.

Summary

Ok, this is the end. A short series of two articles to introduce the main concepts to creating jQuery plugins isn't a bad thing when you are looking for help starting with jQuery and custom plugin development.

Let's try to summarize the main points we have seen in this couple of posts:

  • Understand the importance of entry point to your plugin. This is handled in a new function on the $.fn object and is responsible to (or can) control: plugin initialization, call to setter or getter methods, simulate private methods, etc.
  • Encapsulate your plugin's functionalities in a prototyped function
  • Store, if needed, a reference to the DOM element where your plugin is applied to.
  • Remember to implement a destroy method responsible to free all the resources used by your plugin
  • Create a default options object that serves as a base to extend it with the options specified by the user
  • Keep calm and remember try and error is a (necessary) way to learn

References

The web is plenty of great information:

http://docs.jquery.com/Plugins/Authoring

http://www.websanova.com/tutorials/jquery/the-ultimate-guide-to-writing-jquery-plugins

http://jqueryboilerplate.com/

https://github.com/zenorocha/jquery-plugin-patterns

http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#jquerypluginpatterns

 

»
Author's profile picture acanimal

AnimatedCluster pan related bug... fixed !!!

If you regularly follow this blog and are web mapping developer that works with OpenLayers, (too much coincidences???) probably you know about the the Animated marker cluster strategy for OpenLayers I created some time ago.

»
Author's profile picture acanimal

Things I learnt creating a jQuery Plugin (Part I)

jQuery is one of the most used JavaScript libraries, if not the most used one, which allows to make great things with the big set of little tools it offers to the web developers: HTML/DOM manipulation, CSS manipulation, HTML event methods, effects and animations, AJAX, utilities, ...

One of the key aspects of jQuery is the possibility to extend it with new functionalities, so called plugins. For those who has a basic knowledge of jQuery and want or need to create a new jQuery plugin this post tries to be a helping summary of good things to take into account.

»
Author's profile picture acanimal

OpenLayers, create a checkboard layer to know the tile names using Google Charts API

Pyramid tiles are used by many providers as a more efficient way (than WMS server) to provide images. The idea is simple, we have zoom levels and on every level we have NxN tiles of a specific size (typically 256x256 pixels). Google, Yahoo, Bing or OpenStreetMaps are samples of tile providers.

pyramid

Here, we are going to create a new OpenLayers layer that will show a checkboard with the name of the tile, all this with the help of the Google Charts API.

We need to take into account every provider uses a different pyramid tile notation, that means the same tile can be named [level=1,x=0,y=0] by one provider and named [level=1,x=0,y=1] by another.

Next code is based on OpenLayers.TMS layer, which follow the OSGeo TMS specification.

I have divided the code in two TMS subclasses. The first one is responsible to draw the checkboard and the second one to draw the tile name on top every tile. The checkboard layer makes use of Google Chart API to generate black tiles.

OpenLayers.Layer.Checkboard = OpenLayers.Class(OpenLayers.Layer.TMS, {

	getURL: function (bounds) {
		var res = this.map.getResolution();
		var z = this.map.getZoom();
		var limit = Math.pow(2, z);
		var x = Math.round((bounds.left - this.maxExtent.left) / (res *this.tileSize.w));
		var y = Math.round((this.maxExtent.top - bounds.top) / (res *this.tileSize.h));

		if (y < 0 || y >= limit) {
		return "";
		} else {
			x = ((x % limit) + limit) % limit;
			var tilename = "";
			if( (x+y)%2==0 ) {
				tilename = "http://chart.apis.google.com/chart?chst=d_text_outline&;chs=256x256&chf=bg,s,ffffffff&chld=FFFFFF|12|h|000000|b||";
			} else {
				// no tile
			}
			return tilename;
		}
	},

	CLASS_NAME: "OpenLayers.Layer.Checkboard"
});

Next is the code that return the tile names:

OpenLayers.Layer.Tilenames = OpenLayers.Class(OpenLayers.Layer.TMS, {

	getURL: function (bounds) {
		var res = this.map.getResolution();
		var z = this.map.getZoom();
		var limit = Math.pow(2, z);
		var x = Math.round((bounds.left - this.maxExtent.left) / (res *this.tileSize.w));
		var y = Math.round((this.maxExtent.top - bounds.top) / (res *this.tileSize.h));

		if (y < 0 || y >= limit) {
		return "";
		} else {
			x = ((x % limit) + limit) % limit;

			var tilename = "";
			if( (x+y)%2==0 ) {
				tilename = "http://chart.apis.google.com/chart?chst=d_text_outline&;chs=256x256&chld=FFFFFF|12|h|000000|b||";
			} else {
				tilename = "http://chart.apis.google.com/chart?chst=d_text_outline&;chs=256x256&chld=000000|12|h|FFFFFF|b||";
			}
			tilename = tilename + "("+z+"/"+x+"/"+y+")";
			return tilename;
		}
	},

	CLASS_NAME: "OpenLayers.Layer.Tilenames"
});

 

»
Author's profile picture acanimal