Archive

Posts Tagged ‘vaadin’
  • Adventures in SEO with Vaadin

    Vaadin logo

    TL;DR: Vaadin was hardly SEO-friendly in the past. Not anymore, with the new Volga library.

    Bookmarking pages

    Bookmarking is as old as www itself. Being able to save an URL is part of the ADN of websites. Regarding web apps, this is somewhat different. For example, in an e-commerce webapp, while it does make sense to bookmark a specific product, bookmarking a specific step of the checkout process does not.

    Following the shop example, here’s what happens in a traditional servlet-based context:

    1. A servlet is mapped on a specific subcontext such as /product/*
    2. When the URL /product/really-cool-product is called, the doGet() method of that servlet is called
    3. The method parses the URL to read the really-cool-product part - which should be an unique key for the product
    4. It delegates to a whole chain of components that loads the product from the datastore
    5. It forwards to a JSP along with the relevant product data
    6. This JSP generates the HTML

    Single-Page Applications

    Come SPAs. By definition, they serve all content under the same URL. This makes bookmarking specific pages of the application impossible because there are no pages per se. In general, SPAs handle this problem with fragment identifiers. The above URL becomes /product#really-cool-product, problem solved. In Vaadin, this directly translate to usage of the Page.getCurrent().setUriFragment() method or of the Navigator API.

    Unfortunately, this doesn’t work at all with the crawling part of SEO. Fragments are not discriminatory parts of an URL: #really-cool-product and #another-cool-product do point to the same URL so bots such as Google Bot won’t crawl both.

    The fragment identifier functions differently than the rest of the URI: namely, its processing is exclusively client-side with no participation from the web server.
    -- Wikipedia

    Distinct URLs for SPAs

    Back to square one, both /product/really-cool-product and /product/another-cool-product paths are required. This problem is not unique to Vaadin, but common to all server- and client-side SPA frameworks. What is required is:

    1. To have the client change the browser’s URL with no server interaction - no page reload nor AJAX calls
    2. To have the server handle paths

    In JavaScript, the answer is to use the History API. I assume everyone is familiar with the following snippet:

    window.back();
    window.go(-1);
    

    This is however absolutely not standard. This should be replaced by the following:

    window.history.back();
    window.history.go(-1);
    

    The history object implements the History API. In particular, it API makes it possible to add entries in the browser history via the pushState() method.

    Suppose http://mozilla.org/foo.html executes the following JavaScript: {% highlight javascript %} var stateObj = { foo: "bar" }; history.pushState(stateObj, "page 2", "bar.html"); {% endhighlight %} This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
    --Mozilla Developer Network

    On the server-side, handling different paths is quite trivial - even though some designs are better than others.

    Beyond distinct URLs

    Distinct URLs is only the emerged part of the iceberg regarding SEO.

    One wants to have dedicated meta headers for each dedicated URL, such as <title> and <meta name="description">. Even further, social medias have their own dedicated meta headers, e.g.:

    Volga, the SEO-friendly Vaadin library

    Implementing the steps above from scratch in your Vaadin project is definitely not trivial. Rejoice, for comes Volga, a ready-to-use library that handles the brunt of things for you.

    To use it, just add this snippet to your POM:

    <dependency>
        <groupId>org.vaadin</groupId>
        <artifactId>volga</artifactId>
        <version>0.1</version>
    </dependency>
    

    Important part of the API include:

    org.vaadin.volga.VolgaDetails
    Holds a set of metadata headers
    org.vaadin.volga.VolgaServlet
    Set the VolgaDetails for the root path and provides bindings between a path and other VolgaDetails objects. This way, each specific path can be set their own VolgaDetails.
    org.vaadin.volga.Volga
    Holds the previously defined mappings
    org.vaadin.volga.VolgaUI
    Handles the initial configuration
    org.vaadin.volga.SeoBootstrapListener
    Fills page metadata headers from a VolgaDetails object

    For more details, please check this example project on Github. It’s deployed online and here are results shown on Google search that proves that it works.

    Demo application as seen on Google Search

    This works for Twitter as well:

    Twitter card for main view Twitter card for second

    Categories: Java Tags: SEOvaadinvolga
  • Feedback on customizing Vaadin HTML template

    Last week, my post was about how you could customize the default Vaadin HTML template so you could add a lang attribute for example. I didn’t ask for feedback, but I got it anyway, so let’s use the occasion to analyze it.

    First, I must admit that my solution was not Vaadin-esque as I used AOP to get the job done. My friend Matti Tahvonen from the Vaadin team was kind enough to provide not only one but 2 alternatives to my proposal. Thanks Matti!

    Alternative solutions

    The first solution - also the one I got the last, was submitted by AMahdy AbdElAziz:

    {% gist nfrankel/51ae9e05a2beca2089ae %}

    Evil but it works and couldn’t be simpler!

    The second solution uses Matti’s own framework - Viritin, to achieve that. I haven’t looked at the framework yet (but it’s in my todo list) so I cannot comment it but here is the snippet:

    {% gist mstahv/4f5b55457a96a8441834 %}

    The standard Vaadin-esque server-side way is a bit more convoluted:

    {% gist mstahv/ddbfc671351cf3dfa3ac %}

    However, this one I can analyze and comment :-)

    Flow decomposition

    Note: readers who are more interested in possoble improvements can skip directly to that section.

    The first part is quite easy. It just registers a new SessionInitListener (the proposed code uses a lambda to do that):

    The second part happens when a request is made and Vaadin notices a new session must be created:

    The end of the previous sequence diagram is designed in a generic way in Vaadin. In our specific case, it’s rendered as such:

    Improvements

    I think a couple of improvements can be made.

    • The code is awfully verbose - even using Java 8's lambda
    • Two objects are created each time a session is initialized, the session listener and the bootstrap listener
    • Setting the servlet class as an internal class of the UI sends shiver down my spine. Though I understand this is a Gist, this is unfortunately what you get by using the Vaadin Maven archetype. This is very far from the Single-Responsibility Principle.

    Since my initial example uses both Spring Boot and Kotlin, here’s my version:

    {% gist nfrankel/0759c7f1c3b8f0aa6231 %}

    With Spring Boot, I can manage the SessionInitListener as a singleton-scoped Bean. By passing it as a servlet parameter, I can create only a single instance of SessionInitListener and BootstrapListener each. Of course, it’s only possible because the language value is set in stone.

    Thanks to Kotlin, I co-located the overriden servlet class within the configuration file but outside the configuration class. Since the servlet is used only by the configuration, it makes sense to put them together… but not too much.

    Finally, note that SessionInitListener is a functional interface, meaning it has a single method. This single method is the equivalent of a function taking a SessionInitEvent and return nothing. In Kotlin, the signature is (SessionInitEvent) -> Unit. Instead of creating an anonymous inner class, I preferred using the function. It’s not an improvement, but a more functional alternative. At runtime, both alternatives will allocate the same amount of memory.

    The complete source code can be found on Github in the manage-lang branch.

    Categories: JavaEE Tags: kotlinvaadin
  • Customizing Vaadin HTML template

    This week, I had an interesting question on Twitter: “How in Vaadin do you add a lang attribute to the html element?”, like this:

    ```html<html lang="fr">

    While it's quite easy to customize individual components on the page, the outer html tag is outside our control. In this article, I'll describe a possible solution to this problem. Note that I think this is too specialized for <a href="http://morevaadin.com" target="_blank">morevaadin.com</a>. However, this should still be my reference site for all things Vaadin.
    
    My first (wrong) thought, was that the `html` element is generated by the UI widget client-side. It's not the case - as there's no such widget. In order to find the answer, I had to understand how the framework works. Here's a short summary of the sequence when one makes a request to a Vaadin application.
    
    <img src="/assets/resources/customizing-vaadin-html-template/sequence.png" class="aligncenter"  height="558" width="827" />
    
    Basically, the Vaadin Servlet delegates to the Vaadin Service. In turn, the service loops over its internal list of Request Handlers until one of them is able to handle the request. By default, the Vaadin Service registers the following handlers:
    
    1. ConnectorResourceHandler
    1. UnsupportedBrowserHandler: returns a specific message if the browser is not supported by Vaadin
    1. UidlRequestHandler: handles RPC communication between client and server
    1. FileUploadHandler: handles file uploads achieved with the `FileUpload` component
    1. HeartbeatHandler: handles heartbeat requests
    1. PublishedFileHandler
    1. SessionRequestHandler: delegates in turn to request handlers that have been registered in the session
    
    This is implemented in `VaadinService.createRequestHandlers()`. However, notice that `VaadinService` is abstract. There's a subtle changed introduced in the concrete `VaadinServletService` subclass that is used. It registers a new request handler - the `ServletBootstrapHandler`, in order for Vaadin to run transparently in both a servlet and a portlet context. In this later case, only a fragment :
    
    <img src="/assets/resources/customizing-vaadin-html-template/classes.png" class="aligncenter"  height="276" width="533" />
    
    The servlet boostrap handler is responsible to generate the initial HTML page at the start of the application, including the desired outer `html` tag. Next requests to the application will just update part of the page via AJAX, but the outside HTML won't change. Thus, this is the class that needs to be updated if one wishes to add a `lang` attribute. A quick glance at the <a href="https://vaadin.com/api/com/vaadin/server/BootstrapHandler.html" target="_blank">class</a> makes it very clear that it's quite hard to extend. Besides, it delegates HTML generation to the <a href="http://jsoup.org/" target="_blank">JSoup</a> and more precisely to the `Document.createShell()` static method.
    
    At this point, you have 3 options:
    
    1. Forget about it, what is it worth anyway?
    1. Rewrite a large portion of the BootstrapHandler and add it before the BootstrapHandler in the handlers sequence
    1. Be lazy and apply Ockham's razor: just use a simple <abbr title="Aspect-Oriented Programming">AOP</abbr>'s aspect
    
    In order to be of any use, I chose the latest option. It's quite straightforward and very concise, you only need the following steps.
    
    Create the aspect itself. Note that I'm using Kotlin to be coherent with the existing project but Java or any other JVM-based language would be the same.
    
    ```java
    @Aspect
    open class UpdateLangAspect {
    
        @Pointcut("execution(static * org.jsoup.nodes.Document.createShell(..))")
        fun callDocumentCreateShell(): Unit {}
    
        @AfterReturning(pointcut = "callDocumentCreateShell()", returning = "document")
        fun setLangAttribute(document: Document): Unit {
            document.childNode(0).attr("lang", "fr")
        }
    }
    

    As the method to instrument is static, it’s not possible to use simple Spring proxies, but we need AspectJ class instrumentation via LTW. In order to activate it in Spring Boot, I just have to update the application.properties file:

    spring.aop.proxy-target-class=true
    

    Also, one has to tell Aspect’s weaver what needs to be instrumented in the META-INF/aop.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <aspectj>
      <aspects>
        <aspect name="ch.frankel.blog.bootvaadinkotlin.UpdateLangAspect" />
      </aspects>
    
      <weaver options="-XnoInline -Xlint:ignore -verbose -showWeaveInfo">
        <include within="org.jsoup.nodes.Document" />
        <include within="ch.frankel.blog.bootvaadinkotlin.UpdateLangAspect" />
      </weaver>
    </aspectj> 
    

    The first section is about the aspect, the second is about what classes need to be instrumented. Note that weaving section needs also to reference the aspect too.

    Finally, one has to update the POM so that launching the application through the Spring Boot Maven plugin will also use the aspect.

    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <configuration>
        <agent>${settings.localRepository}/org/aspectj/aspectjweaver/1.8.8/aspectjweaver-1.8.8.jar</agent>
      </configuration>
    </plugin>
    

    For sake of completeness, the code is available on Github with the manage-langv1 tag.

    At this point, generating the page will display the desired change. Job done!

    Categories: JavaEE Tags: customizationvaadin
  • Playing with Spring Boot, Vaadin and Kotlin

    It’s no mystery that I’m a fan of both Spring Boot and Vaadin. When the Spring Boot Vaadin add-on became GA, I was ecstatic. Lately, I became interested in Kotlin, a JVM-based language offered by JetBrains. Thus, I wanted to check how I could develop a small Spring Boot Vaadin demo app in Kotlin - and learn something in the process. Here are my discoveries, in no particular order.

    Spring needs non-final stuff

    It seems Spring needs @Configuration classes and @Bean methods to be non-final. As my previous Spring projects were in Java, I never became aware of that because I never use the final keyword. However, Kotlin classes and methods are final by default: hence, you have to use the open keyword in Kotlin.

    @Configuration
    open class AppConfiguration {
    
        @Bean
        @UIScope
        open fun mainScreen() = MainScreen()
    }
    

    No main class

    Spring Boot applications require a class with a public static void main(String... args) method to reference a class annotated with @SpringBootApplication. In general, those two classes are the same.

    Kotlin has no concept of such static methods, but offers pure functions and objects. I tried to be creative by having an annotated object referenced by a pure function, both in the same file.

    @SpringBootApplication
    open class BootVaadinKotlinDemoApplication
    
    fun main(vararg args: String) {
        SpringApplication.run(arrayOf(BootVaadinKotlinDemoApplication::class.java), args)
    }
    

    Different entry-point reference

    Since the main function is not attached to a class, there’s no main class to reference to launch inside the IDE. Yet, Kotlin creates a .class with the same name as the file name suffixed with Kt.

    My file is named BootVaadinKotlinDemoApplication.kt, hence the generated class name is BootVaadinKotlinDemoApplicationKt.class. This is the class to reference to launch the application in the IDE. Note that there’s no need to bother about that when using mvn spring-boot:run on the command-line, as Spring Boot seems to scan for the main method.

    Short and readable bean definition

    Java syntax is seen as verbose. I don’t think it’s a big issue when its redundancy is very low compared to the amount of useful code. However, in some cases, even I have to admit it’s a lot of ceremony for not much. When of such case is defining beans with the Java syntax:

    @Bean @UIScope
    public MainScreen mainScreen() {
        return new MainScreen();
    }
    

    Kotlin cuts through all of the ceremony to keep only the meat:

    • No semicolon required
    • No new keyword
    • Block replaced with an equal sign since the body consists of a single expression
    • No return keyword required as there’s no block
    • No return type required as it can easily be inferred
    @Bean @UIScope
    fun mainScreen() = MainScreen()
    

    Spring configuration files are generally quite long and hard to read. Kotlin makes them much shorter, without sacrificing readability.

    The init block is your friend

    In Java, the constructor is used for different operations:

    1. storing arguments into attributes
    2. passing arguments to the super constructor
    3. other initialization code

    The first operation is a no-brainer because attributes are part of the class signature in Kotlin. Likewise, calling the super constructor is handled by the class signature. The rest of the initialization code is not part of the class signature and should be part of an init block. Most applications do not this part, but Vaadin needs to setup layout and related stuff.

    class MainScreenPresenter(tablePresenter: TablePresenter, buttonPresenter: NotificationButtonPresenter,
            view: MainScreen, eventBus: EventBus) : Presenter<MainScreen>(view, eventBus) {
    
        init {
            view.setComponents(tablePresenter.view, buttonPresenter.view)
        }
    }
    

    Use the apply method

    Kotlin has a standard library offering small dedicated functions. One of them is apply, defined as inline fun T.apply(f: T.() -> Unit): T (source). It’s an extension function, meaning every type will have it as soon as it’s imported into scope. This function requires an argument that is a function and that returns nothing. Inside this function, the object that has been apply-ed is accessible as this (and this is implicit, as in standard Java code). It allows code like this:

    VerticalLayout(button, table).apply {
        setSpacing(true)
        setMargin(true)
        setSizeFull()
    }
    

    Factor view and presenter into same file

    Kotlin makes code extremely small, thus some files might be only a line long (not counting import). Opening different files to check related classes is useless. Packages are a way to organize your code; I think files might be another way in Kotlin. For example, Vaadin views and presenters can be put into the same file.

    class NotificationButton: Button("Click me")
    class NotificationButtonPresenter(view: NotificationButton, eventBus: EventBus):
      Presente<NotificationButton>(view, eventBus) { ... }
    

    Lambdas make great listeners

    As of Java 8, single-method interfaces implemented as anonymous inner classes can be replaced with lambdas. Kotlin offers the same feature plus:

    • it allows to omit parentheses if the lambda is the only argument
    • if the lambda has a single argument, its default name is it and it doesn’t need to be declared

    Both make for a very readable syntax when used in conjunction with the Vaadin API:

    view.addValueChangeListener {
        val rowId = it.property.value
        val rowItem = view.containerDataSource.getItem(rowId)
        eventBus.publish(SESSION, rowItem)
    }
    

    Note: still, more complex logic should be put into its own function.

    Categories: JavaEE Tags: kotlinspring bootvaadin
  • My case for Event Bus

    Note: as I’ve attended Joker conference this week, I have to make a break in my “Going the microservices way” serie. However, I hope you dear readers will still enjoy this article.

    Informal talks with colleagues around the coffee machine are a great way to improve your developer skills. Most of the time, people don’t agree and that’s a good way to learn about thinking in context. One of the latest subject was about the Event Bus. Though no Android developer, I’m part of a Mobile team that uses an Event Bus to dispatch events among the different components of the application. Amazingly enough (at least for me), one team member doesn’t like Event Bus. As coincidence go, I just happened to read this post a few days later.

    I guess it’s my cue to make a case for Event Bus.

    There are several abstractions available to implement messaging, one of the first that comes to mind probably being the Observer pattern. It’s implemented in a variety of UI frameworks, such as AWT, Swing, Vaadin, you name it. Though it reverses the caller responsibility from the Subscriber (aka Observer) to the Observable (aka Subject), this pattern has a big drawback: in order for Subscriber to be notified of Observable’s event firing, the Observable has to hold a reference to a collection of Subscribers. This directly translates as strong coupling between them, though not in the usual sense of the term.

    To decrease coupling, the usual solution is to insert a third-party component between the two. You know where I’m headed: this component is the Event Bus. Now, instead of Observers registering to the Subject, they register to the Event Bus and Subject publishes events to the Event Bus.

    The coupling between Subject and Observer is now replaced by a coupling between Subject and EventBus : the Observable doesn’t need to implement a register() method with the Subscriber’s type as a parameter. Thus, the event can come from any source and that source can change in time with no refactoring needed on the Subscriber’s part.

    In the Java world, I know of 3 different libraries implementing Event Bus:

    In the latest two, the implementation of the notify() method is replaced by the use of annotation while in the former, it’s based on an agreed upon method signature(i.e. onEvent(Event<T>)). Thus, any type can be notified, removing the need to implement an Observer interface so that the coupling is reduced even further.

    Finally, all those implementations offer a way to pass an additional payload in the form of an event. This is the final design:

    Advantages of this design are manifold:

    • No need to reference both the Subscriber and the Observable in a code fragment to make the later register the former
    • No need to implement an Observer interface
    • Ability to pass additional payload
    • Many-to-many relations: one Subscriber can subscribe to different events, and an Observable can send different kind of events

    The only con, but it might be an issue depending on your context, is the order in which events are published. In this case, a traditional coupled method-calling approach is better suited. In all other cases - especially in the user interface layer and even more so when it’s designed with true graphical components (AWT, Swing, Android, Vaadin, etc.), you should give Event Bus a shot given all its benefits.

    For example, here’s an old but still relevant article on integrating Guava Event Bus with Vaadin.

  • Improving the Vaadin 4 Spring project with a simpler MVP

    I’ve been using the Vaadin 4 Spring library on my current project, and this has been a very pleasant experience. However, in the middle of the project, a colleague of mine decided to “improve the testability”. The intention was laudable, though the project already tried to implement the MVP pattern (please check this article for more detailed information). Instead of correcting the mistakes here and there, he refactored the whole codebase using the provided MVP module… IMHO, this has been a huge mistake. In this article, I’ll try to highlights the stuff that bugs me in the existing implementation, and an alternative solution to it.

    The existing MVP implementation consists of a single class. Here it is, abridged for readability purpose:

    public abstract class Presenter<V extends View> {
    
        @Autowired
        private SpringViewProvider viewProvider;
    
        @Autowired
        private EventBus eventBus;
    
        @PostConstruct
        protected void init() {
            eventBus.subscribe(this);
        }
    
        public V getView() {
            V result = null;
            Class<?> clazz = getClass();
            if (clazz.isAnnotationPresent(VaadinPresenter.class)) {
                VaadinPresenter vp = clazz.getAnnotation(VaadinPresenter.class);
                result = (V) viewProvider.getView(vp.viewName());
            }
            return result;
        }
    
        // Other plumbing code
    }
    

    This class is quite opinionated and suffers from the following drawbacks:

    1. It relies on field auto-wiring, which makes it extremely hard to unit test Presenter classes. As a proof, the provided test class is not a unit test, but an integration test.
    2. It relies solely on component scanning, which prevents explicit dependency injection.
    3. It enforces the implementation of the View interface, whether required or not. When not using the Navigator, it makes the implementation of an empty enterView() method mandatory.
    4. It takes responsibility of creating the View from the view provider.
    5. It couples the Presenter and the View, with its @VaadinPresenter annotation, preventing a single Presenter to handle different View implementations.
    6. It requires to explicitly call the init() method of the Presenter, as the @PostConstruct annotation on a super class is not called when the subclass has one.

    I’ve developed an alternative class that tries to address the previous points - and is also simpler:

    public abstract class Presenter<T> {
    
        private final T view;
        private final EventBus eventBus;
    
        public Presenter(T view, EventBus eventBus) {
            Assert.notNull(view);
            Assert.notNull(eventBus);
            this.view = view;
            this.eventBus = eventBus;
            eventBus.subscribe(this);
        }
    
        // Other plumbing code
    }
    

    This class makes every subclass easily unit-testable, as the following snippets proves:

    public class FooView extends Label {}
    
    public class FooPresenter extends Presenter<FooView> {
    
        public FooPresenter(FooView view, EventBus eventBus) {
            super(view, eventBus);
        }
    
        @EventBusListenerMethod
        public void onNewCaption(String caption) {
            getView().setCaption(caption);
        }
    }
    
    public class PresenterTest {
    
        private FooPresenter presenter;
        private FooView fooView;
        private EventBus eventBus;
    
        @Before
        public void setUp() {
            fooView = new FooView();
            eventBus = mock(EventBus.class);
            presenter = new FooPresenter(fooView, eventBus);
        }
    
        @Test
        public void should_manage_underlying_view() {
            String message = "anymessagecangohere";
            presenter.onNewCaption(message);
            assertEquals(message, fooView.getCaption());
        }
    }
    

    The same Integration Test as for the initial class can also be handled, using explicit dependency injection:

    public class ExplicitPresenter extends Presenter<FooView> {
    
        public ExplicitPresenter(FooView view, EventBus eventBus) {
            super(view, eventBus);
        }
    
        @EventBusListenerMethod
        public void onNewCaption(String caption) {
            getView().setCaption(caption);
        }
    }
    
    @Configuration
    @EnableVaadin
    public class ExplicitConfig {
    
        @Autowired
        private EventBus eventBus;
    
        @Bean
        @UIScope
        public FooView fooView() {
            return new FooView();
        }
    
        @Bean
        @UIScope
        public ExplicitPresenter fooPresenter() {
            return new ExplicitPresenter(fooView(), eventBus);
        }
    }
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = ExplicitConfig.class)
    @VaadinAppConfiguration
    public class ExplicitPresenterIT {
    
        @Autowired
        private ExplicitPresenter explicitPresenter;
    
        @Autowired
        private EventBus eventBus;
    
        @Test
        public void should_listen_to_message() {
            String message = "message_from_explicit";
            eventBus.publish(this, message);
            assertEquals(message, explicitPresenter.getView().getCaption());
        }
    }
    

    Last but not least, this alternative also let you use auto-wiring and component-scanning if you feel like it! The only difference being that it enforces constructor auto-wiring instead of field auto-wiring (in my eyes, this counts as a plus, albeit a little more verbose):

    @UIScope
    @VaadinComponent
    public class FooView extends Label {}
    
    @UIScope
    @VaadinComponent
    public class AutowiredPresenter extends Presenter<FooView> {
    
        @Autowired
        public AutowiredPresenter(FooView view, EventBus eventBus) {
            super(view, eventBus);
        }
    
        @EventBusListenerMethod
        public void onNewCaption(String caption) {
            getView().setCaption(caption);
        }
    }
    
    @ComponentScan
    @EnableVaadin
    public class ScanConfig {}
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = ScanConfig.class)
    @VaadinAppConfiguration
    public class AutowiredPresenterIT {
    
        @Autowired
        private AutowiredPresenter autowiredPresenter;
    
        @Autowired
        private EventBus eventBus;
    
        @Test
        public void should_listen_to_message() {
            String message = "message_from_autowired";
            eventBus.publish(this, message);
            assertEquals(message, autowiredPresenter.getView().getCaption());
        }
    }
    

    The good news is that this module is now part of the vaadin4spring project on Github. If you need MVP for your Vaadin Spring application, you’re just a click away!

    Categories: JavaEE Tags: open sourcespringvaadin
  • From Vaadin to Docker, a novice's journey

    I’m a huge Vaadin fan and I’ve created a Github workshop I can demo at conferences. A common issue with such kind of workshops is that attendees have to prepare their workstations in advance… and there’s always a significant part of them that comes with not everything ready. At this point, two options are available to the speaker: either wait for each of the attendee to finish the preparation - too bad for the people who took the time at home to do that, or start anyway - and lose the not-ready part.

    Given the current buzz around Docker, I thought that could be a very good way to make the workshop preparation quicker - only one step, and hasslefree - no problem regarding the quirks of your operation system. The required steps I ask the attendees are the following:

    1. Install Git
    2. Install Java, Maven and Tomcat
    3. Clone the git repo
    4. Build the project (to prepare the Maven repository)
    5. Deploy the built webapp
    6. Start Tomcat

    These should directly be automated into Docker. As I wasted much time getting this to work, here’s the tale of my journey in achieving this (be warned, it’s quite long). If you’ve got similar use-cases, I hope it will be useful in you getting things done faster.

    Starting with Docker

    The first step was to get to know the basics about Docker. Fortunately, I had the chance to attend a Docker workshop by David Gageot at Duchess Swiss. This included both Docker installation and basics of Dockerfile. I assume readers have likewise a basic understanding of Docker.

    For those who don’t, I guess browsing the Docker’s official documentation is a nice idea:

    Building my first Dockerfile

    The Docker image can be built with the following command ran into the directory of the Dockerfile:

    $ docker build -t vaadinworkshop .
    

    The first issues one can encounter when playing with Docker the first time, is to get the following error message:

    Get http:///var/run/docker.sock/v1.14/containers/json: dial unix /var/run/docker.sock: no such file or directory
    

    The reason is because one didn’t export the required environment variables displayed by the boot2docker information message. If you lost the exact data, no worry, just use the shellinit boot2docker parameter:

    $ boot2docker shellinit
    
    Writing /Users/i303869/.docker/boot2docker-vm/ca.pem:
    Writing /Users/i303869/.docker/boot2docker-vm/cert.pem:
    Writing /Users/i303869/.docker/boot2docker-vm/key.pem:
        export DOCKER_HOST=tcp://192.168.59.103:2376
        export DOCKER_CERT_PATH=/Users/i303869/.docker/boot2docker-vm
    

    Copy-paste the export lines above will solve the issue. These can also be set in one’s .bashrc script as it seems these values seldom change.

    Next in line is the following error:

    Get http://192.168.59.103:2376/v1.14/containers/json: malformed HTTP response "\x15\x03\x01\x00\x02\x02"
    

    This error message seems to be because of a mismatch between versions of the client and the server. It seems it is because of a bug on Mac OSX when upgrading. For a long term solution, reinstall Docker from scratch; for a quick fix, use the --tls flag with the docker command. As it is quite cumbersome to type it everything, one can alias it:

    $ alias docker="docker --tls"
    

    My last mistake when building the image comes from building the Dockerfile from a not empty directory. Docker sends every file it finds in the directory of the Dockerfile to the Docker container for build:

    $ docker --tls build -t vaadinworkshop .
    
    Sending build context to Docker daemon Too many kB
    

    Fix: do not try this at home and start from a directory container the Dockerfile only.

    Starting from scratch

    Dockerfiles describe images - images are built as a layered list of instructions. Docker images are designed around single inheritance: one image has to be set a single parent. An image requiring no parent starts from scratch, but Docker provides 4 base official distributions: busybox, debian, ubuntu and centos (operating systems are generally a good start).

    Whatever you want to achieve, it is necessary to choose the right parent. Given the requirements I set for myself (Java, Maven, Tomcat and Git), I tried to find the right starting image. Many Dockerfiles are already available online on the Docker hub. The browsing app is quite good, but to be really honest, the search can really be improved.

    My intention was to use the image that matched the most of my requirements, then fill the gap. I could find no image providing Git, but I thought the dgageot/maven Dockerfile would be a nice starting point. The problem is that the base image is a busybox and provides no installer out-of-the-box (apt-get, yum, whatever). For this reason, David uses a lot of curl to get Java 8 and Maven in his Dockerfiles.

    I foolishly thought I could use a different flavor of busybox that provides the opkg installer. After a while, I accumulated many problems, resolving one heading to another. In the end, I finally decided to use the OS I was most comfortable with and to install everything myself:

    FROM ubuntu:utopic
    

    Scripting Java installation

    Installing git, maven and tomcat packages is very straightforward (if you don’t forget to use the non-interactive options) with RUN and apt-get:

    RUN apt-get update && \\
        apt-get install -y --force-yes git maven tomcat8
    

    Java doesn’t fall into this nice pattern, as Oracle wants you to accept the license. Nice people did however publish it to a third-party repo. Steps are the following:

    1. Add the needed package repository
    2. Configure the system to automatically accept the license
    3. Configure the system to add un-certified packages
    4. Update the list of repositories
    5. At last, install the package
    6. Also add a package for Java 8 system configuration
    RUN echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list && \\
        echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections && \\
        apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886
    
    RUN apt-get update && \\
        apt-get install -y --force-yes oracle-java8-installer oracle-java8-set-default
    

    Building the sources

    Getting the workshop’s sources and building them is quite straightforward with the following instructions:

    RUN git clone  https://github.com/nfrankel/vaadin7-workshop.git
    WORKDIR /vaadin7-workshop
    RUN mvn package
    

    The drawback of this approach is that Maven will start from a fresh repository, and thus download the Internet the first time it is launched. At first, I wanted to mount a volume from the host to the container to share the ~/.m2/repository folder to avoid this, but I noticed this could only be done at runtime through the -v option as the VOLUME instruction cannot point to a host directory.

    Starting the image

    The simplest command to start the created Docker image is the following:

    $ docker run -p 8080:8080
    

    Do not forget the port forwarding from the container to the host, 8080 for the standard HTTP port. Also, note that it’s not necessary to run the container as a daemon (with the -d option). The added value of that is that the standard output of the CMD (see below) will be redirected to the host. When running as a daemon and wanting to check the logs, one has to execute bash in the container, which requires a sequence of cumbersome manipulations.

    Configuring and launching Tomcat

    Tomcat can be launched when starting the container by just adding the following instruction to the Dockerfile:

    CMD ["catalina.sh", "run"]
    

    However, trying to start the container at this point will result in the following error:

    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
    WARNING: Problem with directory [/usr/share/tomcat8/common/classes], exists: [false], isDirectory: [false], canRead: [false]
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
    WARNING: Problem with directory [/usr/share/tomcat8/common], exists: [false], isDirectory: [false], canRead: [false]
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
    WARNING: Problem with directory [/usr/share/tomcat8/server/classes], exists: [false], isDirectory: [false], canRead: [false]
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
    WARNING: Problem with directory [/usr/share/tomcat8/server], exists: [false], isDirectory: [false], canRead: [false
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
    WARNING: Problem with directory [/usr/share/tomcat8/shared/classes], exists: [false], isDirectory: [false], canRead: [false]
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.ClassLoaderFactory validateFile
    WARNING: Problem with directory [/usr/share/tomcat8/shared], exists: [false], isDirectory: [false], canRead: [false]
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.Catalina initDirs
    SEVERE: Cannot find specified temporary folder at /usr/share/tomcat8/temp
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.Catalina load
    WARNING: Unable to load server configuration from [/usr/share/tomcat8/conf/server.xml]
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.Catalina initDirs
    SEVERE: Cannot find specified temporary folder at /usr/share/tomcat8/temp
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.Catalina load
    WARNING: Unable to load server configuration from [/usr/share/tomcat8/conf/server.xml]
    Nov 15, 2014 9:24:18 PM org.apache.catalina.startup.Catalina start
    SEVERE: Cannot start server. Server instance is not configured.
    

    I have no idea why, but it seems Tomcat 8 on Ubuntu is not configured in any meaningful way. Everything is available but we need some symbolic links here and there as well as creating the temp directory. This translates into the following instruction in the Dockerfile:

    RUN ln -s /var/lib/tomcat8/common $CATALINA_HOME/common && \\
        ln -s /var/lib/tomcat8/server $CATALINA_HOME/server && \\
        ln -s /var/lib/tomcat8/shared $CATALINA_HOME/shared && \\
        ln -s /etc/tomcat8 $CATALINA_HOME/conf && \\
        mkdir $CATALINA_HOME/temp
    

    The final trick is to connect the exploded webapp folder created by Maven to Tomcat’s webapps folder, which it looks for deployments:

    RUN mkdir $CATALINA_HOME/webapps && \\
        ln -s /vaadin7-workshop/target/workshop-7.2-1.0-SNAPSHOT/ $CATALINA_HOME/webapps/vaadinworkshop
    

    At this point, the Holy Grail is not far away, you just have to browse the URL… if only we knew what the IP was. Since running on Mac, there’s an additional VM beside the host and the container that’s involved. To get this IP, type:

    $ boot2docker ip
    The VM's Host only interface IP address is: 192.168.59.103
    
    

    Now, browsing http://192.168.59.103:8080/vaadinworkshop/ will bring us to the familiar workshop screen:

    Developing from there

    Everything works fine but didn’t we just forget about one important thing, like how workshop attendees are supposed to work on the sources? Easy enough, just mount the volume when starting the container:

    docker run -v /Users/<login>/vaadin7-workshop:/vaadin7-workshop  -p 8080:8080 vaadinworkshop
    

    Note that the host volume must be part of /Users and if on OSX, it must use boot2docker v. 1.3+.

    Unfortunately, it seems now is the showstopper, as mounting an empty directory from the host to the container will not make the container’s directory available from the host. On the contrary, it will empty the container’s directory given that the host’s directory doesn’t exist… It seems there’s an issue in Docker on Mac. The installation of JHipster runs into the same problem, and proposes to use the Samba Docker folder sharing project.

    I’m afraid I was too lazy to go further at this point. However, this taught me much about Docker, its usages and use-cases (as well as OSX integration limitations). For those who are interested, you’ll find below the Docker file. Happy Docker!

    FROM ubuntu:utopic
    MAINTAINER Nicolas Frankel <nicolas [at] frankel (dot) ch>
    
    # Config to get to install Java 8 w/o interaction
    RUN echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list && \
    echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections && \
    apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886
    RUN apt-get update && \
    apt-get install -y --force-yes git oracle-java8-installer oracle-java8-set-default maven tomcat8
    RUN git clone https://github.com/nfrankel/vaadin7-workshop.git
    WORKDIR /vaadin7-workshop
    RUN git checkout v7.2-1
    RUN mvn package
    ENV JAVA_HOME /usr/lib/jvm/java-8-oracle
    ENV CATALINA_HOME /usr/share/tomcat8
    ENV PATH $PATH:$CATALINA_HOME/bin
    
    # Configure Tomcat 8 directories
    RUN ln -s /var/lib/tomcat8/common $CATALINA_HOME/common && \
    ln -s /var/lib/tomcat8/server $CATALINA_HOME/server && \
    ln -s /var/lib/tomcat8/shared $CATALINA_HOME/shared && \
    ln -s /etc/tomcat8 $CATALINA_HOME/conf && \
    mkdir $CATALINA_HOME/temp && \
    mkdir $CATALINA_HOME/webapps && \
    ln -s /vaadin7-workshop/target/workshop-7.2-1.0-SNAPSHOT/ $CATALINA_HOME/webapps/vaadinworkshop
    VOLUME ["/vaadin7-workshop"]
    CMD ["catalina.sh", "run"]
    
    # docker build -t vaadinworkshop .
    # docker run -v ~/vaadin7-workshop training/webapp -p 8080:8080 vaadinworkshop
    
    Categories: Development Tags: dockervaadin
  • Vaadin and Spring integration through JavaConfig

    When I wrote the first version of Learning Vaadin, I hinted at how to integrate Vaadin with the Spring framework (as well as CDI). I only described the overall approach by providing a crude servlet that queried the Spring context to get the Application instance.

    At the time of Learning Vaadin 7, I was eager to work on add-ons the community provided in terms of Spring integration. Unfortunately, I was sorely disappointed, as I found only few and those were lacking in one way or another. The only stuff mentioning was an article by Petter Holmström - a Vaadin team member (and voluntary fireman) describing how one should do to achieve Vaadin & Spring integration. It was much more advanced than my own rant but still not a true ready-to-be-used library.

    So, when I learned that both Vaadin and Spring teams joined forces to provided a true integration library between two frameworks I love, I was overjoyed. Even better, this project was developed by none other than Petter for Vaadin and Josh Long for Pivotal. However, the project was aimed at achieving DI through auto-wiring. Since JavaConfig makes for a cleaner and more testable code, I filled an issue to allow that. Petter kindly worked on this, and in turn, I spent some time making it work.

    The result of my experimentation with Spring Boot Vaadin integration has been published on morevaadin.com, a blog exclusively dedicated to Vaadin.

    Categories: JavaEE Tags: javaconfigspringvaadin
  • Learning Vaadin 7 is out!

    Hey everyone! No code nor rant for this week’s article but just a very good news: Learning Vaadin 7 has been published!

    This new edition of Learning Vaadin describes of course what is new in Vaadin 7 as well has changes from v6 to v7, but also introduces some great additional stuff:

    • Added a section about JavaEE integration: Servlet API, CDI and JPA
    • Added a section about the new connectore architecture: reworked GWT wrapping and added JavaScript wrapping
    • Moved and updated stuff from add-ons to core platform, the best example is Server Push
    • Added a section on a XML-based GUI feature with the Clara add-on - IMHO, this should be integrated into the core sooner or later
    • Upgraded versions of Gatein (for portals) and GlassFish (for OSGi)
    • Replaced Cloud Foundry PaaS with Jelastic PaaS as the latter is part of Vaadin offering
    • After having evaluated some Spring add-ons, completely dropped Spring section, as I found none of them satisfying. Stay tuned however as Spring integration is on the roadmap. Stay tuned on morevaadin.com when it's launched, I'll probably want to play with it.
    • Updated Maven integration - it's not as easy as it was
    • And much much more!

    You can get Learning Vaadin 7 through a variety of channels, including Packt, Amazon, Barnes & Nobles or Safari Books Online.

    Categories: Java Tags: bookvaadin
  • Devoxx France 2013 - Day 1

    Rejoice people, it’s March, time for Devoxx France 2013! Here are some notes I took during the event.

    Java EE 7 hands-on lab by David Delabasse & Laurent Ruaud

    An hands-on lab by Oracle for good old-fashioned developers that want to check some Java EE 7 features by themselves.

    This one, you can do it at home. Just go to this page and follow instructions. Note you will need at least Glassfish 4 beta 80 and the latest NetBeans (7.3).

    You’d better reserve a day if you want to go beyond copy-paste and really read and understand what you’re doing. Besides, you have to some JSF knowledge if anything goes wrong (or have a guru on call).

    Angular JS by Thierry Chatel

    The speaker comes from a Java developer background. He has used Swing in the past and since then, he has searched for binding features: a way to automate data exchange between model and views. Two years ago, he found AngularJS.

    AngularJS is a JavaScript framework, comprised of more than +40 kloc and weights 77 kb minified. The first stable version was released one year ago, codenamed temporal-domination. The application developed by Google with AngularJS is Doubleclick for publishers. Other examples include OVH’s future management console and Youtube application on PS3. Its motto is:

    HTML enhanced for web apps

    What does HTML enhanced means? Is it HTML6? The problem is HTML has never been designed to create applications: it is only to display documents and link between them. Most of the time, one-way binding between Model & Template is achieved to create a view. Misko Hevery (AngularJS founder) point of view is instead of trying to go around this limitation, we’d better add this feature to HTML.

    So, AngularJS philosophy is to compile the View from the Template, and then 2-way bind between View & Model. AngularJS use is easy as pie:

    Your name: <input type="text" ng-model="me">
    Hello {{me}}
    

    AngularJS is a JavaScript framework, that free developers from coding too manyJavaScript lines.

    The framework uses simple concepts:

    • watches around expressions (properties, functions, etc.)
    • dirty checking on events (keyboard, HTTP request, etc.)

    Watches are re-evaluated on each dirty checks. This means expressions have to be simple (i.e. computation results instead of the computations themselves). The framework is designed to handle up to 2000 simple watches. Keep note that standards (as well as user agents) are evolving and that ECMAScript next version will provide Object.observer() to handle x50 the actual number of watches.

    An AngularJS app is as simple as:

    <div ng-app="myapp"></div>
    

    This let us have as many applications as needed on the same page. AngularJS is able to create single-page applications, with browser navigation (bookmarks, next, previous) automatically handled. There’s no such thing like global state.

    AngularJS also provides core concepts like modules, services and dependency injection. There’s no need to inherit from specific classes or interfaces: any object is available for any role. As a consequence, code is easily unit-testable, the preferred tool to do this is Karma (ex-Testacular). For end-to-end scenarii testing, the same dedicated tool is also available, based on the framework and plays tests in defined browsers. In conclusion, AngularJS is not only a framework but also a complete platform with the right level of abstraction, so that developed code is purely business.

    There are no AngularJS UI components, but many are provided by third-party like AngularUI, AngularStrap, etc.

    AngularJS is extremely structuring, it is an opinionated framework. You have to code the AngularJS way. A tutorial is readily available to let you do that. Short videos dedicated to a single focused theme are available online.

    Wow, this the second talk I attend about AngularJS and it looks extremely good! My only complaints are that is follows the trend of pure client-side frameworks and that is not designed for mobile.

    Gradle, 30 minutes to change all by Sébastien Cogneau

    In essence, Gradle is a Groovy DSL to automate build. It is extensible through Java & Groovy plugins. Gradle is based on existing principles: it let you reuse Ant tasks, it reuses Maven convention and is compatible with both Ivy & Maven repositories.

    A typical gradle build file looks like this:

    
    apply plugin: 'jetty'
    version = '1.0.0'
    repositories {
        mavenCentral()
    }
    
    configuration {
        codeCoverage
    }
    
    sonarRunner {
        sonarProperties {
            ...
        }
    }
    
    dependencies {
        compile: 'org.hibernate:hibernate-core:3.3.1.GA'
        codeCoverage: 'org.jacoco....'
    }
    
    test {
        jvmArgs '...'
    }
    
    task wrapper(type:Wrapper) {
        gradleVersion = '1.5-rc3'
    }
    
    task hello(type:Exec) {
        description 'Devoxx 2013 task'
        group 'devoxx'
        dependsOn wrapper
        executable 'echo'
        args 'Do you have question'
    }
    
    

    Adding plugins add tasks to the available build. For example, by adding jetty, we get jettyStart. Moreover, plugins have dependencies so you also have tasks from dependent plugins.

    Gradle can be integrated with Jenkins, as there is an available Gradle plugin. There are two available options to run Gradle build on Jenkins:

    • either you install Gradle and configure its installation on Jenkins. From this point, you can configure your build to use this specific install
    • or you generate a Gradle wrapper and only configure your build to use this wrapper. There's no need to install Gradle at all in this case

    Gradle power let also add custom tasks, such as the aforementioned hello task.

    The speaker tells us he is using Gradle because it is so flexible. But that’s exactly the reason I’m more than reluctant to adopt it: I’ve been building with Ant for ages, then came to Maven. Now, I’m forced to use Ant again and it takes so much time to understand a build file compared to a Maven POM.

    Space chatons, bleeding-edge HTML5 by Phillipe Antoine & Pierre Gayvallet

    This presentation demoed new features brought by HTML5.

    It was too quick to assimilate anything, but demos were really awesome. In particular, one of them used three.js, a 3D rendering library that you should really have a look into. When I think it took raytracing to achieve this 15 years ago..

    Vaadin & GWT 2013 Paris Meetup

    Key points (because at this time, I was more than a little tired):

    • My presentation on FieldGroup and Converters is available on Slideshare
    • Vaadin versions are supported for 5 years each. Vaadin 6 support will end in 2014
    • May will see the release of a headless of Vaadin TestBench. Good for automated tests!
    • This Friday, Vaadin 7.1 will be out with server push
    • Remember that Vaadin Ltd also offers Commercial Support (and it comes with a JRebel license!)
    Categories: Event Tags: angularjsdevoxxhtml5vaadin
  • Announcing More Vaadin

    During the writing of ‘Learning Vaadin’, I had many themes I wanted to write about: components data, SQL container filtering, component alignment and expand ration, separation of concerns between graphic designers and developers, only to name a few. Unfortunately, books are finite in space as well as in time and I was forced to leave out some interesting areas of Vaadin that couldn’t fit in, much to my chagrin.

    Give the success of ‘Learning Vaadin’, I’ve decided to create a site that is meant to gap the bridge between what I wanted and what I could: More Vaadin. Expect to see there articles related to Vaadin! I’ve also decided to open the platform to other contributors, for those interested.

    As a bonus, this is the first article (original article here).

    Table generated buttons

    Before diving in the middle of the subject, let’s have a use-case first. Imagine we have a CRUD application and our current screen lists the datastore entities in a table, a line per entity and a column per property.

    Now, in order to implement the Delete functionality, we use the addGeneratedColumn method of the Table component to display a “Delete” button, like in the following screenshot:

    Table with Delete button

    The problem lies in the action that has to take place when the button is pressed. The behavior needs to be determined when the page is generated, so that the event is processed directly on the server-side: in other words, we need a way to pass the entity identifier (or the container’s item or even the container’s item id) to the button somehow.

    The solution is very simple to implement, with just the use of the final keyword, to let nested anonymous class methods access parameters:

    table.addGeneratedColumn("", new ColumnGenerator() {
    
        @Override
        public Object generateCell(final Table source, final Object itemId, Object columnId) {
            Button button = new Button("Delete");
    
            button.addListener(new ClickListener() {
                @Override
                public void buttonClick(ClickEvent event) {
                    source.getContainerDataSource().removeItem(itemId);
                }
            });
    
            return button;
        }
    });
    

    Remember to regularly check More Vaadin for other reindeer articles :-)

    Categories: Java Tags: vaadin
  • 'Learning Vaadin' contest winners

    Dear readers,

    Thanks for your participation in the ‘Learning Vaadin’ contest. It’s my pleasure to announce the winners:

    • Adolfo Benedetti who commented on the integration side of 'Learning Vaadin'
    • Sebastian who also commented about integration
    • A. Jansenn who noted the Vaadin team is very positive about 'Learning Vaadin' and that it's a good complement to the available documentation

    The winners will be contacted by a Packt representative about the details.

    The choice was hard and I know there will be some deception for not having won a copy. Nevertheless, you can always purchase the book at Packt or Amazon.

    Categories: JavaEE Tags: vaadin
  • 'Learning Vaadin' is out

    This is it! After 10 monts of work, my first book is out: ‘Learning Vaadin’ is now available at Packt and Amazon.

    First things first, what’s is Vaadin? Vaadin is a presentation-layer web framework that let you easily develop Rich Internet Applications. It does so by provding an abstraction over the Servlet API and by letting developers assemble components to design screens (as opposed to pages as in previous generation web frameworks). If you got 5 minutes to spare, you can go try the tutorial and be convinced yourself. Note that I do not hold Vaadin for a golden hammer, but in most contexts, it just is the right tool.

    Now, why write a book? An imperative prerequisite is to believe in the subject. For me, it was love at first sight… I already wrote on Vaadin and used it in real pre-sales demos. During a conversation with Joonas Lehtinen, Vaadin’s CEO, he mentioned he had been approached by Pack to write a book on the subject. My brain processed the information and mere minutes later, I proposed myself.

    Although writing a book is like coding in a project in many ways: there’s a schedule, limited time, reviewing (testing), rewriting (bug fixing), ups and downs, it has not been easy for me. I’m admirative of people who regularly write books in their spare time. They need discipline, of course, but also a supportive family and the right publisher. Fortunately, I had these assets this time and I’m now proud to have finished the book.

    But is it finished? The strangest is that I do not realize yet. I’m waiting to hold a hard-copy in my hands to really think ‘I’ve done it’. Once received, I believe I will be entitled to some much-deserved R&R :-)

    ‘Learning Vaadin’ in the news:

    You’re welcome to mention other references I may have missed.

    Categories: JavaEE Tags: vaadin
  • Vaadin courses on JavaBlackBelt

    For those of you who haven’t heard of JavaBlackBelt, it’s an e-learning community site. Once registered, users can use the site in a variety of ways:

    • First, one can take courses on a variety of programming-related subjects.
    • Then, one can pass exams on these subjects. Each exam is made of questions one has to anwser in a limited time frame. Passing an exam gives you knowledge points; with enough knowledge points, you get the next belt, until the fabled black belt!
    • One can also contribute to the questions pool. Questions give you contribution points: after a certain belt, one needs paying a certain amount of contribution points in order to pass an exam, thus ensuring you give back to the community.
    • Finally, the last version of JavaBlackBelt - also known as BlackBeltFactory - brings the notion of coach: one can offer and/or receive individual mentoring.

    I’m a JavaBlackBelt user since a couple of years. At first, it was in order to get my black belt (boys and their toys). Then, recently, my interest in it was renewed, primarly due to two things:

    • BlackBeltFactory was remade using the Vaadin framework. At this time, it was the biggest reference for Vaadin.
    • Given their freshly acquired Vaadin skills, the BlackBelt team created  a new subject for the community to work on, Vaadin.

    Since Vaadin is becoming more and more an option for the presentation layer, at the beginning of the month, JavaBlackBelt announced the addition of Vaadin Advanced Core, in order for the existing Vaadin Fundamentals not to become bloated.

    People interested in the effort of creating and reviewing both courses and questions are welcomed (and encouraged) to do so!

    PS: remember JavaBlackBelt is first and foremost fun. Don’t take your belts (however high they are) too seriously. John Rizzo, the site’s founder, is only a blue belt while Marko Grönroos, a Vaadin Fundamental leader is white belt. Be humble…

    Categories: Technical Tags: blackbeltvaadin
  • New Filter API in Vaadin 6.6

    Vaadin is available in version 6.6 preview since this week. Among other interesting enhancements, one surely caught my attention, the new Filter API.

    To understand why it’s so interesting, one must know how it’s handled in version 6.5 and before. But first, a word about filters in Vaadin: they are used in containers, which handle collections of items, in order to sort out eligible items. The Container.Filterable interface define a method to add a single filter, whose signature is:

    addContainerFilter(Object propertyId, String filterString, boolean ignoreCase, boolean onlyMatchPrefix)
    

    So, we can only filter on string equality, and this equality can be loosened/tightened toward case and position. Morevoer, filters on the same property are additive. If you need to go beyond that, your goose is cooked. In a previous proposal to a request, the filter had to be accent insensitive, which is not supported. I had to hack like mad to implement it. In effect, since most of the container API’s code is private, I copied it to offer the needed option alternative. It did the trick but it’s pretty dirty.

    However, the new API supplies a true extensible model for filters which renders my previous development obsolete. Facts worth mentioning are the following:

    • The Container.Filterable interface becomes Container.SimpleFilterable, with no other changes in the method signatures
    • A brand-new Container.Filterable is added, with the method:
    addContainerFilter(Container.Filter filter)
    
    • The Filter interface becomes public, and brings an entire hierarchy, with boolean composition in mind (meaning you can OR, AND or NOT you filters in combination). The interface has two methods:
    appliesToProperty(Object propertyId)
    passesFilter(Object itemId, Item item)
    

    These updates make creating an accent-insensitive a breeze. Conclusion is, if you’re interested in Vaadin, you have to take a look at the new version, if only for the filter API!

    To go further:

    • Vaadin 6.6.0 pre1 is available here
    Categories: JavaEE Tags: vaadin
  • Learning Vaadin

    Vaadin is a Rich Internet Application framework in Java that let developers code applications in a very productive way. For more information regarding Vaadin, please consult its site.

    When one wants to learn a framework, one needs to read some documentation. In this regard, Vaadin provides plenty resources:

    This amount of documentation and its level of quality is rarely seen in OpenSource projects. However, I do think there’s a missing link since the book’s intended audience is developers who will “just” code.

    But my experience taught me many will want to go beyond that and understand the big picture as well as nitty-gritty implementation details. In order to provide just this kind of information, I’ve begun the writing of a “Learning Vaadin” book with Packt Publishing, since I believe Vaadin can be be for the presentation layer what Spring was for Java EE: an excellent productivity-oriented tool that ease development. “Learning Vaadin” targets developers who start from the very beginnings but want to deeply understand what they do.

    I got excellent working relationship with the Vaadin’s team as well as the support of Joonas Lehtinen, Vaadin’s fater (thanks Joonas for answering my many questions). Book reviews will be done by members of Vaadin’s team.

    Writing is well underway, having written 5 draft chapters on a total of 10. You can support me in this new challenge by acquiring a copy of the book when it’s delivered (exp. Jan. 2012) or if you can’t wait, the ebook in RAW (draft) mode is available now! Note that since Vaadin is OpenSource, Packt will pay royalties to the project itself.

    Categories: JavaEE Tags: vaadin
  • Second try with Vaadin and Scala

    My article from last week left me mildly depressed: my efforts trying to ease my Vaadin development was brutally stopped when I couldn’t inherit from a Java inner class in Scala. I wondered if it was an impossibility or mere lack of knowledge on my part.

    Fortunately, Robert Lally and Dale gave me the solution in their comments (many thanks to them). The operator used to access an inner class from Java in Scala is #. Simple, yet harder to google… This has an important consequence: I don’t have to create Java wrapper classes, and I can have a single simple Maven project!

    Afterwared, my development went much better. I tried using the following Scala features.

    Conciseness

    As compaired to last week, my listener do not use any Java workaround and just becomes:

    @SerialVersionUID(1L)
    class SimpleRouterClickListener(eventRouter:EventRouter) extends ClickListener {
     def buttonClick(event:Button#ClickEvent) = eventRouter.fireEvent(event)
    }
    

    Now, I can appreciate the lesser verbosity of Scala. This becomes apparent in 3 points:

    • @SerialVersionUID : 10 times better than the field of the same name
    • No braces! One single line that is as readable as the previous Java version, albeit I have to get used to it
    • A conciseness in the class declaration, since both the constructor and the getter are implicit

    Trait

    CustomComponent does not implement the Observer pattern. Since it is not the only one, it would be nice to have such a reusable feature, in other words, a Scala trait. Let’s do that:

    trait Router {
      val eventRouter:EventRouter = new EventRouter()
    }
    

    Note to self: next time, I will remember that Class<?> in Java is written Class[_] in Scala. I had the brackets right from the start but lost 10 minutes with the underscore…

    Now, I just have to declare a component class that mixin the trait and presto, my component has access to an event router object.

    Late binding

    Having access to the event router object is nice, but not a revolution. In fact, the trait exposes it, which defeats encapsulation and loose coupling. It would definitely be better if my router trait would use the listener directly. Let’s add this method to the trait:

    def addListener(clazz:Class[_], method:String) = eventRouter.addListener(clazz, this, method)
    

    I do not really know if it’s correct to use the late-binding term in this case, but it looks like it, since this references nothing in the trait and will be bound later to the concrete class mixing the trait.

    The next stop

    Now, I’ve realized that the ClickListener interface is just a thin wrapper around a single function: it’s the Java way of implementing closures. So, why should I implement this interface at all?

    Why can’t I write something like this val f(event:Button#ClickEvent) = (eventRouter.fireEvent(_)) and pass this to the addListener() method of the button? Because it doesn’t implement the right interface. So, I ask myself if there is a bridge between the Scala first-class function and single method interfaces.

    Conclusion

    I went further this week with my Scala/Vaadin experiments. It’s getting better, much better. As of now, I don’t see any problems developing Vaadin apps with Scala. When I have a little more time, I will try a simple app in order to discover other problems, if they exist.

    You can find the sources of this article here, in Maven/Eclipse format.

    To go further:

    Categories: JavaEE Tags: scalavaadin
  • Mixing Vaadin and Scala (with a touch of Maven)

    People who are familiar with my articles know that I’m interested in Vaadin (see the “Go further” section below) and also more recently in Scala since both can increase your productivity.

    Environment preparation

    Thus it is only natural that I tried to embed the best of both worlds, so to speak, as an experience. As an added challenge, I also tried to add Maven to the mix. It wasn’t as successful as I had wished, but the conclusions are interesting (at least to me).

    I already showed how to create Scala projects in Eclipse in a previous post, so this was really a no-brainer. However, layering Maven on top of that was trickier. The scala library was of course added to the dependencies list, but I didn’t found how to make Maven compile Scala code so that each Eclipse save does the compilation (like it is the case with Java). I found the maven-scala-plugin provided by Scala Tools. However, I wasn’t able to use it to my satisfaction with m2eclipse. Forget the Maven plugin… Basically what I did was create the Maven project, then update the Eclipse configuration from Maven with m2eclipse and finally add the Scala builder: not very clean and utterly brittle since any update would overwrite Eclipse files. I’m all ears if anyone knows the “right” way to do!

    Development time

    Now to the heart of the matter: I just want a text field and a button that, when pressed, displays the content of the field. Simple enough? Not really. The first problem I encountered was to create an implementation of the button click listener in Scala. In Vaadin, the listener interface has a single method void buttonClick(Button.ClickEvent event). Notice the type of the event? It is an inner class of Button and wasn’t able to import it in Scala! Anyone who has the solution is welcome to step forward and tell it.

    Faced with this limitation, I decided to encapsulate both the listener and the event class in two standard Java classes, one in each. In order to be decoupled, not to mention to ease my life, I created a parent POM project, and two modules, one for the Java workaround classes, the other for the real application.

    Next obstacle is also Scala-related, and due to a lack of knowledge on my part. I’m a Java boy so, in order to pass a Class instance, I’m used to write something like this:

    eventRouter.addListenerVisibleClickEvent.class, this, "displayMessage")
    

    Scala seems to frown upon it and refuses to compile the previous code. The message is “identifier expected but ‘class’ found”. The correct syntax is:

    eventRouter.addListener(classOf[VisibleClickEvent], this, "displayMessage")
    

    Moreover, while developing, I wrote a cast the Java way:

    getWindow().showNotification(button.getCaption() + " " + (String) field.getValue())
    

    My friend Scala loudly complained that “object String is not a value” and I corrected the code like so:

    getWindow().showNotification(button.getCaption() + " " + field.getValue().asInstanceOf[String])
    

    Astute readers should have remarked that concatenating strings render this cast unnecessary and I gladly removed it in the end.

    Conclusion

    In the end, it took more time than if I had done the example in Java.

    • For sure, some of the lost time is due to a lack of Scala knowledge on my part.
    • However, I'm not sure the number of code lines would have been lower in Java, due to the extra-code in order to access inner classes .
    • In fact, I'm positive that the project would have been simpler with Java instead of Scala (one project instead of a parent and 2 modules).

    The question I ask myself is, if Scala cannot extend Java inner classes - and that being no mistake on my part, should API evolve with this constraint? Are inner classes really necessary in order to achieve a clean design or are they only some nice-to-have that are not much used?

    In all cases, developers who want to code Vaadin applications in Scala should take extra care before diving in and be prepared to have a lower productivity than in Java because there are many inner classes in Vaadin component classes.

    You can find the sources for this article here in Maven/Eclipse format.

    To go further:

    Categories: JavaEE Tags: mavenscalavaadin
  • Playing with Spring Roo and Vaadin

    One year ago, under the gentle pressure of a colleague, I tried Spring Roo. I had mixed feelings about the experience: while wanting to increase productivity was of course a good idea, I had concerned regarding Roo’s intrusiveness. I left it at that, and closed the part of my memory related to it.

    Now, one year later, I learned that my favourite web framework, namely Vaadin, had set their sight on a Roo plugin. That was enough for me to get back on my feet and try again. This article tries to describe as honestly as possible the good and the bad of this experience related to both Roo and the Vaadin plugin.

    Pure Roo

    First of all, I download the free STS 2.5, that includes Roo 1.1.1 and install it. No problem at this time. Then, I create a new Spring Roo project inside STS. Unluckily, STS does not create the default maven directories (src/main-test/java-resources): errors appear in my Problems tab. Trying to solve the project, I type the project command into Roo’s shell inside STS. Roo complains I should give it my top-level package, though I already did that with the wizard. OK, I am a nice guy and do as asked:

    project --topLevelPackage ch.frankel.blog.roo.vaadin

    This time, Roo successfully creates the aforementioned directories as well as a Spring configuration file and a log4j properties file.

    Next step is to create my persistence layer. The use of CTRL+SPACE is real nice and helps you much with command parameters. Combined with hint, it’s real easy to get comfortable with Roo.

    persistence setup --provider HIBERNATE --database DERBY

    Roo nicely updates my Maven POM and let it download the latest version right dependencies (JPA, Hibernate, Derby, etc.). I can always change version if I need a specific one. It even adds JBoss Maven repo so I can download Hibernate. I just need to update my database properties, driver and URL. Uh oh: when I open the file, I see Roo has strangely escaped colons characters with backslash. I just replace the example escaped URL with an unescaped real one.

    Meanwhile, I notice an error in the log: “The POM for org.aspectj:aspectjtools:jar:1.6.11.M1 is missing, no dependency information available”. Roo updated my POM with version 1.6.11.M1. If I check on repo1, the latest version is 1.6.10. Replacing 1.6.11.M1 with 1.6.10 removes the error.

    Now would be a good time to create my first entity:

    entity --class ~.entity.Teacher --testAutomatically

    STS now complains that the target directory doesn’t exist, like before it complained for source directories. In order to remedy to that, I just do as before, I launch an instruction. In this case, I order Roo to launch the tests with the perform test command. In turn, Roo launches mvn test under the hood and Maven does create the target directory.

    Entities without fields are useless. Let’s add a first name and a name to our teacher.

    field string --fieldName firstName

    field string –fieldName name</code>

    It would be cool to have courses attached.

    entity --class ~.entity.Course --testAutomatically

    field string –fieldName name

    focus –class Teacher

    field set –fieldName courses –type Course</code>

    Notice that since Roo works in a contextual manner, I have to use the focus command so that I do not create the courses Set inside the Course class but inside the Teacher class.

    Vaadin plugin

    Until now, there was nothing about Vaadin. Here it comes: following the instructions from Vaadin’s wiki, I download the latest Vaadin Roo plugin snapshot and put in in my Roo local OSGI repository. In order to the new bundle to be seen by Roo, I have to restart it which I don’t know how to do inside STS. Instead, I restart STS.

    There comes the magic command:

    vaadin setup --applicationPackage ~.web --useJpaContainer false

    This command:

    • adds Vaadin dependency
    • adds web directory with images
    • updates the POM to war packaging

    Yet, when I try to add my new web project to Tomcat, STS complains it doesn’t find candidate projects. The problem lies in that Eclipse is not synchronized with Maven and as such, my project lacks the Web facet. The solution: right-click on my project, go to the Maven menu and click on “Update project configuration” submenu. When done, I can add the project to Tomcat like any other web project (since it is anyway).

    Starting Tomcat and going to http://localhost:8080/vaadin, I can see Vaadin handling my request. I just miss the views over my entities, which is done with the following:

    vaadin generate all --package ~.web.ui --visuallyComposable true

    Conclusion

    Well, that was quick, if not perfect. I do miss some features in Roo:

    As for the Vaadin plugin, it lacks updating Eclipse files after having changed the POM. Someone not familiar with m2eclipse inner workings could lose some time with this behaviour.

    On the other hand, I have a simple webapp in a matter of minutes, that I can now update how I choose. CTRL+SPACE and hint are Roo killer features. Moreover, like the Vaadin add-on showed, you can add whatever functionality is lacking with your own plugin (or use one already available). What’s really important for me though, and without it, I wouldn’t even consider using Roo is that it is completely removable in 3 easy steps. As such you can use Roo’s productivity boost, not tell anyone and remove Roo just before passing your project to the maintenance team.

    Thanks to Joonas Lehtinen and Henri Sara for their work on Roo Vaadin’s plugin and sending me ahead of schedule the wiki draft explaining the Vaadin part.

    Here are the sources for this article in Maven/STS format.

    To go further:

    Categories: JavaEE Tags: roospringvaadin
  • Server-client push with Vaadin

    Vaadin Logo

    I’m more and more comitted into Vaadin since I see so many advantages to this solution. This time, I’ve investigated how to push server data to the client.

    Vaadin is a general purpose framework that is wise enough not to force you to code in one way or another. Many features are available in the core distribution but many more are available in the add-ons directory. One such add-on let you add push feature to your simple application. This add-on is based on ICEPush technologies and is aptly named ICEPush add-on.

    ICEPush is a brand of technology usable with both Java and JavaScript that uses long polling in order to achieve push and as such does not need port opening (save the one the standard HTTP stream uses, of course). The ICEPush Vaadin add-on integrates ICEPush into your Vaadin application in a very simple way, so that only so much steps are needed in order to develop a full-fledged application with push features.

    Set-up ICEPush add-on

    Once you’ve created your Vaadin project (and application), add the ICEPush libraries to your project. If you use Maven, just add the following snippet to your POM:

    <dependency>
       <groupId>org.vaadin.addons</groupId>
       <artifactId>icepush</artifactId>
       <version>0.2.0</version>
    </dependency>
    <repository>
       <id>vaadin-addons</id>
       <url>http://maven.vaadin.com/vaadin-addons</url>
    </repository>
    

    If not, just download the ZIP available in the directory. Beware that all JAR inside should be copied to your WEB-INF/lib. Even though 2 of them look alike, one is the ICEPush JAR, the other the integration layer on Vaadin.

    Note: if you use the Vaadin plugin with your IDE, and it asks you to recompile your widgetset, just click yes and be done with it.

    Use the right servlet

    Replace the default servlet configured in your web.xml (probably com.vaadin.terminal.gwt.server.ApplicationServlet) with org.vaadin.artur.icepush.ICEPushServlet.

    Add the ICEPush object to your window

    In order to use push technology, you’ll have to add a new ICEPush object to the window in use, like so:

    public class PushApplication extends Application {
    
      private ICEPush push = new ICEPush();
    
      @Override
      public void init() {
        Window mainWindow = new Window("Push Application Example");
        mainWindow.addComponent(push);
      }
    }
    
    

    Now, each time you nee to update the window, just call push.push() and it’s done!

    This method call will update the client’s window with the update you made. Vaadin will do true AJAX in that it won’t reload the page, just update the view with the changes.

    As usual, you’ll find the source of this article here, in Eclipse format.

    To go further:

    Categories: JavaEE Tags: vaadin
  • Chicken and egg problem with Spring and Vaadin

    The more I dive into Vaadin, the more I love it: isolation from dirty plumbing, rich components, integration with portlets, Vaadin has it all.

    Anyway, the more you explore a technology, the bigger the chances you fall down the proverbial rabbit hole. I found one just yesterday and came up with a solution. The problem is the following: in Vaadin, application objects are tied to the session. Since I’m a Spring fanboy, it does make sense to use Spring to wire all my dependencies. As such, I scoped all application-related beans (application, windows, buttons, resources, …) with session like so:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
      <context:annotation-config />
      <bean id="application" scope="session">
      <aop:scoped-proxy />
    ...
    </beans>
    

    This works nicely, until you happen to use DI to wire further. By wire further, I mean wiring windows into application, button into windows and then resources (icons) into buttons. It is the last  step that cause a circular dependency. Icon resources are implemented in Vaadin by com.vaadin.terminal.ClassResource. This class has two constructors that both needs an application instance.

    The dependency cycle is thus: application -> window -> button -> resource -> application. Spring don’t like it and protests energically to it by throwing an exception which is labeled like so Requested bean is currently in creation: Is there an unresolvable circular reference?

    I think, in this case, that the design of the ClassResource is not adapted. That’s whyI designed a class aligned with Spring deferred instantiation: since the application is session-scoped, Spring uses a proxy that defers instantation from application start (Spring normal behaviour) to session use. The point is to implement the ApplicationResource interface, which needs an interface, but to set application only when needed:

    public class DeferredClassResource implements ApplicationResource {
    
      private static final long serialVersionUID = 1L;
    
      private int bufferSize = 0;
      private long cacheTime = DEFAULT_CACHETIME;
      private Class<?> associatedClass;
      private final String resourceName;
      private Application application;
    
      public DeferredClassResource(String resourceName) {
        if (resourceName == null) {
          throw new IllegalArgumentException("Resource name cannot be null");
        }
        this.resourceName = resourceName;
      }
    
      public DeferredClassResource(Class<?> associatedClass, String resourceName) {
        this(resourceName);
        if (associatedClass == null) {
          throw new IllegalArgumentException("Associated class cannot be null");
        }
        this.associatedClass = associatedClass;
      }
    
    ... // standard getters
    
      @Override
      public String getFilename() {
        int index = 0;
        int next = 0;
        while ((next = resourceName.indexOf('/', index)) > 0
          && next + 1 < resourceName.length()) {
          index = next + 1;
        }
        return resourceName.substring(index);
      }
    
      @Override
      public DownloadStream getStream() {
        final DownloadStream ds = new DownloadStream(associatedClass
          .getResourceAsStream(resourceName), getMIMEType(),
          getFilename());
        ds.setBufferSize(getBufferSize());
        ds.setCacheTime(cacheTime);
        return ds;
      }
    
      @Override
      public String getMIMEType() {
        return FileTypeResolver.getMIMEType(resourceName);
      }
    
      public void setApplication(Application application) {
        if (this.application == application) {
          return;
        }
        if (this.application != null) {
          throw new IllegalStateException("Application is already set for this resource");
        }
        this.application = application;
        associatedClass = application.getClass();
        application.addResource(this);
      }
    }
    

    DeferredClassResource is just a copy of ClassResource, but with adaptations that let the application be set later, not only in constructors. My problem is solved, I just need to let application know my resources so it can call setApplication(this) in a @PostConstruct annotated method.

    Categories: JavaEE Tags: springvaadin
  • Vaadin Spring integration

    I lately became interested in Vaadin, another web framework but where everything is done on the server side: no need for developers to learn HTML, CSS nor JavaScript. Since Vaadin adress my remarks about web applications being to expensive because of a constant need of well-rounded developers, I dug a little deeper: it will probably be the subject of another post.

    Anyway, i became a little disappointed when I wanted to use my favourite Dependency Injection framework, namely Spring, in Vaadin. After a little Google research, I found the Vaadin Wiki and more precisely the page talking about Vaadin Spring Integration. It exposes two ways to integrate Spring in Vaadin.

    The first one uses the Helper “pattern”, a class with static method that has access to the Spring application context. IMHO, those Helper classes should be forgotten now we have DI since they completely defeat its purpose. If you need to explicitly call the Helper static method in order to get the bean, where’s the Inversion of Control?

    The second solution uses Spring proprietary annotation @Autowired in order to use DI. Since IoC is all about decoupling, I’m vehemently opposed to coupling my code to the Spring framework.

    Since neither option seemed viable to me, let me present you the one I imagined: it is very simple and consists of subclassing the Vaadin’s AbstractApplicationServlet and using it instead of the classical ApplicationServlet.

    public class SpringVaadinServlet extends AbstractApplicationServlet {
    
      /** Class serial version unique identifier. */
      private static final long serialVersionUID = 1L;
    
      private Class clazz;
    
      @Override
      public void init(ServletConfig config) throws ServletException {
        super.init(config);
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(
          config.getServletContext());
        Application application = (Application) wac.getBean("application", Application.class);
        clazz = application.getClass();
     }
    
      /**
      * Gets the application from the Spring context.
      *
      * @return The Spring bean named 'application'
      */
      @Override
      protected Application getNewApplication(HttpServletRequest request)
        throws ServletException {
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(
          request.getSession().getServletContext());
        return (Application) wac.getBean("application", Application.class);
      }
    
      /**
      * @see com.vaadin.terminal.gwt.server.AbstractApplicationServlet#getApplicationClass()
      */
      @Override
      protected Class getApplicationClass()
      throws ClassNotFoundException {
        return clazz;
      }
    }
    

    This solution is concise and elegant (according to me). Its only drawback is that it couples the servlet to Spring. But a class-localized coupling is of no consequesence and perfectly acceptable. Morevoer, this lets you use Spring autowiring mechanism, JSR 250 autowiring or plain old XML explicit wiring.

    Categories: JavaEE Tags: springvaadin