Play framework

Excellent! This is how java web frameworks should had been from 2005. Play is a full stack framework and has so many features that putting them all on this post it will end up being an index list. But it’s not only the long list of features it has, it’s that everything works out of the box, there is no need to figure out how to do something. As I said the list is big, so I will only list those that I found more exciting… (I am using this framework on one of my current projects and it works very well on production environment, it’s not just another experiment).

Here they are:

  • Active Record style model, based on JPA annotations and backed by hibernate. This is probably the most missing feature form java frameworks, for some strange reason no other Java web framework (at least non that I am aware off) tackle this one and developers are stack with an anemic model – well this is probably a very controversial issue with pros and cons from both sides, anyway, this works fine for me and the fact that it removes the need for DAOs is a big win. Furthermore, just like POJOs you can transfer the model objects them from the service layer to the front-end and back again.
  • No need to compile the sources, just make a change and reload your browser.
  • Template engine, it uses Groovy as an expression language, I am not familiar with Groovy at all but I love this feature, it works just like the django templates, there is no need to know Groovy to use it.
  • Play is modular, there are already plenty of modules to use and it’s really easy to write yours. Standard distribution of Play comes with two optional modules, CRUD and Secure. I think all projects have a need for both modules. With CRUD you have a full web administration interface for all your model objects and it’s fully customizable. Secure is a simple module that helps you setup a basic authentication and authorization management, it’s also highly customizable.
  • Play also ships with an embedded application server, just type ”play run” and the world is ready for your next cool app, of course you can deploy your application on any application server. It’s really nice that the embedded application server is ready for production, it’s not just a subset to help you during development.
  • Testing the app is easier than ever.  It uses the JUnit for unit and functional testing, in your functional testing you can access directly your web controller objects. And there is a third kind of testing, Selenium for your views. But it does not stop there you can run your tests from your web page. In fact the tests are loaded only when you run Play in test mode “play test CoolApp”. Even more, with the Fixtures help class you can load your test data from a yaml file in no time. Do you want more! Continuous Integration to run your test auto-magically, just run Play with the auto-test command. I know what you think, you can do all these with any framework since they are not framework specific, but just imagine the time you need to set everything up, in Play they just work.
  • Ready for REST, it is easily scaled by running multiple instances of the same application on several servers.
  • IDE agnostic :) it comes with a command line tool that converts your project so it can be used in your favorite IDE.
  • And it’s really fast

There are a lot more cool things about this framework. It’s very different from the rest of the frameworks in a good way, just as Spring broke the rules of enterprise development years ago, Play does the same, it breaks the rules and takes an unconventional away of doing thing which is closer to the developer, with the usability and productivity in mind.

Give it a try http://www.playframework.org

Advertisements

Clean and usable URLs in Stripes

Cool URIs don’t change wrote Tim Berners-Lee more than a decade ago, URLs should be clean, usable and persistent. However, the biggest percentage of URLs around the web still are not clean and usable and even less persistent. There are lots of reasons that URLs are not persistent and most of the times it is not in the hands of the developer or webmasters, under certain circumstances some domains may not continue to be alive or they may change hands, anyway there isn’t much a framework can do about that. But for the URLs to be clean and usable is totally in the hands of the developers and webmasters. Unfortunately most web frameworks makes things even worse by not providing the mechanism to handle URLs or by making it really difficult to change the default behavior.

Stripes is not one of those frameworks and it really makes it easy to create clean URLs and provides a very flexible mechanism for handling them.

The simplest way to do it is using the @UrlBinding annotation. Let’s assume we have the following action bean:


package com.project.action;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

/**
 * @author omer haderi
 * @version 1.0
 */
public class SimpleMathActionBean implements ActionBean {
	private static final String view = "/WEB-INF/jsp/index.jsp";

	private ActionBeanContext ctx;

	private double number;

	public ActionBeanContext getContext() {
		return ctx;
	}

	public void setContext(ActionBeanContext ctx) {
		this.ctx = ctx;
	}

	@DefaultHandler
	public Resolution view() {
		return new ForwardResolution(view);
	}

	public Resolution sqrt() {
		number = Math.sqrt(getNumber());
		return new ForwardResolution(view);
	}

	public double getNumber() {
		return number;
	}

	public void setNumber(double number) {
		this.number = number;
	}
}

The URL for this action bean to calculate the square root (assuming the default behavior) will be:
http://www.domain.com/SimpleMath.action?sqrt=&number=10

To simplify this we just need to mark the bean with the following annotation:
@UrlBinding(“/public/simple_math”)
after this the URL will be:
http://www.domain.com/public/simple_math?sqrt=&number=10

Of course the point is to remove the question mark, the ampersand and the equals sign. In the previews URL the [sqrt] is an event of the action bean as you can see from the action bean class. There is a special notation to identify the event in the UrlBinding which is {$event}, so we need to modify the annotation as follows:
@UrlBinding(“/public/simple_math/{$event}”)
after this the URL will be:
http://www.domain.com/public/simple_math/sqrt=&number=10

Let’s move on and remove the rest of symbols. In our URL the [number] is a parameter and just like the events it can be embedded in the UrlBinding as follows:
@UrlBinding(“/public/simple_math/{$event}/{number}”) and it can even have a default value
@UrlBinding(“/public/simple_math/{$event}/{number=5}”)
after this the URL will be:
http://www.domain.com/public/simple_math/sqrt/10/

That’s it just one annotation and the URL is simple, more readable and makes more sense.

This is how will the action bean class look like after marking it with the annotation that we just constructed:


/**
 * @author omer haderi
 * @version 1.0
 */
@UrlBinding("/public/simple_math/{$event}/{number=5}")
public class SimpleMathActionBean implements ActionBean {
...
}

Here are the two URLs:
before: http://www.domain.com/public/simple_math?sqrt=&number=10
after   : http://www.domain.com/public/simple_math/sqrt/10/
as you can see the later is much better.

You may be wondering what’s that /public over there!?
That’s the url-mapping in the servlet-mapping of the DispatcherServlet in the web.xml which can be anything that makes sence for your project:

<servlet-mapping>
	<servlet-name>DispatcherServlet</servlet-name>
	<url-pattern>/public/*</url-pattern>
</servlet-mapping>

When using UrlBinding annotation only the URL of those action beans that are marked by the annotation will change, the rest of the actions will still have the default URL binding as explained in the “URL Binding in Stripes“.

To change the default behavior to all Action Beans we would need to create a subclass of NameBaseActionResolver and override its methods:


package com.project.extensions;
/**
 * @author omer haderi
 * @version 1.0
 */
public class CustomActionResolver extends NameBasedActionResolver {
        // this is the url-pattern from the DispatcherServlet servlet-mapping in the web.xml
	private static final String URL_PATTERN = "/public";

	@Override
	protected String getBindingSuffix() {
		return "";
	}

	@Override
	protected String getUrlBinding(String actionBeanName) {
		String result = super.getUrlBinding(actionBeanName);
		result = separeteCamelCaseWithUnderscore(result).toLowerCase();

		return URL_PATTERN + result;
	}

	private static String separeteCamelCaseWithUnderscore(String s) {
		String pattern = "(?<=[A-Z])(?=[A-Z][a-z])|(?<=[^A-Z])(?=[A-Z])|(?<=[A-Za-z])(?=[^A-Za-z])";
		return s.replaceAll(pattern, "_");
	}
}

You need to add the extension package in the filter parameters in the web.xml see “URL Binding in Stripes” for more information.

From now on all the action beans will have this as default URL binding.

URL Binding in Stripes

The best thing about Stripes is that it follows the convention over configuration practice. One of the most convenient conventions is the automatic generation and binding of URLs to the action bean class names. During development this is very helpful since you don’t need to keep in sync a configuration file as you add or delete action beans. To generate the URLs Stripes follows certain rules, of course as with everything else in Stripes you can change the default rules if they don’t meet your needs.

First lets see the default rules and then I’ll discus  how to change them if needed.

Stripes will automatically load all your action beans at start up, but we need to tell Stripes where to start looking for action beans, we need to declare at least one root package. We can do this by specifying the ActionResolver.Packages init-param in the declaration of the StripesFilter in web.xml which is the only mandatory configuration parameter. If you keep your action beans in different packages you can add all of them separated by comma as shown in the following spinet.

<filter>
  <filter-name>StripesFilter</filter-name>
  <filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
  <init-param>
    <param-name>ActionResolver.Packages</param-name>
    <param-value>com.pk1.action,com.pk2.action</param-value>
  </init-param>
</filter>

Now that Stripes knows how to load the action beans lets see how the URLs are generated and bound to the action bean class names. Lets suppose we have the following action bean:


package com.action.test;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;

public class HelloActionBean implements ActionBean {
	private ActionBeanContext context;

    public ActionBeanContext getContext() {
        return context;
    }
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @DefaultHandler
    public Resolution view () {
	return new ForwardResolution("/WEB-INF/jsp/home.jsp");
    }
}

Our action bean class name is HelloActionBean and it’s located under the package com.action.test; to refere to this action in a jps we can use the following name /test/Hello.action.

As mentioned previously to generate the URLs Stripes follows certain rules.
1. It will remove the package name up to and including the the following names if present in the package [action, stripes, web, www]. That’s why we refer to the /test/Hello.action without the full package name since the package name of this bean includes the token action and is removed up to that token.
2. It will remove from the class name the following suffixes [ActionBean, Action or Bean]. That’s why we have the /test/Hello.action instead of /test/HelloActionBean.action.
3. It will convert package name and class names to paths and change all periods to forward slashes. Instead of [test.Hello.action] we have /test/Hello.action
4. It will append the .action to the end of the striped bean name.

Fast forward:
rule 1: from com.action.test.HelloActionBean we get test.HelloActionBean
rule 2: from test.HelloActionBean we get test.Hello
rule 3: from test.Hello we get /test/Hello
rule 4: from /test/Hello we get /test/Hello.action

Lets see some examples of how this works:
com.pk1.action.HelloActionBean –> /Hello.action
com.pk1.web.HelloAction –> /Hello.action
com.pk1.www.HelloBean –> /Hello.action
com.pk1.stripes.HelloActionBean –> Hello.action
com.pk2.module.HelloActionBean –> /com/pk2/module/Hello.action

Some controversial examples:
com.pk1.web.MyActionBeanX  –> /MyActionBeanX.action (the ActionBean is not removed since it is not at the end)
com.pk1.www.ActionBean –> /.action (the ActionBean is removed based on the rule number 2)
http://www.web.action.stripes.HelloBean –> /Hello.action (all package tokens are removed since they are in the list of rule number 1)

Now that we know the rules for generating the URLs, lets see how we can change them to meet our needs. This process is quite easy.
The class that implements the rules for URL binding is the NameBasedActionResolver. To change the rules for URL binding you just need to extend this class and override the getBasePackages() and/or getBindingSuffix(), (if you change the suffix do not forget to change url-pattern of the servlet mapping in the web.xml). You can change completely the behavior of URL binding by overriding the getUrlBinding(String). Your custom class for the URL bind rules should be registered as a Stripes extension.

Here is an example of how to change the suffix from [action] to [go]. As I said this is quite easy, it requires two steps:

1. Change the servlet mapping in web.xml


<servlet-mapping>
	<servlet-name>DispatcherServlet</servlet-name>
	<url-pattern>*.go</url-pattern>
</servlet-mapping>

2. Extend the NameBasedActionResolver and override the getBindingSuffix()


package com.ext;

import net.sourceforge.stripes.controller.NameBasedActionResolver;

public class CustomActionResolver extends NameBasedActionResolver {
	@Override
	protected String getBindingSuffix() {
		return ".go";
	}
}

Note that this is an extension and extensions are loaded automatically by Stripes but as with action beans we need to tell Stripes where to look for. To configure extensions we need to add another init-param to the StripesFilter as we did for the action beans. The parameter name for the extensions is [Extension.Packages].
Here is an example:


<init-param>
	<param-name>Extension.Packages</param-name>
	<param-value>com.ext</param-value>
</init-param>

Extending the NameBasedActionResolver we can tweak the URLs in any way we want and as you can see it is quite easy, an interesting tweak would be to implement clean URLs but that will be another post.

The Stripes framework

Choosing a java web framework is somehow a complex process, not because they are difficult to evaluate but because there are so many of them (in fact it seems that there are more java frameworks than java developers :) but having many frameworks is a good thing. It means that there is a lot of competition and the competition seems to be healthy since most of the frameworks are open source, so competition is based on quality and features instead of marketing and lobbing.

Different people have different criteria on selecting a framework and probably different needs, so I will list my criteria an the reasoning behind them for choosing Stripes.
(Disclaimer: this expresses only my views on what I expect from a framework, I don’t think there are good or bad frameworks, from my point of view there are only convenient frameworks – just trying to avoid flame war here, although flame wars entertains me a lot!).

I would like to start with what I consider the most annoying thing when working with a Java framework which is not other than XML configuration files. Having worked with JSF and Struts where you need to configure all your managed-beans/action-beans and pretty much everything else into an xml configuration file, which during development becomes a mess to keep it in sync, I enjoy that Stripes removes all this configuration hassle with autoloading feature. The only xml configuration file that you need is the web.xml but that is required by the Servlet specification. Configuration by exception (a.k.a convention over configuration) is the way to go, developers should focus on business solutions and not in framework configuration details that will just disturb the flow of thinking. Hopefully other framework will follow – or maybe some already does.

Testing is the most important part of development and therefore frameworks should come with a build-in support for testing to make this process easy. So Stripes comes with a set of mock objects that help developers to easily write unit tests.

Easy extension and customization. Stripes is designed in modular form it is quite easy to add a customization plugin to change the behavior of any part of the framework, because of this modular design the extensibility of Stripes is trivial. Actually This is one of the areas that the framework really make the difference.

I don’t think that there’s a need to explain why internationalization of web application is important, all frameworks need to have a built-in support for i18n. Stripes tags comes with a default bundle lookup strategy so that i18n is just a mutter of adding key/value pairs in the resource bundle.

Never trust the user input, therefore a strong and flexible validation mechanism is needed. Stripes provides a powerful validation mechanism which is based on annotations (remember there is no XML configuration).

When working with request parameters the most annoying process is converting Strings to objects and vise versa, the Stripes support for this process is just amazing. But it is not just conversion there is also support for formating an object to string and that’s as easy as the conversion process.

Stripes comes with a built in support for layouts, with three tags you can achieve pretty much everything. If the built in support for templating is not enough you can use freemarker.

Since we are talking about web framework and web applications it would be a pity to not take advantage of Ajax. Any Ajax framework can be used due to Stripes simple and transparent request/response nature.

These are some of the features that I like to see in a framework and surely you can find this features in most frameworks and probably more but the difference is that with Stripes is easy and development is fun again as the book of Frederic Daoud suggests and proves it.

If you want to learn Stripes I suggest the “Stripes … and Java web development is fun again” from The Pragmatic Programmers, in fact this is the only book about Stripes but even if there were more books I am totally sure that I would suggest this book again, it is very well written and it covers everything about Stripes.

The following is a quick list of Stripes features, which I will try to explain and give an example in future post for each one of them and link them back to this page:

URL Binding
Built in Validation
Custom Validation
Type Conversion
Formatting
Layouts
Using Freemarker
Localization
Exception Handling
Interceptors
URL Customization
Ajax Integration
Framework Extension
Framework Customization
Testing
Dependency Injection (Giuce/Spring)
JPA Integration
Security and Encryption
Cache-ing

The examples will be deployed on google app engine.

P.S: Now that the jsr 330 is approved maybe the next version of Stripes will come with build in Dependency Injection.

If you would like to start playing with Stripes and google app engine have a look at the following links:
https://110j.wordpress.com/2009/09/19/getting-started-with-stripes-google-app-engine/
https://110j.wordpress.com/2009/09/20/redoing-guestbook-example-with-stripes/

Stripes resources:
Stripes Home Page
Stripes … and Java development is fun again

tail the log file inside eclipse

Most common tool to follow the logs of the application is tail at least under unix, linux and probably mac osx operating systems. So we just need to open a console and type tail -f path/app.log. Fairly simple but it would be nice to have it inside eclipse, which turns out to be also very simple to configure it with the external tools of eclipse.

Open External Tools Configurations:

External tool configuration

External tool configuration

Hit Run and that’s it. Windows users should install a tail for windows first!

Enjoy!

Organize django applications in packages and modules

When you create a django application you have one module to add your model classes the models.py and one module to add your views the views.py (also called actions in other web frameworks), and there are possibly other modules like forms.py and admin.py. This is perfectly fine when you have a small application with a couple of classes in your models.py and few functions  in your views.py. However, this files start to become unmanageable when adding more and more code. For example, in one of my projects the views.py is more than 600 lines and the models.py contains more than 20 classes. For that reason I decided to split the models.py and put each class in its won module, and also organize the views.py in more modules depending on related functionality.

To split the views.py in more modules it’s a no brain task, it is simply a python module and there is nothing that can prevent you from doing so. However, the models.py needs more attention and few more steps to accomplish the task since this module is used by the manage.py module.

Lets take an example and organize the code so it is more manageable.
Here’s how my application looks like at first, there is only one module for all model classes and one module for all views (actions):

This is how the models.py looks like
Note that the code example is from the book “Learning Website Development with Django”:

from django.db import models
from django.contrib.auth.models import User

class Link(models.Model):
    url = models.URLField(unique = True)

    def __str__(self):
        return self.url

class Bookmark(models.Model):
    title = models.CharField(max_length = 200)
    user = models.ForeignKey(User)
    link = models.ForeignKey(Link)

    def __str(self):
        return "%s, %s" % (self.user.username, self.link.url)

class Tag(models.Model):
    name = models.CharField(max_length = 64, unique = True)
    bookmarks = models.ManyToManyField(Bookmark)

    def __str__(self):
        return self.name

class SharedBookmark(models.Model):
    bookmark    = models.ForeignKey(Bookmark, unique = True)
    date        = models.DateTimeField(auto_now_add = True)
    votes       = models.IntegerField(default = 1)
    users_voted = models.ManyToManyField(User)

    def __str__(self):
        return '%s, %s' % self.bookmark, self.votes

This is only a small part of the views.py module, in the real example there are more than 200 lines of code:

from django.core.exceptions import ObjectDoesNotExist
from django.template import Context
from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from bookmarks.forms import *
from bookmarks.models import * 

def main_page(request):
    shared_bookmarks = SharedBookmark.objects.order_by('-date')[:10]
    variables = RequestContext(request,
                {'shared_bookmarks': shared_bookmarks})
    return render_to_response('main_page.html', variables)

@login_required()
def user_page(request, username):
    user = get_object_or_404(User, username=username)
    bookmarks = user.bookmark_set.order_by('-id')
    variables = RequestContext(request,
                {'bookmarks': bookmarks,
                 'username': username,
                 'show_tags': True,
                 'show_edit': username == request.user.username, })
    return render_to_response('user_page.html', variables)

def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')

def register_page(request):
    form = RegistrationForm(request.GET)
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
    if form.is_valid():
        user = User.objects.create_user(username=form.cleaned_data['username'],
                                        password=form.cleaned_data['password1'],
                                        email=form.cleaned_data['email'])
        return HttpResponseRedirect('/register/success/')
    else:
        form = RegistrationForm()
        variables = RequestContext(request, {'form': form})
    return render_to_response('registration/register.html', variables)

So I will take a more Java approach and create two packages one for the model and one for the views:

As I said, there is no problem whatsoever to organize the views.py into more modules, the authentication.py module is an example of the separated functionality:

from django.template import RequestContext
from django.template.loader import get_template
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404

@login_required()
def user_page(request, username):
    user = get_object_or_404(User, username=username)
    bookmarks = user.bookmark_set.order_by('-id')
    variables = RequestContext(request,
                {'bookmarks': bookmarks,
                 'username': username,
                 'show_tags': True,
                 'show_edit': username == request.user.username,})
    return render_to_response('user_page.html', variables)

def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')

Separating model classes and placing them into their won module follows, for brevity only the Bookmark class will be shown but all the other classes are separated in similar way. The difference now is that we have added a class inside Bookmark class called Meta with the field called app_label where we define the name of the application, if you do not add this field then the separation will not work, there is a workaround which requires to modify the the manage.py. Note that the Meta class can be used for a lot more things, like the ordering of objects for example. Here is the bookmark module:

from django.db import models
from django.contrib.auth.models import User

from media.bookmarks import *

class Bookmark(models.Model):
    title = models.CharField(max_length = 200)
    user = models.ForeignKey(User)
    link = models.ForeignKey(Link)

    def __str(self):
        return "%s, %s" % (self.user.username, self.link.url)

    class Meta:
        app_label = 'bookmarks'

Another thing that should be done is to add the following import lines in the __init__.py, this way the manage.py can find your classes and you can import your model classes as you did previously:

from bookmarks import Bookmark
from link import Link
from sharedbookmark import SharedBookmark
from tag import Tag

The same for the views, I use the * here since I want to import every function from the modules but you can define the function names there:

from authentication import *
from registration import *
from search import *

Of course the admin.py and the forms.py modules can be organized in the same way.

The concept of django applications is to be small and focused on certain and related functionality so that they can be plugged in different projects without tweaking and maybe that is the reason that the code is organized in a simple modules instead of packages.  But I think this way the application looks cleaner and more manageable even for the small ones, or maybe I have been exposed to Java for a long time and it looks more like a Java application…

Enjoy!

Poor obfuscation implementation

POI – “Poor Obfuscation Implementation”, at least this was the initial meaning of the acronym. The POI project of Apache contains pure Java ports for the Microsoft File formats based on OLE 2 Compound Document Format.

There are several sub-projects under POI.

  • POIFS is the implementation of the OLE 2 Compound Document format, this is the basic API for all the other POI projects.
  • HSSF-XSSF is the implementation of the Excel ’97 file format and the XSSF is the implementation of the Excel 2007 OOXML (.xlsx) file format.
  • HPSF is the implementation for reading the so called property set streams, essentially this is the Document Summary that one can find in the properties of Microsoft Office files.
  • HWPF is the implementation the Microsoft Word 97(-2007) file format. This is my favorite one, with this API you can read and write MS word documents. Unfortunately this project is headless for the moment. Note that HWPF do not support docx file format (MS Word 2007).
  • HSLF is the implementation for MS PowerPoint files, provides a way to read, create or modify PowerPoint presentations.
  • HSMF is the implementation of the Outlook MSG format.
  • HDGF is the implementation of the Visio file format, provides the ability to read (only) the low level contents of visio files.
  • HPBF is the implementation for MS Publisher files. It is in an early stage and provides the ability to read parts of publisher files, writing is not supported yet.
  • The POI library can also be compiled as a Ruby extension.

The acronyms of this project are really funny:
POIFS – Poor Obfuscation Implementation File System
HSSF – Horrible SpreadSheet Format
HWPF – Horrible Word Processor Format
and so on…

As I said before the HWPF is my favorite, with the API that this project provides we can manipulate the content of MS Word documents. Either we like it or not, a huge amount of data has been written and saved in MS Word format. I am sure that there are a lot of use cases where you would want to have access to this data through java API. Using this java ports we can avoid hacks and provide elegant solutions.

Two of my favorite use cases are:
1. Translating a word document automatically using google translator (the translation is horrible, but is much better than nothing)
2. Paragraph alignment in bilingual text.

Lets see the first use case in e very simple implementation, the steps of the algorithm are:
a. extract the paragraphs from the word document.
b. translate the paragraphs using google translator. (or any proprietary translator that you may have)
c. insert the translated text in a new word document.

Here is the code for the first use case:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import org.apache.poi.hwpf.extractor.WordExtractor;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;

public class Translator {
	private WordExtractor extractor;
	private String destFileName;

	public Translator(String sourceFileName, String destFileName) throws IOException {
		this.destFileName = destFileName;
		extractor = new WordExtractor(new FileInputStream(sourceFileName));
	}

	/**
	 * #a. extract the paragraphs from the word document.
	 */
	public String[] extractParagraphs() {
		return extractor.getParagraphText();
	}

	/**
	 * #b. translate the paragraphs using google translator.
	 */
	public String translate(String[] paragraphs, String sourceLanguage, String destLanguage)
			throws Exception {
		StringBuilder container = new StringBuilder();
		for (String text : paragraphs) {
			System.out.println(text);
			container.append(text);
		}
		String result = Translate.translate(container.toString(), sourceLanguage, destLanguage);
		System.out.println(result);
		return result;
	}

	/**
	 * #c. insert the translated text in a new word document.
	 */
	public void insertText(String text) throws IOException {
		FileOutputStream fs = new FileOutputStream(destFileName);
		OutputStreamWriter out = new OutputStreamWriter(fs);
		out.write(text);
		out.close();
	}

	public static void main(String[] args) throws Exception {
		if (args == null || args.length < 2) {
			System.out.println("Usage: Translator  ");
			System.exit(0);
		}
		Translator tr = new Translator(args[0], args[1]);
		// a.
		String[] paragraphs = tr.extractParagraphs();
		// b.
		String translatedText = tr.translate(paragraphs,
								Language.ENGLISH,
								Language.FRENCH);
		// c.
		tr.insertText(translatedText);

		System.out.println("\nDone!");
	}
}

The second use case is a bit more complicated but equally easy, for legal reasons I can not post the code… sorry, maybe it is a good exercise ;) for you.

You can find a lot more information about the POI project @ http://poi.apache.org/
end for the google java translation api @ http://code.google.com/p/google-api-translate-java/

To run the code just type: java Translate c:\mydoc_en.doc c:\mydoc_fr.doc

Note that in order to run the code, the following packages will be needed which you can find at the previews listed sites:
poi-3.1.jar
poi-scratchpad-3.1-FINAL-20080629.jar
google-api-translate-java-0.5.jar

The Scene Graph project

Project Scene Graph is an Open Source java implementation of a scene graph functionality (doesn’t make much sense, does it). So the question is what’s a scene graph? Well a scene graph is hierarchical representation of graphical objects, known as nodes, in a scene, in other words, it is a way of ordering the nodes into a hierarchy where parent nodes affect child nodes, think of this hierarchy of nodes as an n-tree where you can have as many nodes as you want.

The main goal of Scene Graph project is to support the JavaFX Script, however, you don’t need to wright JavaFX in order to take advantage of the Scene Graph since it is an API and can be included in projects just as any other API. In fact the Scene Graph API can be combined with Swing perfectly since it is written by the Java2D team. Needless to say that it is not limited to work with Swing or java applications, other languages and frameworks can take advantage of this cool API.

What can you do with Scene Graph API? Well, you can add a lot of cool features to your applications that without this API would had been very difficult if not impossible. The Scene Graph API allows creation and specification of several types of content:

  • Nodes: 2D graphics, Swing components, text, and images (for now)
  • State: transforms (positioning and orientation of nodes), visual effects, and other visual state of the content
  • Animation: varying properties of the scene graph objects over time
  • Effects: simple objects that change the appearance of scene graph nodes (e.g. blurs, shadows, color adjustment)

If you want to learn more about the Scene Graph visit:
scenegraph.dev.java.net the home page of the project
scenegraph-demos.dev.java.net demos
Overview
Scene Graph Basics

Here are some pictures of their demos!
Vodpod videos no longer available.