The dojox.grid widgets family and the strange case of the items modification

So, you are building a web application and decided to use the great Dojo framework.  Probably, if you need to use grids, you will decide to use some of the available widgets subclass of dojox.grid.

Well, my friend, be aware with the data you use to fill the grid's store !!!

Author's profile picture acanimal

What Doesn't Stay in Vegas?

Today, and thanks to a colleague, I found this great video about how the Las Vegas city has grown in the past years.

When Landsat 5 launched on March 1, 1972, Las Vegas was a smaller city. This image series, done in honor of the satellite's 28th birthday, shows the desert city's massive growth spurt since 1972. The outward expansion of the city is shown in a false-color time lapse of data from all the Landsat satellites.

Author's profile picture acanimal

Scale-adaptative Projection

Take a look to this awesome exercise from the Oregon State University:

Author's profile picture acanimal

Dojo + OpenLayers = New Challenges

Recently, the new Dojo 1.7 was released with many improvements and important changes.

As a developer, I'm pleased to work with Dojo on RIA application because simple reasons:

  • It offers almost all I need: module organization, an extensive set of widgets to create interfaces, manipulation of DOM elements, AJAX communications, etc.
  • It is relatively easy to use and learn. Here I found the declarative way to work really useful because helps developers and designers work together but on different things.
  • Creating custom widgets, after some relatively easy learning curve, brings you more power and flexibility.

Yes, Dojo is a great project, but as I mentioned at the beginning I like it for RIA projects, that is, for big or complex CRUD applications. For small things, like nice web pages, I prefer jQuery plus some plugins.

Looking at the new features of Dojo 1.7 I found a new module dojox.geo.openlayers which acts as a wrapper around OpenLayers GIS library and extends with some Dojo capabilities.

Now, add Dojo GFX shapes or Dojo widgets on top OpenLayers is possible, opining new possibilities. With this merge we can do things like add pie charts to our maps to show to statistics information. It is awesome !!!

A very short introdutcion to dojox.geo.openlayers package

Before making a little demo playing with all this new things, we need a short description.

The main class in the package is dojox.geo.openlayers.Map which acts as a kind of wrapper around the OpenLayers.Map class. You can access at any time to the OpenLayers underline object with the getOLMap() method.

Next, there is the dojox.geo.openlayers.Layer class which is a wrapper around the OpenLayers.Layer class. It allows to attach to the map any Dojo element.

The dojox.geo.openlayers.GfxLayer is a subclass of the previous class specially designed to work with GFX shapes and render them on top of OpenLayers map.

The dojox.geo.openlayers.Feature class represents the features we can attach to a dojox.geo.openlayers.Layer. The subclass dojox.geo.openlayers.GeometryFeature is designed to render LineString, Points and Collections of geometries.

Because GeometryFeature works with dojox.gfx package to render the geometries you need to add it always to a dojox.geo.openlayers.GfxLayer layer.

Hands on code

We are going to create a map with three features:

  • a dojox.gfx shape feature, with an animation attached to it to change it fill color,
  • a pie chart and
  • a stacked area chart.

You can see the demo in action, (source code at GitHub) and it should looks something like:

Lets go. Start creating new HTML page and paste the next code, which correspond to the skeleton of our demo:

		<title>Dojo + OpenLayers = New Challenge</title>
            html, body {
                width: 100%;
                height: 100%;
        <script type="text/javascript" src=""></script>
        <link rel="stylesheet" href=""/>
        <link rel="stylesheet" href=""/>
        <script type="text/javascript" src=""></script>
        <script type="text/javascript">
            ], function(ready) {

                    console.log(dojo.version.major + "." + dojo.version.minor + "." + dojo.version.patch);

					// Here put the magic !!!

    <body class="claro">
        <div id="map" style="width: 100%; height: 100%;"></div>

I'm using Dojo 1.7 and the new way to work using require. As you can see I'm referencing the modules my code requires from dojo and dojox packages

Once Dojo is loaded the ready is executed showing the Dojo version in the console and executing the code shown next, which really creates the map and the features.

In the "here put the magic" section we can place the code that creates a new dojox.geo.openlayers.Map instance:

// Define some Map options.
// openLayersMapOptions: Options for the underlaying OpenLayers.Map instance
// baseLayerName: Name of the base layer for the map
// baseLayerType: Type of the base layer. See 'dojox.geo.openlayers.BaseLayerType'
// baseLayerUrl: Necessary, for example, for WMS.
// accessible: Adds a OpenLayers.Control.KeyboardDefaults control to the map
//     to move it using keyboard.
// touchHandler: Touch support for the map.
var options = {
    baseLayerName : "OSM",
    baseLayerType : dojox.geo.openlayers.BaseLayerType.OSM,
    touchHandler : true,
    accessible : true

// Create a map instance
var map = new dojox.geo.openlayers.Map('map');

Next create a GFX layer. On it we can attach geometry features or any other Dojo widget feature.

Remember you only can attach geometry features to a GFX layer.

// Create a GFX layer
var gfxLayer = new dojox.geo.openlayers.GfxLayer();

Now create a geometry feature, defined by a LineString with some points, and add it to the layer:

// Create a geometry feature
var line = new dojox.geo.openlayers.LineString([{x:0, y:45},{x:0, y:55},{x:20, y:55},{x:20, y:50},{x:0, y:45}]);
var feature = new dojox.geo.openlayers.GeometryFeature(line);
feature.setStroke({color: "#666", width: 2});

// Add to the GFX layer

We want to animate the fill color of the geometry feature so we need to create a couple of animation. The first one will change the fill color from the original color to transparent, while the second will change from transparent to the original color again.

The trick is once the first animation ends we start the second animation (using the 'onEnd' method) and the same for the second animation. This way we create an infinite animation effect.

// Add an animation to change the color of the feature
var animA = dojox.gfx.fx.animateFill({
    shape : feature,
    duration : 700,
    color : {
        start: "#999",
        end: "transparent"
    onAnimate: function() {
        // Required to update the layer while feature change it fill color
    onEnd: function() {;
var animB = dojox.gfx.fx.animateFill({
    shape : feature,
    duration : 700,
    color : {
        start: "transparent",
        end: "#999"
    onAnimate: function() {
        // Required to update the layer while feature change it fill color
    onEnd: function() {;

Now, we are going to create a pie chart widget feature. We are going to use the dojox.geo.openlayers.WidgetFeature class which required an object in the constructor defining the widget to create, the lat/lon where to place the widget and some more parameters. You can find all the available parameters in the source code documentation:

//	* _createWidget_: Function for widget creation. Must return a `dijit._Widget`.
//	* _dojoType_: The class of a widget to create;
//	* _dijitId_: The digitId of an existing widget.
//	* _widget_: An already created widget.
//	* _width_: The width of the widget.
//	* _height_: The height of the widget.
//	* _longitude_: The longitude, in decimal degrees where to place the widget.
//	* _latitude_: The latitude, in decimal degrees where to place the widget.

The pie chart widget have a 100x100 size and will we located at (lon,lat)=(5, 40). The createWidget property must point to a function responsible to create the appropriate widget:

// Add a widget feature
var chartSize1 = 100;
var co1 = [5,40];
var descr1 = {
    // location of the widget
    longitude : co1[0],
    latitude : co1[1],
    // the function which creates the widget
    createWidget : function(){
        var div = dojo.create("div", {}, dojo.body());
        var chart = new dojox.charting.widget.Chart({
            margins : {
                l : 0,
                r : 0,
                t : 0,
                b : 0
        }, div);
        var c = chart.chart;
        c.addPlot("default", {
            type : "Pie",
            radius : chartSize1 / 2,
            labelOffset : chartSize1,
            fontColor : "black"

        var ser = [2, 8, 12, 43, 56, 23, 43, 1, 33];
        c.addSeries("Series", ser);
        c.theme.plotarea.fill = undefined;  // Transparent background
        return chart;
    width : chartSize1,
    height : chartSize1
var graphFeature1 = new dojox.geo.openlayers.WidgetFeature(descr1);

Similarly, we create a second widget feature with a stacked area chart with different dimensions and location:

// Add a second plot feature
var chartSize2 = [300,200];
var co2 = [15,45];
var descr2 = {
    // location of the widget
    longitude : co2[0],
    latitude : co2[1],
    // the function which creates the widget
    createWidget : function(){
        var div = dojo.create("div", {}, dojo.body());
        var chart = new dojox.charting.widget.Chart({
            margins : {
                l : 0,
                r : 0,
                t : 0,
                b : 0
        }, div);
        var c = chart.chart;

        c.addPlot("default", {type: "StackedAreas", tension:3})
        .addAxis("x", {fixLower: "major", fixUpper: "major"})
        .addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", min: 0})
        .addSeries("Series A", [1, 2, 0.5, 1.5, 1, 2.8, 0.4])
        .addSeries("Series B", [2.6, 1.8, 2, 1, 1.4, 0.7, 2])
        .addSeries("Series C", [6.3, 1.8, 3, 0.5, 4.4, 2.7, 2])
        return chart;
    width : chartSize2[0],
    height : chartSize2[1]
var graphFeature2 = new dojox.geo.openlayers.WidgetFeature(descr2);

Once we have all the features in the layer, it is a good idea to refresh it:



I think the fusion of Dojo with OpenLayers opens new possibilities to create rich content and behavior mapping applications. We can create dojo features and make them really amazing using effects, animation and events (like this).

I usually work with OpenLayers and, because Dojo simply acts as a wrapper on some OpenLayers classes, we can access them and work directly adding data from WFS server, GML files, etc

Is it a perfect solution? As always it depends on your needs but for all of us which work in complex RIA applications that needs some GIS features the dojox.geo.openlayers package offers a new spot light :)

Author's profile picture acanimal

Presentation tools in the browser

With the arrival of HTML5+CSS3 the browsers are getting more attention because the new possibilities.

One example of the possibilities are the proliferation of frameworks, tools and libraries to create HTML presentations to run in the browser. No need to transform your presentation from PowerPoint or Keynote to any portable format, the content is plain HTML.

Author's profile picture acanimal

Filling Flexigrid with JSON/XML data

Flexigrid is one of the most useful and powerful grid plugins for jQuery. Unfortunately, as the author explains in the project page, there is no much documentation so you must learn how to use it looking at existing code.

If anytime you need to fill a Flexigrid with JSON or XML content and you are a little buggy to look at example code, here is the great summary:

Author's profile picture acanimal

Greedy and Nongreedy Matching in a Regular Expression

This questions has come to me many times so it is time to write a post that acts as a reminder.

Author's profile picture acanimal

Open alternatives to Google Maps

Lately there was a not much surprising news about Google products and services. Among other things Google has changed the Google Maps API use policy and will charge to those users that exceed some download limits.

It is well known that Google Maps is one of the most (or the most) famous mapping service used around the net and it starts the web GIS revolution some years ago but hopefully it is not the only API we can use. Bing and the discontinued Yahoo Maps, are great competitors but this post is related to open source alternatives you can find to create your web mapping applications.

Author's profile picture acanimal

Using YouTube API to embed videos dinamically on your web site

It is easy to embed a given YouTube video on a web site, simply use the wizard to get code required code, but what about to do the some automatically using JavaScript? Yes, suppose you have a preferred user you follow all his videos and would like to put his/her latest video in your web site.

Every YouTube video has a unique identifier so the challenge is how to get the id if the latest uploaded (or updated if you prefer) video.

Searching for videos

YouTube has a very rich API and you have lot of parameters available to use, but, probably most important are the ways to search. Mainly you have two options to search videos for a given user:

  • Search video feeds:
  • Search videos uploaded for specific user:

First way is more flexible than second, because you can use lot of parameters to chose and author, limit results number, order by, etc, while the second is like setting the author parameter in the first one.

IMPORTANT !!! Read careful the YouTube API documentacion, concretely the sentence:

Requests using other parameters, such as orderby, will return cached results.

That makes me (on other folks) spent lot of time trying to find way searched doesn't get really updated results.

The requests

What will be our test request? Yeah !!! We are going to check for the lastest video of the user... ironmaiden !!!

We want to get maximum one videos from ironmaiden user and ordered by date of publication. In addition, we want the response be in JSON format (not in XML) so we use the 'alt' parameter too:

The response

By default, the returning data is specified in XML format (see here) but with the help of alt=jsonc parameter it is returned in JSON notation (see here). For the previous first request the response is:

            "title":"IMTV London",
            "description":"A quick IMTV from the O2. The full IMTV UK episode will be available to fanclub members soon!",
            "tags":["iron","maiden","imtv","on","board","flight","666","Iron Maiden","United Kingdom","Metal"],

As you can see the ID of the video is at:


Embeding a video

Embeding a video by hand is easy, you simply click on "share" button, then on "embed", copy and paste the code and that's all:

But hey !!! We are bad boys, worst if it is possible, we are programmers and we live to programming, so we are going to do the same than any other mortal but programming, so program once run forever !!! (mmm... that slogan sounds me like a island name programming language).

The intention is to make the code necessary to get the latest video identifier and inject the code to embed video on page, like this:

<iframe width="420" height="315" src=""
frameborder="0" allowfullscreen></iframe>

Automatically embedding the latest video

Finally arrive to the most interesting section. As you can imagine we can do it in the AJAX way, making an asynchronous request and injecting the code but in addition I will put a more "static" way to do, thanks to the callback parameter in the request.

The AJAX way

First, create div elements to contain the video frame and a button to start the loading process:

<div id="ajax_video"></div>
<button id="ajaxbutton">AJAX way</button>

In the head section of the document Ihave added the required JavaScript code (I'm using jQuery to do it):

<script type="text/javascript">
            function(response) {
                if( && {
                    var items =;
                    if(items.length>0) {
                        var item = items[0];
                        var videoid = "";
                        console.log("Latest ID: '"+videoid+"'");
                        var video = "<iframe width='420' height='315' src='"+videoid+"' frameborder='0' allowfullscreen></iframe>";

As we mention, the request get the latest video from ironmaiden user, creates an iframe element containing it and add it to the previously created div element.

Using callback parameter

This version differs from previous one because the request is made when page is loaded. What I'm saying? Exactly this, the request is made including JavaScript code:

<script type="text/javascript" src=""></script>

The url includes the callback parameter which is responsible to call the specified function once the code is loaded.

Putting it all together, in the same way that previous case you need a div element that contains the video iframe and a JavaScript code to add the iframe from the response:

<div id="static_video"></div>
<script type="text/javascript">
    function showVideo(response) {
        if( && {
            var items =;
            if(items.length>0) {
                var item = items[0];
                var videoid = "";
                console.log("Latest ID: '"+videoid+"'");
                var video = "<iframe width='420' height='315' src='"+videoid+"' frameborder='0' allowfullscreen></iframe>";
<script type="text/javascript" src=""></script>

The browser load the elements in the order it encounters, so it is important to put the code in the right place so browser finds first the 'showVideo' function before loading the YouTube code request.


You can see a demo working here.


Author's profile picture acanimal

Sending emails with Java

I start writing this post as a simple "how to send an email" using Java, but later I found I need to briefly explain more things. So, here is this kind of all in one summary about sending emails with Java.

Outside the Java SE platform, but included in JavaEE one, the JavaMail package provides a platform to build mail and messaging applications. Lets go with an example.

Sending a simple text message

// Common variables
String host = "your_smtp_server";
String from = "from_address";
String to = "to_address";

// Set properties
Properties props = new Properties();
props.put("", host);
props.put("mail.debug", "true");

// Get session
Session session = Session.getInstance(props);

try {
    // Instantiate a message
    Message msg = new MimeMessage(session);

    // Set the FROM message
    msg.setFrom(new InternetAddress(from));

    // The recipients can be more than one so we use an array but you can
    // use 'new InternetAddress(to)' for only one address.
    InternetAddress[] address = {new InternetAddress(to)};
    msg.setRecipients(Message.RecipientType.TO, address);

    // Set the message subject and date we sent it.
    msg.setSubject("Email from JavaMail test");
    msg.setSentDate(new Date());

    // Set message content
    msg.setText("This is the text for this simple demo using JavaMail.");

    // Send the message
catch (MessagingException mex) {

Alternatively, instead using:

msg.setText("This is the text for this simple demo using JavaMail.");

you can use next to set the message content:

msg.setContent("This is the text for this simple demo using JavaMail.", "text/plain");

Checking an email address

Here is a little trick to check, using a regular expression, if an email address is well formed:

Pattern rfc2822 = Pattern.compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");
if(rfc2822.matcher(EMAIL_ADDRESS).matches()) {
    // Well formed email

Multipart messages

That's fine, but usually you don't send simple text messages. Instead you send nice HTML body messages with bold or italic text, images, and so on.

NOTE: See below at references section to see about MIME format which extends the data you can attach to an email to allow multiparts, attachments, etc.

When you write a multipart message the content is composed of different parts, for example one part is the message written as simple text and a second part with the same message written in an enhanced way using HTML. Then the client that reads the message is responsible to render the appropriate part depending on its capabilities.

// Here create two parts and set as message contect
// Create and fill first part
MimeBodyPart part1 = new MimeBodyPart();
part1.setText("This is part one of this multipart message.");

// Create and fill second part
MimeBodyPart part2 = new MimeBodyPart();
part2.setText("This is part two of this multipart message.");

// Create the Multipart.
Multipart mp = new MimeMultipart();

// Set the message's content


Sending attachments

Terrific, we know how to send a plain text email and something more incredible like a multipart message with HTML content. Next step is to send an email attaching too some files.

Create an email with attached file is similar to create a multipart message where one part can be the text of the message and another part is the attached file. The secret is in the next lines:

// Create a new part for the attached file
MimeBodyPart part3 = new MimeBodyPart();

// Put a file in the second part
FileDataSource fds = new FileDataSource("THE_FILE_NAME");
part3.setDataHandler(new DataHandler(fds));

// 'mp' is the previously created 'MimeMultipart' object

// 'msg' is the previously created 'Message' object


HTML messages

Create a message o multipart message with HTML content is really easy, simply specify the MIME type in the setContent method:

MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>Sample</h1><p>This is a sample HTML part</p>", "text/html");

Attaching images within the HTML code

If you write a rich message using HTML you can, of course, add images using the 'img' tag. If the image is referenced from an external server there is no problem, but: how to attach an image to the message and render within the HTML message body?

The idea is as follow:

  • first you need to attach the image file and set an identifier and
  • second you need to write your HTML code and reference the image identifier in the 'img' tag.
// Create and fill html part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<h1>Sample</h1><p>This is a sample HTML part with an attached image</p>" +
	"<img src='cid:some_image_id'>", "text/html");

// Create a new part for the attached image and set the CID image identifier
MimeBodyPart imagePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("THE_IMAGE_FILE_NAME");
imagePart.setDataHandler(new DataHandler(fds));
imagePart.setHeader("Content-ID", "some_image_id");


Anything more to say?

Arrived to this point you are almost a master of sending emails. You know how to send simple emails, multipart emails with richest HTML content and attach files and images on your message.

What more can a programmer desire?

Probably, a more easy to use API and that is what Apache Commons Email project offer you. See the 'user guide' section to understand what I say. It offers a more abstract API more close to humans than to protocols.


JavaMail - JavaMail project home page.

Apache Commons Email - Apache Commons subproject to simplify the way to work with JavaMail API. See the 'user guide' section

MIME (Multipurpose Internet Mail Extensions) - Description of MIME format for multipart emails.

Author's profile picture acanimal