We’ve got a number of high-priority tasks going on at work right now, so I’ve not had time to post about all the interesting tech we’re using. I have kept up on my reading, though, and I thought I’d share a few links to articles and sites I’ve found very helpful in the last while. We will soon return to our irregularly unscheduled postings
Dispelling Maven Myths Spring’s Roo Project: RAD for Standard Java Presentation on the Oracle/Sun Purchase and it’s impact on Java technologies Make-It-Easy: A tiny framework for writing Test Data Builders in Java The Tortoise and the Hare (Why there’s always time to do it right) Refactoring Large Software Systems Process-Centric vs. Information-Centric approach to SOA GitReady: Learning GIT, the easy way! A Primer on Cargo: Automated Maven Deployment A New Dawn for Java Oracle’s Strategy for Java Hudson, Best CI Tool! When “Given, When, Then” Doesn’t Fit
I owe the Vaadin framework an apology. When demoing some research I’ve been doing on Vaadin to a colleague today, he asked if Vaadin, like many Ajax-oriented frameworks, “breaks” the browser’s back button. What he meant was that when you’re working in a Vaadin app, pressing your normal “back” button in the browser takes you to whatever site you were visiting before you came to the Vaadin app, not to the last place you were inside the Vaadin app.
I told him yes - and hence the source of my apology. Strictly speaking, I was correct: if you take no extra care, then clicking the browser “back” will take you out of your Vaadin app altogether. However, this bothered me, and I went home to tinker with it a bit.
It turns out that Vaadin has full and easy support for “back”, bookmarking, and all of the other URL goodness you might expect in any other kind of web application or site, and it’s so easy.
By adding a component called a UriFragmentUtility to your first Vaadin window, you get a “hook” into the URL of your application, with the ability to both read and write the “fragment” portion of the URL, that is, anything after a # sign in the URL. For example, if your application’s URL is www.foo.com/myapp, then www.foo.com/myapp/#bar will have a “fragment” of “bar”.
I had already wired up my Vaadin to use Spring to dependency-inject it’s components, so I was able to map this fragment directly to the Spring ID’s of my components. So when my app says “www.foo.com/myapp/#bar”, I can have it automagically find the component “bar” and display it in the main area. Invalid names (if the user types a URL I don’t understand) can easily be handled with an appropriate message, or I can just send them back to the main menu.
The reverse is also true: if the user selects a new item from my menu, and the application loads the component, I can use the UriFragmentUtility to set the fragment seen in the URL box - so the user clicks a menu choice, and the URL changes to “www.foo.com/myapp/#baz”.
This means bookmarks work as well: if I bookmark “www.foo.com/myapp/#baz”, and come back tomorrow, it will work just as expected, taking me directly to the “baz” “page” of my app (I use “page” cautiously, as there is in fact no such concept as a “page” in a Vaadin app).
It’s equally easy to handle URL parameters, or to read a format of URL that doesn’t include the “#”, if you are bothered by it. So I can do things like “www.foo.com/myapp/someplace/1234″, and automatically load the component “someplace” and pass it the parameter 1234, or “www.foo.com/myapp/someplace?id=1234″ if you prefer.
All easy, all friendly to the browser back-button - which now does exactly what the user would expect - takes him/her to the last place in the Vaadin app he was.
So as far as I’m concerned, Vaadin doesn’t break the back button at all, and leverages it, bookmarking, and URLs and general very easily.
This also solves the issue of how to Search-Engine Optimize a Vaadin app - but that’s another post for a later day.
Thought I’d pass that along.
In my ongoing experiments with Apache ServiceMix, I recently installed the Felix Web Console project, and it was simple and helpful.
OSGi containers typically have a “console” for administering the bundles you’re deploying into our container via the command-line. ServiceMix has a nice “remote” feature, that allows me to get to the console of our ServiceMix instance from my local machine easily, without having to actually ssh to the ServiceMix box.
It looks like this:
You can list your bundles, install, uninstall, restart, etc, all from here.
What Felix Web Console brings to the table is a nice webapp front-end on all this functionality.
Installation is the easiest thing possible: you go to your existing console and type:
<dependency> smx@root:osgi> install http://mirror.switch.ch/mirror/apache/dist/felix/org.apache.felix.webconsole-2.0.2.jar
It reports that a new bundle is installed, and gives you the number (237 in my case).
Then I say:
start 237
And I can immediately surf to the following URL in my browser: http://servicemix.point2.com:8080/system/console
and see the following page:
Now I can browse my bundles, install, uninstall - and all the same good stuff as via the console, even view the output of the log service, except all from the comfort of my web browser.
Like many things in the OSGi world, it just works like it’s supposed to, and is much easier to do than it is to explain
In my ongoing tinkering with the Vaadin web framework, I had a need to build a country and state/province dropdown, much like you see on almost every e-commerce site out there.
Unlike the typical pair of these fields, however, I wanted mine to work correctly - that is, for the list of provinces or states to reflect the currently selected country automatically.
Simple as this sounds, it’s an exercise I’ve done many many times in too many different frameworks and technologies to count, and it’s never quite as easy it as seems like it ought to be. As you can see, many sites give up, and simply have a combined list of all states and Canadian provinces, or some such hack. I’ve never actually seen one that changes the name of the “State” field to “Province” when Canada is selected as the country, for instance.
So I set out to try this in Vaadin, and was pleasantly surprised.
Let’s assume we’re building a Form object in Vaadin. We can add our “country” drop down select box by saying this:
Select country = new Select("Country:"); country.addItem("[Unspecified]"); country.addItem("United States"); country.addItem("Canada"); country.addItem("Afganistan"); form.addField("country", country);
Of course, we’d probably want our list of countries to come from some other data source, like a property file or static list, but this gives you the idea.
Now we add our “state” drop-down:
final Select state = new Select("State:"); form.addField("state", state);
Now we must decide whether to populate the state with actual U.S. States or Canadian provinces….
country.addListener(new Property.ValueChangeListener() { public void valueChange(Property.ValueChangeEvent valueChangeEvent) { String selectedCountry = valueChangeEvent.getProperty().getValue().toString(); if (selectedCountry.equals("United States")) { state.setCaption("State:"); state.removeAllItems(); state.addItem("Alabama"); state.addItem("Texas"); state.addItem("Idaho"); } else if (selectedCountry.equals("Canada")) { state.setCaption("Province:"); state.removeAllItems(); state.addItem("Alberta"); state.addItem("Saskatchewan"); state.addItem("Manitoba"); } state.requestRepaint(); } });
So our fields before we select a country look like this:
Now we’ve got a “state” field that will change it’s title to “Province:” if the country we select is Canada, and populate itself with the appropriate list of the provinces.
But switch right back to “State” and populate the dropdown accordingly if we change our minds and select United States again…
Not too difficult, and very easy to understand and extend to other situations (or countries).
As with all Vaadin, it’s pure Java, fully testable (at the Unit level, as well as at the functional level). In fact for the “real” version of this (which reads it’s countries and such from property files), I was even able to easily TDD it, which often isn’t the case in UI technologies.
In Part 1 of our OSGi adventures, we described how to build a nice Ajax-aware Vaadin UI app, and couple it to a generic back-end OSGi service we called the service dispatcher.
Now we’ll take the adventure to the next step, show how to deploy that webapp into our OSGi container and get it up and running, then go through the functionality of the Dispatch Service, and show how it routes requires through to the first of our domain-specific application services.
In our UI, we built a form that allowed the user to enter and save a “Dealer”, with some fields like name, phone number, etc., so the first service we’ll build for the service dispatcher to talk to will be our “dealer” service.
First, though, let’s see how to get our webapp into our OSGi container.
As we’re building our Vaadin app with Maven, we can easily add the small bits of additional configuration to turn our project into an OSGi-friendly WAR file.
OSGi deploys “bundles”, but a bundle is just a jar file (or a war, which is after all just a special kind of jar) with a bit of extra meta-data. The META-INF/MANIFEST.MF file is where the magic happens. We add the following to our POM:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.0</version> <configuration> <archive> org.springframework.osgi.web.context.support,\ org.springframework.web.servlet,\ org.springframework.web.servlet.handler,\ org.springframework.web.servlet.mvc,\ org.springframework.web.servlet.view,\ dwmj.domain,\ org.springframework.web.servlet.mvc.annotation,\ org.springframework.web.context <manifestEntries> <Bundle-ManifestVersion>2</Bundle-ManifestVersion> <Bundle-SymbolicName>com.point2.Admin</Bundle-SymbolicName> <Bundle-Name>Admin</Bundle-Name> <Bundle-Version>1.0.0</Bundle-Version> <Bundle-Activator>com.point2.ServiceClient</Bundle-Activator> <Import-Package>org.osgi.framework,com.point2.services.dispatch,javax.servlet;version="2.4.0", javax.servlet.http;version="2.4.0",org.osgi.service.http;version="1.2.0", org.osgi.util.tracker;version="1.3.2"</Import-Package> <Webapp-Context>admin</Webapp-Context> <Bundle-ClassPath>WEB-INF/classes, WEB-INF/lib/service-dispatch-api-1.0.0.jar, WEB-INF/lib/vaadin-6.1.3.jar</Bundle-ClassPath> </manifestEntries> </archive> </configuration> </plugin>
This bit of magic allows Maven to build us a MANIFEST.MF like this:
Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Created-By: Apache Maven Built-By: mnash Build-Jdk: 1.6.0_15 Extension-Name: admin Implementation-Title: admin Implementation-Version: 1.0-SNAPSHOT Bundle-Activator: com.point2.ServiceClient Bundle-ClassPath: WEB-INF/classes, WEB-INF/lib/service-dispatch-api-1. 0.0.jar, WEB-INF/lib/vaadin-6.1.3.jar Bundle-ManifestVersion: 2 Bundle-Name: Admin Bundle-SymbolicName: com.point2.Admin Bundle-Version: 1.0.0 Import-Package: org.osgi.framework,com.point2.services.dispatch,javax. servlet;version="2.4.0",javax.servlet.http;version="2.4.0",org.osgi.s ervice.http;version="1.2.0",org.osgi.util.tracker;version="1.3.2" Webapp-Context: cadmin
Now we have our OSGi-friendly .war file, sitting in our target directory. We can then connect to the console of our OSGi container (in this case, ServiceMix), and say:
install war:file:/Users/mnash/experiments/admin/target/admin-1.0.0-SNAPSHOT.war
Our container honors the “Webapp-Context” tag in our manifest, so we can then surf to http://localhost:8181/admin/ to see our application. 8181 is the default port for the Jetty HTTP service in ServiceMix - it can easily be changed to another number as required, of course.
Dispatch Service Now that we can see how to get the wepapp into ServiceMix, let’s look at the Dispatch Service in detail.
Our Dispatch Service is going to be a regular OSGi bundle, so we have a separate Maven project that produces a .jar file in this case, not a WAR file.
Our MANIFEST.MF needs the following magic for this project:
Bundle-ManifestVersion: 2 Bundle-SymbolicName: com.point2.services.dispatch.DispatchService Bundle-Name: DispatchService Bundle-Version: 1.0.0 Bundle-Classpath: .,lib/commons-beanutils-1.8.0.jar,lib/commons-collections-3.2.1.jar Bundle-Activator: com.point2.services.dispatch.impl.DispatchServicePublisher Import-Package: org.osgi.framework Export-Package: com.point2.services.dispatch
You can see we’re again specifying a “Bundle-Activator” class, which, much like the ServiceClient class in our webapp, is called by the OSGi framework when the bundle containing this service is started.
One slight oddity: The dispatch service needs the two jars listed under “Bundle-Classpath:” to do it’s business - because we are building an OSGi bundle, we “embed” these jars in our bundle (which is, yes, another jar) by putting them in the src/main/resources/lib directory. We refer to them in that location in the POM, and Maven automatically includes them in the finished jar, where they’re available when our bundle needs them. The other alternative is to install the dependencies as their own bundles, but that’s a whole ‘nother post
In the case of DispatchService, we’ve got an activator like this:
public class DispatchServicePublisher implements BundleActivator { private ServiceRegistration registration; public void start(BundleContext context) throws Exception { registration = context.registerService(DispatchService.class.getName(), new DispatchServiceImpl(), null); DispatchServiceImpl.setBundleContext(context); System.out.println("Dispatch Service registered"); } public void stop(BundleContext context) throws Exception { registration.unregister(); System.out.println("Dispatch Service unregistered"); } }
Which simply takes a reference to the BundleContext on startup and passes it to the DispatchServiceImpl, which implements the DispatchService interface, like so:
public interface DispatchService { List<Map<String, Object>> call(String serviceName, String serviceOperation, Map<String, Object> parameters, String versionPattern, String securityToken) throws Exception; }
The big JuJu with OSGi is that only this interface is “exposed” from the bundle. No other service can see the innards of our service, unlike Jars on a classpath.
The implementation of the DispatchService is equally straightforward:
public class DispatchServiceImpl implements DispatchService { private static BundleContext context; public List<Map<String, Object>> call(String serviceName, String serviceOperation, Map<String, Object> parameters, String versionPattern, String securityToken) throws Exception { ServiceReference reference = getServiceNamed(serviceName); if (reference == null) throw new RuntimeException("There is no service with service-name " + serviceName); Object service = context.getService(reference); Adapter adapter = new Adapter(service); List<Map<String, Object>> response = adapter.callList(serviceName, serviceOperation, parameters); context.ungetService(reference); return response; } private ServiceReference getServiceNamed(String serviceName) throws Exception { ServiceReference[] references = context.getAllServiceReferences(null, null); System.out.println("There are " + references.length + " services available"); for (int i = 0; i < references.length; i++) { ServiceReference reference = references[i]; Object serviceNameValue = reference.getProperty("service-name"); if (serviceNameValue != null) { System.out.println("I see service with name " + serviceNameValue); if (serviceNameValue.toString().equalsIgnoreCase(serviceName)) return reference; } } throw new RuntimeException("There is no service available with service-name " + serviceName); } public static void setBundleContext(BundleContext newContext) { context = newContext; } }
The dispatch service implementation simply looks through the “published” services in the OSGi context, and looks at the “service-name” property of each service to find the one specified in the call. Assuming it finds an appropriate service, it then uses another class, Adapter, to do the type conversion of the generic Map of parameters to the specific types needed for the service being called, then uses Java reflection to actually make the call and return the response as a List of Maps, again converting the service-specific types to a generic Map in order to pass the response back to the user interface.
Why do we go through those gyrations, instead of just having access to the domain-specific beans in our UI? If we want a full decoupling, and the advantages that come with it, the type-independence of this approach gives us that. It also allows parallel development of the UI and the back-end services without an ever-increasing number of binary dependencies as well - for that matter, with the static data adapter in the Vaadin app allows us to develop on our UI entirely without the back-end services. That’s pretty decoupled.
The Dispatch Service by itself, though, doesn’t give us any functionality. It acts much like a router on a network, simply moving the request from the client to the proper service on the back-end, so let’s build such a service - in this case, a service for handling Dealers.
Dealer Service The bulk of our application-specific code will be prepared as independent OSGi services, just like this one. In later postings, I’ll describe how to set up dependencies between services (and how to use Spring DM to make doing that kind of thing far simpler).
First, let’s look at our MANIFEST.MF for our new service (again, we can use Maven to produce this for us, but the result is the same):
Bundle-ManifestVersion: 2 Bundle-SymbolicName: com.point2.services.dealer.DealerService Bundle-Name: DealerService Bundle-Version: 1.0.0 Bundle-Activator: com.point2.services.dealer.impl.DealerServicePublisher Import-Package: org.osgi.framework Export-Package: com.point2.services.dealer
The two key elements above are the Bundle-Activator, a class called DealerServicePublisher, and the Export-Package.
OSGi best practices dictate that the package that is exported should only contain the interface for the class (or classes) you wish to make available from your service. In our case, that comprises a bean class, called “Dealer”, and the interface to our actual service, DealerService.
The Dealer bean is very simple, just your basic property-holding JavaBean:
public class Dealer { private String name; private String phone; private String contactLast; private String contactFirst; private String address1; private String address2; public String getContactLast() { return contactLast; } public void setContactLast(String contactLast) { this.contactLast = contactLast; } public String getContactFirst() { return contactFirst; } .....
I’ve ommitted the rest of the getters and setters here for brevity (in case you’re wondering, yes, this is much easier to express in Scala, and yes, OSGi works just fine with Scala…)
The interface for our service is even simpler:
public interface DealerService { public void save(Dealer dealer); public Dealer findById(int id); }
Of course, a fully fleshed-out service might in fact have more methods, but again, you get the idea.
I won’t bore you with the actual implementation of the DealerServiceImpl class, but it’s important to note that it’s not in the same package as the Dealer bean and the DealerService implementation. They are the only two classes (well, one class, one interface) in that package, as the entire package is “exported” by OSGi, and therefore visible to other services and clients.
The DealerServicePublisher is the last piece to examine, and it’s pretty straightforward as well:
package com.point2.services.dealer.impl; import com.point2.services.dealer.DealerService; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import java.util.Dictionary; import java.util.Hashtable; public class DealerServicePublisher implements BundleActivator { private ServiceRegistration registration; public void start(BundleContext context) throws Exception { System.out.println("Registering dealer service"); Dictionary dictionary = new Hashtable(); dictionary.put("service-name", "dealer"); registration = context.registerService(DealerService.class.getName(), new DealerServiceImpl(), dictionary); } public void stop(BundleContext context) throws Exception { System.out.println("Unregistering dealer service"); registration.unregister(); } }
Essentially all we do in this activator is “register” our service, making it visible to the OSGi container and other services or clients that need it. We add an extra property via the “Dictionary” object, which allows us to specify arbitrary properties to be associated with our service. Because we want to look up our services from the dispatcher by name, rather than by class or interface name, we use the string “dealer” and associate it with the key “service-name”. If you examine the code for our DispatchService, you’ll see that it uses this property to find services.
Now we can build our new service with a simple “mvn package” command, and install the resulting jar into our OSGi runtime with “install file:/Users/mnash/experiments/dealer/target/dealer-1.0.0.jar” (again, you can do an install directly from the Maven repository, or from a URL, as opposed to a file).
That’s it - our “dealer” service is now available, and our “dispatch” service is fired up and ready to locate it.
If we deploy our Vaadin application in our OSGi container (as described in the previous post), you’ll find that calls to the “call” method of the ServiceClient now return the “real” data from our service.
In the next few posts we’ll examine an even easier way to define new services, and explore the power of OSGi for updating and working with our decoupled services. Then we’ll look at how to hook services together, allowing services to call other services to do their jobs as required.
In my experience, the future of modularity on the JVM is OSGi.
Many developers don’t seem to recognize the need for it, but other bloggers have covered this in great detail (see my Resources page for some links), so I’m not going to try to “sell” OSGi here at all - I assume you’re already sold, and looking at how to put OSGi to good use in your development and deployment process.
Extending my recent experiments with the Vaadin framework, I decided I wanted to have a Vaadin front-end talking to a set of OSGi services on the back end. Initially, these will be running within the same OSGi container, which in this case is FUSE 4, the commercially supported variant of Apache ServiceMix.
One of my goals was to acheive a loose coupling between the Vaadin webapp and the backing services, so that new services can readily be added, started, stopped, and updated, all without any impact on the running Vaadin app. I also wanted to maintain the convenience of being able to run and tinker with the UI portion of my app by just doing a “mvn jetty:run”, so the app needed to be able to start even if it wasn’t inside the OSGi container.
Fortunately, doing all this is pretty easy, and in the next series of articles I’ll describe how I went about it, and where the good parts and bad parts of such an approach became obvious.
In this part, we’ll start by describing the Vaadin app, and how it calls the back-end services. In later parts, I’ll describe the evolution of the back-end services themselves, as I experimented with more sophisticated techniques.
Vaadin Dependency I’m building all my apps with Apache Maven, so the first step was to create a POM file suitable for Vaadin. Fortunately, Vaadin is a single jar file, and trivial to add to the classpath. My POM needed this dependency:
<dependency> <groupId>vaadin</groupId> <artifactId>vaadin</artifactId> <version>6.1.3</version> <scope>system</scope> <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/vaadin-6.1.3.jar</systemPath> </dependency>
Here I’m using the trick of specifying a systemPath for my jar, instead of retrieving it on demand from a local Nexus repository or from the internet, but that’s just one way of doing it - the main thing is to get this one Vaadin jar on your path.
web.xml Next I proceeded to tweak my web.xml to have my top-level Vaadin application object available on a URL. The main Vaadin object is an extension of a Servlet, so this is also very easy - here’s my web.xml in it’s entirety:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Admin</display-name> <servlet> <servlet-name>Admin</servlet-name> <servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class> <init-param> <param-name>application</param-name> <param-value>Admin</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>Admin</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
In this situation my “Admin” class is in the default package, which is not generally a good practice, but you get the idea.
Menu and MenuDispatcher I then used the “Tree” class in Vaadin to build myself a nice tree-style menu, and added that to the layout on my main page. My main page has some chrome regions for a top banner and other assorted visual aids, then a left-side area where the menu lives, and a “main” area, where all the real action in the application will happen.
A class I called MenuDispatcher “listens” for events on the menu (e.g. the user clicking something), and does the appropriate action when a certain menu item is clicked.
Here’s the interesting bits from the MenuDispatcher - as you can see, it’s constructed with a reference to the “mainArea” layout when it’s first initialized.
public class MenuDispatcher implements ItemClickEvent.ItemClickListener { private VerticalLayout mainArea; public MenuDispatcher(VerticalLayout mainArea) { this.mainArea = mainArea; } public void itemClick(ItemClickEvent event) { if (event.getButton() == ItemClickEvent.BUTTON_LEFT) { String selected = event.getItemId().toString(); System.out.println("Selected " + selected + " from menu"); if (selected.equals("create dealer")) { createDealer(); } else if (selected.equals("edit dealers")) { editDealer(); } ... } System.err.println("Selected " + event.getItemId()); } } private void createDealer() { mainArea.removeAllComponents(); Component form = new CreateDealerForm(); mainArea.addComponent(form); mainArea.setComponentAlignment(form, Alignment.MIDDLE_CENTER); mainArea.requestRepaint(); } private void editDealer() { ... } ... }
Again, this code can be made more sophisticated - I’m thinking a little Spring magic could make adding new forms and such very convenient, but this gets us started.
Submitting the Form The “CreateDealerForm” object referred to in the Dispatcher then builds a Vaadin “Form” class, much like the example form built in the “Book of Vaadin”. The only interesting part of my form was that I chose not to back it with a Bean class, which is an option with Vaadin forms. If you back with a bean, then you essentially bind the form to the bean, and the form fields are generated for you from the bean.
If I wanted to then send the corresponding bean to the back-end service, then binding the bean to the form would be a good way to go. Instead, however, I don’t want my back-end services to be sharing beans with my UI application at all. I’ll explain why and how later on in more detail.
The interesting part of my form, then, is how I handle the submission of the form:
Assuming I have a button on my form, defined like so:
Button okbutton = new Button("Submit", dealerForm, "commit");
I can add a listener to this button (again, using Vaadin’s magic ability to route the Ajax events to my Java code) like thus:
okbutton.addListener(new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { Map<String, Object> parameters = new HashMap<String, Object>(); for (Object id: dealerForm.getItemPropertyIds()) { Field field = dealerForm.getField(id); parameters.put(id.toString(), field.getValue()); } System.out.println("*** Calling dealer service via dispatcher"); ServiceClient.call("dealer", "save", parameters, null, null); getWindow().showNotification("Dealer Saved"); } });
I’m using an anonymous inner class to listen to the event, and the “buttonClick” method gets called when the user says “Submit”.
The next steps are where the form meets the back-end service: First, I iterate over the form and build a map containing all the field values. The map is keyed with a string, for the name of the field or property, and the value in the map is the value the user entered. Note that these values are already typed - e.g. a checkbox can have a boolean, a TextField can have a string, a calendar field can have a java.util.Date. We retain these types, and wrap everything up in a map.
Now (after a quick println so I can see what’s going on), I call a static method on class called ServiceClient, sending along the name of the service I want to call, the operation on that service, and the parameter map I just built from my form.
The last line just shows a nice “fade away” non-modal notification to the user that the dealer he entered has been saved (assuming the call to ServiceClient didn’t throw an exception, which we’re assuming for the moment for simplicity).
So, now we have our “call” method to consider, where the map of values we built in our Vaadin front-end gets handed off to the appropriate back-end service.
Calling the Service
The only job of the ServiceClient object is to route a call from somewhere in our Vaadin app (in this case, the submission of a form) to the proper back-end service, and potentially return a response.
We identify our back-end services by a simple string, the “service name” (our first argument). The second argument to call tells us the “operation” we want from this service, as a single service can normally perform several different operations. For instance, our dealer service might have the ability to save a dealer, get a list of dealers, find a specific dealer, and so forth.
In Java parlance, a service operation might correspond to a method on the service interface, but we’re not coupling that tightly at this point - our service, after all, might not be written in Java for all we know at this point, and I prefer to keep it that way.
This is the “loose joint” in the mechanism between the UI and the back-end. To keep the joint loose, we don’t send a predefined Bean class to the back-end service to define the parameters to the service operation, we send a map, where that map contains a set of key/value pairs. The keys are always Strings, but the values can be any type - possibly even another map, for instance, which would allow us to express quite complex structures if required, in a type-independent fashion.
Let’s have a look at ServiceClient:
public class ServiceClient implements BundleActivator { private static DispatchService dispatchService = null; public void start(BundleContext context) throws Exception { ServiceReference reference = context.getServiceReference(DispatchService.class.getName()); if (reference == null) throw new RuntimeException("Cannot find the dispatch service"); dispatchService = (DispatchService) context.getService(reference); if (dispatchService == null) throw new RuntimeException("Didn't find dispatch service"); } public void stop(BundleContext context) throws Exception { System.out.println("Stopping bundle"); } public static List<Map<String, Object>> call(String serviceName, String operation, Map<String, Object> params, String versionPattern, String securityToken) throws Exception { if (dispatchService == null) { System.out.println("No OSGi dispatch service available - using dummy static data"); return StaticDataService.call(serviceName, operation, params, versionPattern, securityToken); } return dispatchService.call(serviceName, operation, params, versionPattern, securityToken); } }
Let’s go through that class piece by piece. First, you’ll notice that the class implements the BundleActivator interface - this tells the OSGi container that it is possible to call this class when the OSGi bundle containing it is started and stopped. During the start process, you can have the class receive a reference to the BundleContext. This is somewhat analagous to the Spring ApplicationContext, in that it gives our class access to the other services also deployed in OSGi. The Spring DM framework lets you do this kind of thing more declaratively, but it’s good to know how the low-level works before engaging the autopilot, I always find.
In order to allow BundleActivator to be found, we need another couple of things on our classpath, so we add this to our POM:
<dependency> <groupId>org.osgi</groupId> <artifactId>osgi_R4_core</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.osgi</groupId> <artifactId>osgi_R4_compendium</artifactId> <version>1.0</version> </dependency>
This defines the BundleActivator interface and other OSGi requirements which we use.
As you can see, we use our reference to the OSGi context to get a ServiceReference to an interface called “DispatchService”. We’ll examine dispatch service in detail in my next posting, but for now you can see we hold on to our reference as an instance variable.
When the call to the “call” method happens, our DispatchService reference is already available if we’re running inside an OSGi container, all wired up and ready to go. To give us flexibility, though, we also allow for the case where dispatch service is null, meaning we’re not running inside and OSGi container.
Instead of crashing and burning, however, we simply redirect our call to a “StaticDataService” class, which does just what you might expect. For every call it understands, it returns a static “canned” response. This allows us to build and test our UI without actually having written any of the back-end services, and to continue to run our Vaadin app with a simple “mvn jetty:run”, when all we’re working on is look and feel, or logic that only affects the UI.
This means my “cycle time” to test a change in the UI code is a matter of seconds - when I do a “mvn jetty:run” my code is compiled and up and running in my browser in about 5 seconds, and that’s on my 5 year-old macbook laptop, so there’s no penalty for not having a dynamic language in the mix here, from my point of view.
If DispatchService is not null, however, then we’re running “for real” inside an OSGi container, so we use our stored reference to the dispatch service to “forward on” our call. The dispatch service works it’s magic, which we’ll examine in a later post, and returns a List of Map objects with our response. This list might only contain one Map, of course, if the service was a simple one.
The response is then returned to the caller elsewhere in the Vaadin application, to do whatever is necessary from a UI point of view - perhaps populate a form or table with the response data.
As we’ll see in detail in my next post, the dispatch service in this case acts as a “barrier” between the UI-oriented code in our Vaadin app and our domain-specific application logic contained in our services. It is responsible for mapping our generic map of parameters into whatever domain beans are used by our back-end services, and for figuring out which of those services should be called, and which operation on that service is required. Those services then return whatever domain-specific objects they return, and the dispatcher grinds them into non-type-bound maps, or lists of maps, if there is a whole series of returns.
This means our Vaadin app only ever has to talk to one thing: the dispatcher. We only change our Vaadin code for one reason: to change the UI, never in response to a change of service code, even if the beans and classes of that service change significantly.
Next time we’ll look at the dispatch service and the first of our application-specific domain-aware services, and see how they come together.
I’ve had the chance over a recent weekend to have a first crack at a web framework called Vaadin.
I was originally browsing for news about the latest release of Google’s GWT framework when I stumbled on a reference to Vaadin, and decided to go take a look. What I found intrigued me, and I decided to take it for a test drive, as I was down sick for a couple of days with a laptop nearby…. My back became annoyed with me, but it was worth it, I think.
First Look First off, the practicalities: Vaadin is open source, and with a reasonable license, the Apache License. The essential bits of Vaadin are contained in a single JAR, and it’s both Ant and Maven friendly right out of the box.
The next thing that struck me about Vaadin was the documentation. The first unusual thing about it’s documentation was the fact of it’s existance, as open source projects are downright notorious for poor documentation. Vaadin is a pleasant exception, with tons of examples, a well-organized API doc, in the usual JavaDoc format, and even the “Book of Vaadin”, an entire PDF book (also available in hardcopy) that takes you through Vaadin in enough detail to be immediately productive.
Given that surprisingly pleasant start, I dug deeper, creating a little app of my own.
Just the Java, Ma’am The main thing that kept me interested in Vaadin once I started digging further was that it’s pure Java. Many frameworks talk about writing your UI work in Java, such as Wicket, but there’s still a corresponding template and some wiring that happens to put the code and the template together. Not so with Vaadin.
When they say “just Java”, they mean it - your entire UI layer is coded in Java, plain and simple. No templates, no tag libraries, no Javascript, no ‘nuthin. It’s reminiscent of the Echo framework, except in Vaadin’s case the Javascript library that your code automatically produces is Google’s GWT, instead of Echo’s own Core.JS library.
Unlike GWT, though, the Vaadin approach doesn’t bind you to any specific source code though, it’s just a binary jar you put on your classpath.
The only thing in my sample app, other than 2 Java files, was a web.xml and a css stylesheet, both of which were only a few lines long. And this was no “Hello, World”, either, but a rich AJAX webapp with a tree menu, fancy non-modal “fading” notifications, images, complex layouts, and a form with build-in validation. And it took maybe 4 hours of total work to produce - and that was from a standing start, as I’d never heard of Vaadin before last Thursday. Not bad, not bad at all.
I found I was able to get a very capable little webapp up and running with no need to invent my own components, even though I had trees and sliders and menus and other assorted goodies on the page. It worked in every browser I was able to try it in, which is certainly not the case for my own hand-rolled JavaScript most of the time
I haven’t yet tried creating my own custom components, but it certainly looks straightforward enough.
I did try linking to external resources, and included non-Vaadin pages in my app, with no difficulties, so it appears that Vaadin plays well with others, and can be introduced into an existing project that uses, for instance, a whack of JSP’s that one might want to obsolete.
Webapps I think Vaadin warrants more exploration, and I intend to put it further through its paces in the next few weeks. It appears extremely well-suited to web applications, as opposed to websites with a tiny bit of dynamic stuff in them.
It offers an interesting alternative to some of the patterns I’ve seen for advanced dynamic webapp development so far.
One approach I’ve seen a lot is to divide the duties of creating an app into the “back end” services and the “UI”. Generally the UI is written in either JavaScript, or uses Flex or some other semi-proprietary approach. The “back end” stuff is frequently written to expose it’s services as REST, then the two are bolted together. The pain point here happens when the two meet, as it’s common and easy to have minor (or major!) misunderstandings between the two teams. This usually results in a lot of to-and-fro to work out the differences before the app comes all the way to life.
The other approach, more common on smaller or resource-strapped teams, is to have the same group responsible for both UI and back-end services. This reduces the thrash in the joints a bit, but doesn’t eliminate it, because the two technologies on the two sides of the app aren’t the same. You can’t test JavaScript the same way you write Java, for instance, and they’re two different languages - one of which (Java) has far better tooling support than the other. IDE support, for instance, is superb for Java, and spotty at best for JavaScript.
With Vaadin, both of these approaches become unnecessary, as its the same technology all the way through (at least, what you write is - technically it’s still using JavaScript, but because that’s generated, I don’t count it).
You get to use all of the tools you know and love for the back-end services to write the code for the UI, which you can then unit and functional test to your heart’s content.
The temptation to mix concerns between UI code and back-end service code must still be resisted, of course, but at least that code isn’t buried somewhere in the middle of a JSP page, ready to leap out and bite you later.
Because you’re using dynamic layouts, the app always fits properly on the screen without any extra work, addressing a pet peeve of mine, the “skinny” webapp, restraining itself to the least common denominator of screen size, thus rendering impotent my nice wide monitors.
Scala Just because Vaadin is a Java library doesn’t restrict you to using Java to drive it, however. I made another little webapp where the whole UI was defined in Scala, calling the Vaadin APIs, and it worked like a charm. In some ways, Scala is an even better fit for Vaadin than straight Java, I suspect. I haven’t tried any other JVM compatible language, but I see no reason they wouldn’t work equally well.
Deployment and Development Cycle As I was building the app with Maven, I added a couple of lines to my POM and was able to say “mvn jetty:run” to get my Vaadin app up and running on my local box in a few seconds. My development cycle was only a few seconds between compile and interactive tests, as I was experimenting with the trial-and-error method.
TDD would be not only possible, but easy in this situation.
I successfully deployed my little Vaadin app to ServiceMix, my OSGi container of choice, without a hitch.
Performance appeared excellent overall, although I haven’t formally tested it with a load-testing tool (yet).
Summary So far, I’m impressed with Vaadin. I’m more impressed with any web framework I’ve worked with in a number of years, in fact. I’m sure there are some warts in there somewhere, but for the benefits it brings to the table, I suspect they’re easily worth it. I think the advantages to teams that already speak fluent Java is hard to overstate, and the productivity to produce good-looking and functioning webapps is quite remarkable.
I was recounting to a colleague the other day a story that is probably much funnier to fellow developers than anyone else, and thought I’d share it here as well.
I had the opportunity for a number of years to work with a software team in the Bahamas, for a company with operations there. They were a great group to work with, and we did some good stuff. The Bahamas has it’s own “dialect” of English sometimes, however, and it was a while before I got used to the slight differences and accents from my native Bermudian.
One of my favorite elements of the unique Bahamian dialect is their use of a unbound variable in natural language.
You know when you’re talking about something, and the name of a specific piece of technology escapes you? Well, those of you with younger memories maybe don’t have this mental lazy-loading happen quite as often as us old geezers, but I’m sure it happens once in a while. You’re saying something about a webapp deployed to a cluster and you want to refer to the device that distributes the processing load of the users across the machines in the cluster. “Load balancer” is the term you’re looking for, but your brain has hit a bad sector and is busy doing an fsck, so you stammer over the right term.
Bahamians have invented a term especially for this situation, and I call it the “unbound variable” in natural language. We’re not sure what it’s value should be in this situation, but it serves as a place holder when we think of the right word later on.
It’s called “tingum”, pronounced just like you’d expect, with a short “i”. Its considered bad form to pronounce it “thing-um”, I understand, even thought that might be the root of the word originally.
So you can simply say, “When the tingum moves a session from one server to another”, rather than having to actually work out the necessary technobabble to go in that spot.
It saves us the trouble of having to come up with new terms at random, like “whatsit”, or the much more verbose “thing-a-me-bob” or “whatchamacallit”.
It’s important not to bind this variable to any one term, even if it later becomes clear what that term should be in any one context, because that would reduce it’s generality. If you know that tingum should be bound to “load balancer”, you might inadvertently use it in it’s bound form in the wrong sentence.
In this sense, it’s rather like “_” (the underscore) in Scala - it’s *supposed* to be unbound.
So, the next time your mental RAM gets a checksum error and you can’t remember the correct technical term, keep the “tingum” in mind!
How can you not love a language that has a keyboard layout like this?
Seriously, though, I’ve found a certain fascination in APL ever since I first saw it back in … well, a number of years ago. A+, a new language based in part on good ‘ole APL, promises to be just as fascinating, but in a more modern and up-to-date way.
I remember having to find a special terminal (yes, a terminal) that had the funky APL keyboard caps, then picking out a program, one special character at a time. The good new was that in about 5 characters (including a couple of overtyped things that looked like squashed bugs), my program was finished - and doing real work. That’s the amazing thing about APL, and it’s modern ancestor A+ - the expressiveness is just amazing.
I’d show you some code samples, but you need a special font to read them, so you’ll just have to go have a look around on the A+ site.
Readability isn’t quite as scary as you might think at first, either, at least once you know what all those funny dead-bug symbols mean, as there’s not that many of them in a typical program. There’s also an ASCII mode, for the less adventurous.
I’ve yet to really give A+ a proper workout, but I have to say I’m looking forward to referring to my key-cap printout and taking it out for a spin!
I had a situation yesterday where I needed to have the value of an environment variable visible within my IDE, which currently happens to be IntelliJ IDEA. My operating system for this environment is OSX (on a Mac), so my first instinct was to set the variable in my .profile.
This works fine for applications I launch from a Terminal window using the shell - such as Maven or Ant.
Unfortunately, IntelliJ didn’t “see” the variable at all, as it’s launched as a regular Mac application (from my Toolbar or as an application in the Applications folder). As I was accessing the variable from within a Maven POM file within IntelliJ, it was polite enough to highlight it in red. The same POM file worked fine from the command-line, but of course that’s because the variable was being set within my .profile, so the shell could “see” it.
My second instinct was to put it in /etc/profile, in the *nix fashion, but this didn’t work either.
A bit of googling found the answer, though. I created a file called “launchd.conf” in the /etc directory. (You’ll need to use “sudo” to edit this file, e.g. “sudo vi /etc/launchd.conf”)
In this file I can add “setenv” commands to establish values for the environment variables I need. In this case, I needed to specify a variable to tell my Maven build files (which I use from inside IntelliJ) where my Weblogic installation resides, so I did:
setenv WL_HOME /Users/mnash/bea/wlserver_10.3
Then I reboot, and voila, my variable value is now available both from a command window and from within IntelliJ.
Thought I’d pass this along.
My thanks to this article for the information about launchd.conf.