miércoles 25 de marzo de 2009

IWebMvc2 stable release available

A quick post just to mention I've compiled and uploaded a new IWebMvc2 version. Although it includes a Beta version of dojo most things work (minor issues with image preview in IE remain). It packages two new widgets, Panel and Chart (though the later is considered preliminary and it's not enabled in the demo). The Panel widget allows a user to freely move content around the screen, collapse it or drag&drop it to enabled zones.

Apart from those this release includes loads of bug fixes and is nearly final. It's been tested under FF3+, IE 7/8, Chrome and Safari with good results (of course, report any issues you can find).

The demo application is composed of several pages this time (instead of the CRUD widget alone) so the developer can see how widget composition does work. In addition this time I've chosen a full download (instead of Ivy) to achieve a better user experience when just evaluating the framework. It should be much faster this time, with a boot time under a minute (unfortunately HSQLDB still needs to be populated on startup).

My next steps include a deep evaluation of other Java web frameworks including Grails, Ariba Web and Oracle ADF Faces. Obviously each of those have unique characteristics difficult to replicate (and, well, more workforce) but that makes for an interesting goal, doesn't it?

I hope you enjoy it!

lunes 23 de marzo de 2009

I'm no Javascript ninja..and you?

It's a sad confession to make but true nonetheless. Of course, I'm not a newbie either, I know the basics of the language, how to work with objects and functions and, of course, closures. I've even read (probably not that thoroughly) the Javascript Bible. But, for example, it was just last week that I met loop closures for the first time. A loop closure is a language construct where a function can be applied to the traversed elements:

for (i in [0, 1]) (function (i) {alert(i)}) (["a", "b"][i])

I was amazed really. For me, the former solution to that problem (a scoping issue of the loop variable but read the whole article if in doubt) was usually along these lines:

function loop(array, fn) {
   for ( i in array) fn.call(array, array[i])
}

loop(["a", "b"], function(i){ alert(i) })

Now, how much more elegant is the first snippet? It's like programming in Groovy, sometimes you are just surprised by the power offered by those one-liners. I have to admit that without the proper knowledge, the first time you face that kind of code is, well, daunting.

But, to the topic, I was reading John Resig (highly recommended) and I stumbled upon:

var obj = (function() {
   var a = 21;
   return {
      fn: function() {a;}
   };
})();

var foo;
eval('foo=a', obj.fn);

The above code was engineered to showcase a FF problem when handling evals. I wasn't designed for anything meaningful don't worry. But in the process it happens to include interesting tidbits like private variables and the call of a function just after it's been defined. The really weird part are the two last lines where it assigns the foo variable (using an eval) in the scope of the function resultant of the anonymous function invocation. Well, it required me some time to understand that. What brings me to the current situation, I'm no JS ninja you see?

JS has so many gotchas with inheritance and polymorphism that I'm not sure I will understand them all, ever. Then there are all the web issues like cross-browser, cross-domain, XSS, sandboxing et al. Even though I'm programming an OSS web framework (IWebMvc) and it's quite capable, I hope, I still have issues with topics like namespaces! Not to mention if I should offer out-of-the-box support for things like Google Caja. And that's after battling hard with other topics like cache, encapsulation, minification, gzipping, XHR, the many APIs AND the functionality itself. I don't wonder anymore why people find Javascript so fearful and find monstrosities like JSF palatable..

So, what takes to be a ninja? Well, first of all this code should not pose any problem:

Function.prototype.bind = function(){
   var fn = this,
      args = Array.prototype.slice.call(arguments),
      object = args.shift();
   return function() {
      return fn.apply(object,
         args.concat(Array.prototype.slice.call(arguments)));
   };
};

There you have an augmented native object (Function), private variables declarations, the "full" Array API and closures, of course. And, fortunately, a tutorial here. Once there, you should be aware of browser native APIs, for example, querySelectorAll or the new native JSON parsing support. You have to be in touch with the future of the web (worker threads, HTML5..). Canvas knowledge seems pretty useful as of today as well! Are you up to the task? My only advice, read the dojo or jQuery sources, there are no better tutorials out there. And then...the challenge ;-)

miércoles 18 de marzo de 2009

Glassfish v3 embedded, are we there yet?

I've been preparing a new Release Candidate of IWebMvc2 (get it here). This time I wanted to part from Jetty as, although easy to setup, the results were not that amazing (a first access of around forty five seconds required to compile a complex JSP that relies on many tag files). And I've been following closely the development of Glassfish v3 (I really hope IBM does not buy Sun) so this seemed like a perfect opportunity to test the new embedded server feature.

I started collecting some information from here and there and it seemed easy. I just needed a new repository location

<ibiblio name="glassfish" m2compatible="true"
   root="http://download.java.net/maven/glassfish" />

And a couple of lines in my ivy.xml file

<dependency org="org.glassfish.embedded" name="glassfish-embedded-api"
   rev="3.0-Prelude-Embedded-b14" conf="run->default" />
<dependency org="org.glassfish.embedded" name="glassfish-embedded-web"
   rev="3.0-Prelude-Embedded-b14" conf="run->default" />

Unfortunately GFv3Embedded does not offer any Ant tasks yet so you need a Java class. Something like:

EmbeddedInfo ei = new EmbeddedInfo();
Server server = new Server(ei);
server.start();

Tedious but hardly a showstopper. On the bright side the server instance is fully configurable and, for example, a pool/datasource can be added via code (mimicking the admin console commands)

CommandExecutor ce = server.getCommandExecutor();
options.setProperty("datasourceclassname", "myDataSourceClass");
options.setProperty("DEFAULT", "myConnPool");
ce.execute("create-jdbc-connection-pool", options);

Or a WAR deployed dynamically

options.setProperty("DEFAULT", "c:\\temp\\iwebmvc2.war");
ce.execute("deploy", options);

So far so good. The surprise came later while executing the script. Just take a look of a trimmed version of the output

[ivy:retrieve] found org.glassfish.embedded#glassfish-embedded-api;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.distributions#web;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.distributions#nucleus;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.osgi-platforms#felix;3.0-Prelude-Embedded-b14
[ivy:retrieve] found com.sun.enterprise#hk2;0.3.32-prelude-b28
[ivy:retrieve] found com.sun.enterprise#hk2-core;0.3.32-prelude-b28
[ivy:retrieve] found com.sun.enterprise#config;0.3.32-prelude-b28
[ivy:retrieve] found com.sun.enterprise#auto-depends;0.3.32-prelude-b28
[ivy:retrieve] found com.sun.enterprise#tiger-types-osgi;0.3.32-prelude-b28
[ivy:retrieve] found org.glassfish.core#api-exporter;3.0-Prelude-Embedded-b14
[ivy:retrieve] found com.sun.enterprise#osgi-adapter;0.3.32-prelude-b28
[ivy:retrieve] found woodstox#wstx-asl;3.2.3 in public
[ivy:retrieve] found org.glassfish#javax.xml.stream;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.core#glassfish;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.core#kernel;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.common#glassfish-api;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.common#internal-api;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.admin#config-api;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.common#common-util;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.external#grizzly-module;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.common#stats77;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.deployment#deployment-common;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.external#asm-all-repackaged;3.0-Prelude-Embedded-b14
[ivy:retrieve] found com.sun.pkg#pkg-client;1.0.7-15.1269
[ivy:retrieve] found org.glassfish.flashlight#flashlight-framework;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.flashlight#flashlight-agent;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.admin#monitoring-core;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.admin#admin-cli;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.admin#cli-framework;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.admin#launcher;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.branding#branding;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.distributions#nucleus-base;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.docs#basedocs;3.0-Prelude in javanet
[ivy:retrieve] found org.glassfish.deployment#deployment-admin;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.deployment#deployment-autodeploy;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.external#javadb;3.0-Prelude-Embedded-b14
[ivy:retrieve] found javadb#javadb;10.2.2.1-20070823
[ivy:retrieve] found org.glassfish.web#webtier-all;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.web#web-gui-plugin-common;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.web#web-glue;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.web#web-cli;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.common#container-common;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.common#glassfish-naming;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.transaction#transaction-internal-api;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish#javax.transaction;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish#javax.resource;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish#javax.persistence;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.connectors#connectors-internal-api;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish.deployment#dol;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish#javax.servlet;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish#javax.annotation;3.0-Prelude-Embedded-b14
[ivy:retrieve] found org.glassfish#javax.enterprise.deploy;3.0-Prelude-Embedded-b14
...and so on...

And worse....


::::::::::::::::::::::::::::::::::::::::::::::
:: FAILED DOWNLOADS ::
:: ^ see resolution messages for details ^ ::
::::::::::::::::::::::::::::::::::::::::::::::
:: org.glassfish.osgi-platforms#felix;3.0-Prelude-Embedded-b14!felix.distribution-fragment
:: com.sun.enterprise#hk2;0.3.32-prelude-b28!hk2.hk2-jar
:: org.glassfish.core#glassfish;3.0-Prelude-Embedded-b14!glassfish.hk2-jar
:: org.glassfish.core#kernel;3.0-Prelude-Embedded-b14!kernel.hk2-jar
:: org.glassfish.common#glassfish-api;3.0-Prelude-Embedded-b14!glassfish-api.hk2-jar
:: org.glassfish.common#internal-api;3.0-Prelude-Embedded-b14!internal-api.hk2-jar
:: org.glassfish.admin#config-api;3.0-Prelude-Embedded-b14!config-api.hk2-jar
:: org.glassfish.common#common-util;3.0-Prelude-Embedded-b14!common-util.hk2-jar
:: org.glassfish.common#stats77;3.0-Prelude-Embedded-b14!stats77.hk2-jar
:: org.glassfish.deployment#deployment-common;3.0-Prelude-Embedded-b14!deployment..
....and many many more....

What was that? A horror movie? In the end I was able to find a JAR file that packaged every dependency (glassfish-embedded-all-10.0-SNAPSHOT.jar) but it looked like overkill (I don't want EJB, JMS, ...). At least I've learned something: Jetty works wonders for me, it's just I hadn't realized it fully :-)

So kudos to the GFv3 team, a full blown embeddable Application Server is a nice feature to have. But there's work till it reaches (something that resembles) a mature option.

sábado 7 de marzo de 2009

Parallelism in Spring

Update: This article has been promoted to Dzone

I've been wanting to post about parallelism in Spring for ages by now. It's an interesting topic that doesn't get the attention it deserves(if any at all), probably because an IoC container and Spring in particular really shine managing dependencies, a task that intuitively promotes serial processing, and also because JEE APIs (say Servlet or EJB) hide the need of it. There's a specific area where no matter what you'll be looking for concurrency and that is data retrieval. As long as a couple of different resources are involved, or even one alone if the data requested is independent, there are efficiency gains processing the several connections in parallel. A common case in todays environments would be, for example, calling web services.

Standard Java does not really offer any API to manage concurrency once inside a request (though the request itself is managed from a pool). In fact, it's open for discussion if the standard forbids opening new threads in a web context (it's specifically banned for EJBs). WebSphere and Weblogic proposed an alternative called CommonJ aka WorkManager API. It's a very good alternative when running under those application servers. Spring offers another, arguably even more powerful, option with the TaskExecutor abstraction. It's sometimes preferable, in a Spring environment, because it can use CommonJ as the underlying API but it can also use the Java5 Executor framework (among others) as well, making the switch just a matter of changing a couple of configuration lines.

Let's review how to use the framework. Our only pre-requisite is to have at least two data retrieval services already configured as a dependency of a third bean. All the data retrieval services must share a common interface, I can recommend something like the Command pattern here (beware this approach is not fully followed bellow to better showcase inbound data processing). At this point we're going to change the individual dependencies and transform them into a collection, we'll add init and destroy methods and an executor (let's start with a JDK5 implementation):

public class ParallelService implements InitializingBean, DisposableBean {
   private List<Command<T>> commands;
   private ExecutorService executor;
}

With our current implementation based on Java 5 executors we need to start up the thread pool in the initialization method and conclude everything when Spring context is closed:

public void afterPropertiesSet() throws Exception {
   executor = Executors.newFixedThreadPool(commands.size());
}

public void destroy() throws Exception {
   executor.shutdownNow(); // Improve this as much as liked
}

We just need to handle the concurrent execution now. It's easy to do with the Future management of asynchronous tasks. Another alternative is to submit all tasks and await termination (see ExecutorService):

public void execute(Data data) {
   Set<Future<?>> tasks = new HashSet<Future<?>>(commands.size());
   for (Command command : commands)
      tasks.add(executor.submit(new RunCommand(command, data)));
   for (Future future : tasks)
      future.get();
   //Other stuff to execute after all data has been retrieved
}

The code above just creates a collection of Future objects to check when the jobs have finished. The tricky part is the creation of the concurrent job from a custom service and pass the required data (if needed). An inner class wrapper will suffice:

private static class RunCommand implements Runnable {
   private final Data data;
   private final Command command;
   public RunCommand(Command command, Data data) {
      this.data = data;
      this.command = command;
   }
   public void run() {
      command.execute(data);
   }
}

Well, that was pretty easy indeed. Right now we have a perfectly valid way to invoke beans in parallel. This approach has pros and cons. In the former list we have independence from Spring APIs (of course imagine that the Spring interfaces are substituted by their matching XML attributes) but we are also limited to a Java5 environment. If we don't mind introducing a dependency with Spring itself we can transform the source code to use the TaskExecutor framework:

public class ParallelService {
   private TaskExecutor taskExecutor;
   private List<Command<T>> commands;
   public void setTaskExecutor(TaskExecutor taskExecutor) {
      this.taskExecutor = taskExecutor;
   }
}

And now the init and destroy methods are substituted by some XML configuration:

<bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
   <property name="corePoolSize" value="5" />
   <property name="maxPoolSize" value="10" />
   <property name="queueCapacity" value="25" />
</bean>

But notice that not all implementations of the TaskExecutor interface allow tracking the progress of a task once scheduled for execution!

public void execute)( {
   for (Command command : commands)
      taskExecutor.execute(new RunCommand(command));
}