Archive

Posts Tagged ‘vaadin’

Feedback on customizing Vaadin HTML template

March 28th, 2016 No comments

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:

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:

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

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:

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.

Send to Kindle
Categories: JavaEE Tags: ,

Customizing Vaadin HTML template

March 20th, 2016 2 comments

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 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 morevaadin.com. 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.

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
  2. UnsupportedBrowserHandler: returns a specific message if the browser is not supported by Vaadin
  3. UidlRequestHandler: handles RPC communication between client and server
  4. FileUploadHandler: handles file uploads achieved with the FileUpload component
  5. HeartbeatHandler: handles heartbeat requests
  6. PublishedFileHandler
  7. 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 :

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 class makes it very clear that it’s quite hard to extend. Besides, it delegates HTML generation to the JSoup 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?
  2. Rewrite a large portion of the BootstrapHandler and add it before the BootstrapHandler in the handlers sequence
  3. Be lazy and apply Ockham’s razor: just use a simple AOP‘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.

@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!

Send to Kindle
Categories: JavaEE Tags: ,

Playing with Spring Boot, Vaadin and Kotlin

January 10th, 2016 1 comment

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): Presenter<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.

Send to Kindle
Categories: JavaEE Tags: , ,

My case for Event Bus

October 18th, 2015 5 comments

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)). 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.

Send to Kindle

Improving the Vaadin 4 Spring project with a simpler MVP

January 18th, 2015 5 comments

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 {

    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!

Send to Kindle
Categories: JavaEE Tags: , ,

From Vaadin to Docker, a novice’s journey

November 23rd, 2014 2 comments

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//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 

# 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
Send to Kindle
Categories: Development Tags: ,

Vaadin and Spring integration through JavaConfig

March 9th, 2014 No comments

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.

Send to Kindle
Categories: JavaEE Tags: , ,

Learning Vaadin 7 is out!

September 29th, 2013 No comments

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.

Send to Kindle
Categories: Java Tags: ,

Devoxx France 2013 – Day 1

March 28th, 2013 No comments

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:

Yout name: 
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:

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!)
Send to Kindle
Categories: Event Tags: , , ,

Announcing More Vaadin

February 12th, 2012 3 comments

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:

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 🙂

Send to Kindle
Categories: Java Tags: