10 days ago

## Back to Base (make SQL great again)

I have to admit upfront that my brain is somehow incompatible with JPA. Every time I try to use JPA, I will somehow wind up fighting weird issues, be it LazyInitializationException with Hibernate, or weird sequence generator preallocation issues with EclipseLink. I don't know what to use merge() for; I lack the mean to reattach a bean and overwrite its values from the database. I don't want to bore you to death with all of the nitty-gritty details; all the reasons are summed in Issue #3 Remove JPA. I think that the number 1 reason of why JPA is incompatible with me is that

JPA is built around the idea that the Java classes, not the database, is the source of truth.

My way of thinking is the other way around: I think that the database (and not the JPA) is the source of truth. This way of thinking is however incompatible with the very core of the JPA technology and makes it impossible to use JPA for me.

### The Source Of Truth

To allow Java beans to be the source of truth, JPA defines certain techniques and requires Hibernate to sync Java beans with the database behind the scenes. That is unfortunately a non-trivial issue which cannot be done automatically in certain cases, and that's why JPA abstraction suffers from the following issues:

• Hibernate must track changes done to the bean, in order to sync them to the underlying database. That is done by intercepting all calls to setters, which can only be done by runtime class enhancement (for every entity Hibernate creates a class which extends that entity, overrides all setters and injects some Hibernate core class which is notified of changes). Such class can hardly be called a POJO since passing that class around will start throwing LazyInitializationException like hell. That is the black magic, pure and evil.
• It intentionally lacks the method to reattach a bean and overwrite its contents with the database contents - this goes against the idea of having Java class the source of truth.
• By abstracting joins into Collections, it causes the programmers to unintentionally write code which suffers from the 1+N loading issues.

Since I'm very bullheaded, instead of trying to attune my mind towards JPA I explored the different approach: let's step back and make the database the source of truth again.

### Database As The Source Of Truth

Having Database as the source of truth means that the data in your bean may be obsolete the moment it leaves the database (since there might be somebody else already modifying that thing). The optimistic/pessimistic locking is the way around that, and to have the most recent data you will need to requery from the database.

The bean can now ditch all of its sync capabilities and become just a snapshot: a sample of the state of the database row at some particular time. Changes to the bean properties will no longer be propagated automatically to the database, but need to be done explicitly by the developer. The developer is once again in charge.

There - I have solved the whole detached/managed/lazy initialization exception nonsense for you :-)

The beans are once again POJOs with getters and setters, simply populated from the database by reading the data from the JDBC ResultSet and calling bean's setters.

That can be achieved by a simple reflection. Moreover, no runtime enhancement is needed since the bean will never track changes; to save changes we will need to issue the INSERT statement. Very important thought: since there's no runtime enhancement, the bean is really a POJO and can be actually made serializable and passed around in the app freely; you don't need DTOs anymore.

### The Vaadin-on-Kotlin Persistency Layer: vok-db

There is a very handy library called Sql2o which maps JDBC ResultSet to Java POJOs. This idea forms the very core of vok-db. To explain the data retrieving capabilities of the vok-db library, let's begin by implementing a simple function which finds a bean by its ID.

#### vok-db: Data Retrieval From Scratch

The findById() function will simply issue a select SQL statement which selects a single row, then passes it to Sql2o to populate the bean with the contents of that row:

The function is rather simple: it is actually nothing more but a simple Kotlin reimplementation of the very first "Execute, fetch and map" example in the Sql2o home page. The Sql2o API will do nothing more but create a JDBC PreparedStatement, run it, create instances of clazz using the zero-arg constructor, populate the bean with data and return the first one. Using this approach it is easy to implement more of the finders, such as findAll(clazz: Class<T>), findBySQL(clazz: Class<T>, where: String). However, let's focus on the findById() for now.

To obtain the Sql2o's Connection (which is a wrapper of JDBC's connection), we simply poll the HikariCP connection pool and use the db{} method to start+commit the transaction for us. This will allow us to retrieve beans from the database easily, simply by calling the following statement from anywhere of your code, be it a background thread, or a Vaadin button click listener:

This is nice, but we can do better. In the dependency injection world, for every bean there is a Repository or DAO class which defines such finder methods and fetches instances of that particular bean. However, we have no DI and therefore we do not have to have a separate class injected somewhere, just for the purpose of accessing a database. We are free to attach those finders right where they belong: as factory methods of the Person class:

This will allow us to write the finder code even more concise:

Yet, adding those pesky findById() (and all other finder methods such as findAll()) manually to every bean is quite a tedious process. Is there perhaps some easier, more automatized way to add those methods to every bean? Yes there is, by the means of mixins and companion objects.

As a first attempt, we will define a Dao interface as follows:

Remember that the companion object is just a regular object, and as such it can implement interfaces?

This allows us to call the finder method as follows:

Not bad, but the Person::class.java is somewhat redundant. Is there a way to force Kotlin to fill it for us? Yes, by the means of extension methods and reified type parameters:

Now the finder code is perfect:

vok-db follows this idea and provides the Dao interface for you, along with several of utility methods for your convenience. By the means of extension methods, you can define your own global finder methods, or you can simply attach finder methods to your beans as you see fit.

You can even define an extension property on Dao which produces Vaadin's DataProvider, fetching all instances of that particular bean. Luckily, you don't have to do that since vok-db already provides one for you.

Next up, data modification.

#### vok-db: Data Modification

Unfortunately Sql2o doesn't support persisting of the data, so we will have to do that ourselves. Luckily, it's very simple: all we need to do is to generate a proper insert or update SQL statement:

Simply by having your beans implement the Entity interface, you will gain the ability to save and/or create database rows:

Pure simplicity:

about 1 month ago

## Try out TeamCity quickly with Docker

Teamcity is quite a nice continuous integration server from Jetbrains. The set up is not that easy though since you typically need to install the TeamCity server itself, and at least one agent which will perform the building itself.

Luckily, with Docker, you can set up TeamCity very easily on any PC, without the fuss of installing the server and the agent. The following docker-compose.yml configuration file will direct Docker to download appropriate images both for TC server and for TC agent and run them. Create a folder named teamcity and drop the docker-compose.yml file in there:

Then, create the following folders inside of the teamcity folder which will store both the server and the agent persistent folders:

Now just start the containers with:

Now you can direct your browser to http://localhost:8111 and configure TC to use the embedded database; then just head to agents and authorize the teamcity-agent so that TC server will trust it and will run the builds there.

### Building Android APKs with TeamCity

Building an Android app requires the Android SDK to be preinstalled in the Agent itself. That can be done quite easily - we will extend the teamcity-agent docker image and add the SDK on top of that. In the teamcity folder above, create a folder named agent-android-docker and put the following Dockerfile there:

You will also need the packages.txt along the Dockerfile itself, with the following contents:

Then, download the Android SDK Tools for Linux (Not the whole Studio, just the SDK Tools; the download links are at the bottom of the page). As of the writing of this article, the direct link to the SDK Tools is this: https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip . Unpack the zip file to agent-android-docker/sdk, so that the contents of the sdk folder contain the folder tools.

To use this new Agent Image, we will simply direct the Docker Compose to build it - just modify the docker-compose.yml file and change it as follows:

Done - just run docker-compose up.

3 months ago

## Vaadin and Kotlin Coroutines

When Kotlin 1.1 brought in Coroutines, at first I wasn't impressed. I thought coroutines to be just a bit more lightweight threads: a lighter version of the OS threads we already have, perhaps easier on memory and a bit lighter on the CPU. Of course, this alone can actually make a ground-breaking difference: for example, Docker is just a light version of a VM, but it's quite a difference. It's just that I failed to see the consequences of this ground-breaking difference; also, performance-wise in Vaadin apps, it seems that there is little need to switch away from threads (read Are Threads Obsolete With Vaadin Apps? for more info).

So, is there something else to Coroutines with respect to Vaadin? The answer is yes.

### What are Coroutines?

Coroutine is a block of code that looks just like a regular block of code. The main difference is that you can pause (suspend) that block by calling a special function; later on you can direct the code to continue the execution; the function will simply end and the calling code resumes execution. This is achieved by compiler magic and thus no support from JVM/OS is necessary. The Informal Kotlin Coroutines introduction offers great in-depth explanation. Even better is Roman Elizarov's Coroutine Video - the most clear explanation of Coroutines that I've seen (here is the part 2: Deep Dive into Coroutines on JVM).

There are the following problems with Coroutines:

• the compiler magic (a nasty state machine is produced underneath);
• the block looks like just a regular synchronous code, but suddenly out of nowhere completely another thread may continue the execution (after the coroutine is resumed). That's not something we can easily attune our mental model to.
• They're not easy to grok.

Just disadvantages, what the hell? I can do pausing with threads already, simply by calling wait() or locks or semaphores etc; so what's the big fuss? The important difference is that at the suspension point, the coroutine detaches from the thread - it saves its call stack, the state of the variables and bails out, allowing the thread to do something else, or even terminate. When the coroutine is resumed later on, it can pick any thread to restore the stack+state in, and continue execution. Aha! Now this is something we can't do with threads.

### The Blocking Dialogs

The coroutines suspend at suspension functions, and we can resume them as we see fit, say, from a button click handler. Consider the following Vaadin click handler:

This can't be done with the regular approach since we can't have blocking dialogs with Vaadin. The problem here is as follows: assume that confirmDialog() function blocks the Vaadin UI thread to wait for the user to click the "Yes" or "No" button. However, in order for the dialog to be actually drawn in the browser, the Vaadin UI thread must finish and produce response for the browser. But Vaadin UI thread can't finish since it's blocked in the confirmDialog function.

However, consider the following suspend function:

When the dialog's Yes or No button is clicked, the block is called with response of true (or false, respectively), which resumes the continuation, and with it, the calling block.

This allows us to write the following code in the button's click handler:

The launch method slates the coroutine to be run later (via the UI.access() call). The click handler does not wait for the coroutine to run but terminates immediately, hence it does not block. Since the listener is now finished and there is no other UI code to run, Vaadin will now run UI.access()-scheduled things, including our coroutine (coroutine is the block after the launch method).

The coroutine will create the confirm dialog and will suspend (and detach from the UI thread). That allows the UI thread to finish and draw the dialog in the browser. Later on, when the "Yes" button is clicked, the coroutine is resumed in the UI thread. It will close the dialog (the code is left out for brevity), deletes the entity and finishes the coroutine and the UI thread as well, allowing the dialog close to be propagated towards the browser.

And alas, with the help of compiler magic, we now have blocking dialogs in Vaadin. Of course those dialogs are not really blocking - that still can not be done. What the compiler actually does is that it will break the coroutine code into two parts:

• the first part creates the dialog and exits;
• the second one runs on button click, closes the dialog and deletes the entity.

The compiler will convert our nice block into a nasty state automaton class. However, the illusion in the source code is perfect.

### Further Down The Rabbit Hole

The above coroutine is rather simple - there are no cycles, try/catch blocks, and only a simple if statement. I wonder if the illusion will hold with a more complex code. Let's explore further.

We will create a simple movie tickets ordering page. The workflow is as follows:

1. we will first check whether there are tickets available; if yes then
2. we'll ask the user for confirmation on purchase;
3. if the user confirms, we make the purchase.

We will access a very simple dummy REST service for the query and for purchase; the app will also provide server-side implementations for these dummy services, for simplicity reasons. Since those REST calls can take a while, we will display a progress dialog for the duration of those requests.

Let's pause briefly and visualize the code using the old, callback approach. We can block safely in the UI thread during the duration of those REST calls, but then we can't display the progress dialog: it's the same situation as with the blocking confirmation dialog above. Hence we need to run that REST request in the background, end the UI request code, and resume when the REST request is done. Lots of REST clients allow async callbacks - for example Retrofit2 (which is usuually my framework of choice). Unfortunately Retrofit2's dark secret is that it blocks a thread until the data is retrieved. With NIO2 we can do better, hence we'll use Async Http Client. In pseudo-code, the algorithm would look like this:

Behold, the Pyramid of Doom. And that's just the happy flow - now we need to add error handling on every call, and also make the whole thing cancelable - if the user cancels and navigates to another View, we need to clean up those dialogs. Brrr.

Luckily we have Coroutines, and hence we can rewrite the purchaseTickets() like this:

Looks sequential, easy to read, easy to understand, but it has full power of error handling and cancelation handling:

• Error handling - we simply throw an exception as we would in a sequential code, and the kotlin-produced state machine will take care that it is propagated properly through try{}catch blocks and out of the coroutine. There, our Vaadin integration layer will catch the exception and will call the standard Vaadin error handler.
• Cancelation: the confirmDialog() function simply tells the continuation to close the dialog when the coroutine is completed (both successfully, exceptionally or canceled). The withProgressDialog() is even simpler - it will simply use try{}finally to hide the dialog; coroutine will then call the finally part even when canceled.

Coroutines allowed us to do amazing things here: we were able to use the sequential programming approach which produced readable/debuggable code, which is at the same time highly asynchronous and highly performant. I personally love that I am not forced to use Rx/Promise's thenCompose, thenAccept and all of that functional programming crap - we can simply use the built-in language constructs as if, try{}catch again.

The whole example project is at github: Vaadin Coroutines Demo - visit the page for more instructions on how to run the project for yourself and open it in your IDE. It's very simple.

You can try out the cancelation for yourself: normally it should be hooked on View's detach() which is called when navigating away, but it's easier to play around when you have a button for that (the "Cancel Purchase" button in the example app).

### Further Ideas

Your application may need to access a relational database instead of making REST calls, to fetch the data. JDBC drivers only allows blocking access mode - that's fine since it's fine to block in JVM with Vaadin. Yet, there are fully async database drivers (for example for MySQL and PostgreSQL there are drivers on Github), so feel free to go ahead and use them with Continuations.

Unfortunately, we can't use async approach with Vaadin's Grid's DataProvider. This is because the DataProvider API is not asynchronous: the nature of the API requires us to compute the data and return it in the request itself. However, that's completely fine since it's OK to block in JVM.

Of course you can implement even more longer running processes. Perhaps it might be possible to save the state of a suspended coroutine to, say, a database. That would allow us to develop and run long-running business processes in your app, in a really simple way, with the full power of the Kotlin programming language. The possibilities are interesting.

3 months ago

## Are Threads Obsolete With Vaadin Apps?

Let me start by saying that threading model (or, rather, single thread model) provides the most simplistic programming paradigm - the imperative synchronous sequential programming. It is easy to see what the code is doing, it is easy to debug, and it is easy to reason about (unless you throw in dynamic proxies, injected interfaces with runtime implementation lookup strategy and other "goodies" of the DI) - that's why having such paradigm is generally desirable. Of course that holds only when you have one thread. Adding threads with no defined communication restrictions overthrows this simplicity and creates the most complex programming paradigm.

A new async hype of using Rx/Promises/Actors/whatever is high right now. node.js guys preach the new, event-based model to be superior to the current threading model. This marketing makes sense since they only have one thread (or, rather, one event queue), thus they can't do otherwise. However, compared to the simplicity of the single thread model, any code using async techniques will be order of magnitude harder to understand and debug:

• callback-based programming introduces Callback Hell/Pyramid of Doom; implementing error-handling on top of that turns the pyramid into unmaintainable mess.
• Rx/Promises introduces combinators such as thenCompose, thenAccept and others. While native to functional programming, it is quite foreign to imperative programming style and introduces a completely new programming vocabulary instead of reusing language constructs such as if, try{}catch etc. This vocabulary also tend to differ from library to library; also the API-to-code ratio is quite high and creates high verbosity (Java programmers could tell stories ;)
• Misusing Actors to create complex app tends to create a mesh of messages which is impossible to debug or reason about; any bug is hard to spot, reason about its origin and fix.

True, these techniques do offer a programming paradigm which is easier to use than "here, have multiple threads and do whatever you like" - that's a ticket to hell (unless you use 1-master-n-slave threads paradigm). But they produce code far more complex than the single thread model does.

### Simplicity Is Discarded Too Easily

With Vaadin, you only have one thread per session (or user). Since sessions are generally independent and do not tend to communicate, with Vaadin you effectively have one thread where you do things synchronously - update the UI, fetch stuff from REST/database synchronously, update the UI some more and return. That is the most simple programming paradigm you can get. Moving to Rx/Promises/Actors for whatever reasons will make your program more complex by an order of magnitude.

Unfortunately, simplicity is typically discarded too easily since it only creates indirect costs: the development is slower since the code is way more complex and harder to modify/add features to, there are more bugs so the maintenance is slower. When simplicity is discarded, the result is typically a big ball of mud nobody dares to refactor.

You don't want to go there. Make it work correctly; only then make it work fast. Don't include Rx in your project solely as an excuse to learn something new.

### Debunking Arguments Against Threads

Typically there is the performance argument against threads: the threads are too heavyweight, and JVM can only create 3000 native threads anyway before something horrible happens, hence we must pursue alternatives. But that is simply not true, at least for a typical Vaadin app.

Vanilla OpenJDK on my Ubuntu Linux can create 12000 threads just fine, before failing to create additional thread with OutOfMemoryError. But that's only because there is a systemd hard limit on user process number which is around 12288; lifting that limit will allow JVM to create 33000 threads (in 4 seconds, so quite fast) before failing. To go even further, we need to increase the available heap size, or decrease stack size, fiddle with Linux ulimits etc. It's doable, and it is worth the preserved simplicity. And we don't even need that many threads after all.

According to the Vaadin scalability study, Vaadin supports up to 10000 concurrent users on one machine. That's 10000 native threads which JVM and the OS can perfectly handle. Typically your page will go nowhere that limit. You're not Google nor Facebook, and thus you don't need to employ complex techniques those guys need to employ. Start small, start simple; when the page grows, the business catches up, the idea is validated and your budget increases, only then you can fiddle with performance.

Regarding native threads performance: Ruby had green threads but they moved to native threads; Python had native threads from the start. Well, to be honest they still have GIL so they can still use but one CPU core, but the point is that those guys considered OS threads lightweight enough so that they started to use them.

As the time passed and JVM got more optimized:

• Intra-process context switching became more cheap
• locks on JVM are now based on CAS and thus very cheap
• JVM can ramp up 30000 threads in 3-5 seconds on my laptop without any issues
• 10000 threads with default stack trace of 512k will consume 5GB of memory; that could be handled by the virtual memory OS subsystem - if I don't use Spring/JavaEE/other huge stack generators then the stack is typically nearly empty and can be left unallocated/swapped out
• Majority of threads typically sleep/are parked, and thus they are not eligible for preemptive multitasking/context switching and thus generate no observable CPU overhead
• The overhead is mostly memory upkeep for stack and some thread metadata.

Therefore, using the threaded imperative model with Vaadin is completely fine and will create no obvious bottlenecks.

### Conclusion

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

I suggest you start simple unless it's absolutely clear that it won't suffice anymore; only then employ more complex techniques. Also, if you're not a functional paradigm guy, don't hop on the Rx/Promises bandwagon - use Kotlin's Coroutines since they produce code that's vastly simpler and superior.

3 months ago

## Move Your Code Together

Nicolas Frankel put some of my feelings into an excellent article Is Object-Oriented Programming compatible with an enteprise context?. During the development of Aedict Online (still as a Java-based JavaEE/JPA app back then, now it's Vaadin-on-Kotlin-based), when trying to find rows from JPA+DB I often tried to find the necessary functionality on the JPA entity itself. Wouldn't it be great if, upon user's log in, we could find the user and verify his password using the following code?

Unfortunately, I was not able to implement the User.findByUsername static method properly on JavaEE. I was forced by JavaEE to move such finders to an enterprise bean, because that was the only way to have transactions and the EntityManager. All my attempts to create such finders from JPA Entity static method failed:

• The DI engine makes it impossible to look up beans from a static method
• Creating a singleton bean with all things injected, providing them from a static context is a pattern discouraged in the DI world.

Eventually I realized that it was the DI itself who directly forbade me to group the code in a logical way, finders (they are in fact factory methods!) together with the Entity itself. I believe that the need to keep the common functionality together is one of the core concepts in pragmatic OOP, and I felt that DI was violating this. As the time passed I got so frustrated that I no longer could see the merits of the DI technology itself. After realizing this I hesitantly rejected the DI approach and tried to prototype a different approach.

I was learning Kotlin back then and I have just learned of global functions with blocks. What if those things could to the transaction for me, outside of EJB context? Such heresy, working with a database just like that! The idea is descibed here, but the gist is that it's dead easy to write a function which runs given block in a transaction, creates an EntityManager and provides it: the db method.

With that arsenal at hand, I was able to simply write this code:

It was that easy. I added a HikariCP connection pooling on top of that and I felt ... betrayed. The Dependency Injection propaganda crumbled and I saw DI standing naked, a monstrosity of dynamic proxies and enormous stack traces, bringing no value but obfuscating things, making things very complex and forcing me to split code in a way that I perceived unnatural (and anti-OOP). By moving away from DI I was expecting a great loss of functionality; I expected that I would have to tie things together painfully. Everybody uses DI so it's right to do so, right?

Instead, the DI-less code worked just like that - there was no need to inject lookup service into my JPA entity as Nicholas had to do, I did not had to resort to use Aspect Weaving or whatever clever technique my tired brain refused to comprehend. Things were simple again. I've embraced the essence of simplicity. Nice poem. Back to earth, Apollo.

I started to use static finders and loved them ever since. Later on I have created a simple Dao which allowed me to just define the User class as follows:

And the Dao would bring in useful static methods such as findAll(), count() etc, and the Entity would bring in instance methods such as save(), delete(), which allowed me to write code such as this:

Ultimately I ditched the JPA crap away and embraced Sql2o with CRUD additions. You can find this approach being used in the Beverage Buddy Vaadin 10 Sample App, along with other goodies, such as:

By throwing the DI away, I no longer had to run the container with Spring Maven plugin or fiddle with Arquillian since I could just run the code as it was, from a simple JUnit tests: Server-side Web testing.

But that's story for another day.

4 months ago

## Vaadin 10 Flow with Kotlin

It is indeed possible to write Vaadin 10 Flow apps in Kotlin. Here are a couple of resources to get you started:

• Two introductionary videos, 40 minutes total running time, which explains the ideas behind Vaadin 10 Flow and behind the Vaadin-on-Kotlin framework itself:

Those videos will also help you to download and start with the very simple skeleton application.

• The skeleton application which contains everything necessary to build the app and launch it, and it only introduces a very simple UI: a button and a text field. You can find all the necessary information here: karibu10-helloworld-application
• A more polished application which shows additional components and also demonstrates the ability to connect to a Polymer Template: the Beverage Buddy application. It has no database access support and only serves in-memory dummy data. It is a part of the Karibu DSL framework; instructions to get it and launch it: Beverage Buddy.
• The same Beverage Buddy application as above, but uses an embedded full-blown H2 SQL database and is based on the Vaadin-on-Kotlin framework: Beverage Buddy.

Please feel free to post any questions at the Vaadin Forums.

4 months ago

## Serverless web testing

Traditionally, the testing of a web portal is done from the browser, by a tool which typically using Selenium under the hood. This type of testing is closest to the user experience - it tests the web page itself. Unfortunately, it has several major drawbacks:

• It is slow as hell. A typical Selenium test case takes at least 5-10 seconds to complete, depending on the complexity of the test.
• Unreliable - the integration with Firefox breaks on every Firefox update; sometimes Selenium itself fails or timeouts randomly.
• Either requires proper IDs, or you have to use CSS/XPath selectors which are very flaky, tend to break on web portal upgrades and tend to grow to absurd lengths, making them maintainability nightmare.

Luckily with Vaadin, being a component-oriented framework, we can do better. How about we stopped testing the Browser, the client-server transport layer and the server-side http parsing code and started to test the app logic directly? Vaadin - being a server-oriented framework - holds all of the component information and hierarchy server-side after all.

By bypassing the browser and running tests "server-side", with all of the business logic directly accessible on classpath from JUnit tests, we gain:

• Speed. Server-side tests are typically 100x faster than Selenium and run in ~60 milliseconds.
• Reliable. We don't need arbitrary sleeps since we're server-side and we can hook into data fetching.
• Run headless since there's no browser.
• Can be run after every commit since they're fast.
• You don't even need to start the web server itself since we're bypassing the http parsing altogether!

Yeah, we can't test CSS with those, but we can now test all the nitty-gritty form validation paths which were just too painful and slow to test with Selenium; that leaves Selenium just for testing the happy paths. This follows the concept of the Test Pyramid:

• Most tests are quickly running simple JUnit tests which test individual classes
• In less numbers there are server-side tests which test the business logic, a basic integration and the "dark corners" of the UI rarely triggered by the user (e.g. validation, crappy user input etc). These tests are able to test surprisingly large coverage of the app.
• That leaves Selenium just tests few happy flows and the overall system integration.

### How to do that

Now if you use Vaadin, there is an alternative to this. Typically what we want is to test our business logic, which resides server-side. Typically the server-side logic is triggered by an user action: the user clicks a button in a browser, which runs the client-side code to rely a RPC to server-side, where Vaadin will run all attached click listeners, which will then execute our logic.

How about we removed the user, the client-side and the RPC from the equation? Certainly we can "click" the button (read run the click listeners) server-side, using just the Vaadin Button API. Certainly we can run a JUnit test which calls button.click(), given that the environment is sufficiently prepared.

As it turns out, it is rather easy to prepare the environment. All that's needed is:

• We need to create VaadinSession and set it as current, so that the UI code can rely that there is a session.
• We need to create the UI and set it as current,
• And we need to obtain Vaadin UI lock, purely because the Vaadin Framework server-side code contains countless asserts that the lock is held.

Once that's done we can simply create Vaadin components and UIs directly from the JUnit tests as follows:

(the MockVaadin.setup() just creates VaadinServletService, VaadinSession and creates Vaadin UI, which provides enough environment for Vaadin components to work happily).

Well this test is not really useful. We need to test our app instead of the Vaadin Button, right? For a really simple app with no navigator we need to:

• Instantiate our UI since that creates our app's UI,
• Find components and interact with them - e.g. press the "Login" button etc.

Luckily, lot of this is provided by the Karibu-Testing library. You can see the library in action in Karibu Helloworld Application. When you build the app using ./gradlew, all tests (including the UI ones) will run automatically. The UI test is just a simple class:

The mockVaadin() function sets up the test environment and instantiates our UI; now we're ready to test!

The simpleUITest() is the main meat. The test method runs with Vaadin UI lock acquired and thus we can access the Vaadin components directly. The _get method is provided by Karibu-Testing and serves for component finding: the _get<TextField>(caption = "Type your name here:") invocation finds the one text fields with given caption in the current UI; if there are none or multiple of those the function fails.

The _click() method on a Button is really useful since it asserts that the button is actually visible, enabled and not read-only and thus can be interacted with; if all of this is satisfied then the button is actually clicked, which invokes the click listeners etc etc.

All that's left is to assert the state of the application - we can assert that a Label has been added and it has a proper contents.

Note that no web server is launched, not even an embedded Jetty - it's unnecessary. This makes the test run very fast and really simple to debug - just try to place a breakpoint into the "Click Me" button click handler and try debugging the test from your IDE.

### A more complex example

With more complex apps which sport the navigator pattern, we moreover need to:

• Instantiate our UI since that creates our app's general outlook,
• Navigate to the view under testing since that populates the page with components,
• Auto-discover all of @AutoView views so that the navigator will work properly.
• Mock our app initialization (since we will have no server and those ContextListeners won't be run automatically)

Since we don't use Spring nor JavaEE components, we don't have to painfully start/stop those fat environments. And since we don't need the web server either, we are still able to write just a basic JUnit tests as follows:

This tests a fairly complex functionality of the Vaadin-on-Kotlin example CRUD app, namely the ability to edit a person. Let's break it down into individual pieces:

• the bootstrapApp() will use the Karibu-Testing built-in autoDiscoverViews() method to find and register all @AutoViews; then it will simply call the WAR bootstrap which will initialize Vaadin-on-Kotlin and run the migrations.
• The teardownApp() will call the WAR teardown which will close the database connection pool and tears down Vaadin-on-Kotlin
• The mockVaadin() will mock Vaadin environment exactly as in the earlier simple example. It will also instantiate our MyUI which sets up the Navigator and creates the page UI.
• Since the database is initialized and ready, we can use it freely; thus we can for example remove all persons in the cleanupDb() method. The Person itself is just a Sql2o entity; by the means of Dao<Person> it gains the extension methods such as deleteAll() and other DAO methods. To learn more about this neat-and-simple database access, just watch the Vaadin-on-Kotlin Part 2 Video.
• The bulk of the test is located in the testEdit() method which shows the person list, then clicks the "Edit" button on the first person, changes the name in the opened dialog and hits the Save button. Then we can assert the state of the database that the person has indeed been updated.

You can see the test itself here: CrudTestView.kt; you can run the app for yourself simply by typing this into your terminal:

You can find more information at Vaadin on Kotlin Example Project; for more information on Vaadin on Kotlin please visit the official Vaadin On Kotlin page. There is a short introductionary video on Youtube.

It takes 2 seconds on my machine to bootstrap JVM, load all classes, initialize everything, run both of those two tests and then clean up. Any further tests will typically take 60-120 milliseconds to complete since everything is already loaded and initialized. This is very fast as compare to launching a Spring application, not to mention launching a JavaEE application, launching a browser... Also, the whole setup is very easy, especially when compared to setting up a testbed to launch JavaEE server; just a tiny bit of magic as compared to tons of magic when using Spring.

4 months ago

## Launch your Vaadin-on-Kotlin app quickly in cloud

So you have built your first awesome VoK app - congratulations! You will probably want to launch it outside of your IDE, or even deploy it somewhere on the interwebz. Just pick up any virtual server provider with your favourite Linux distribution.

There are following options to launch your app:

### From Gradle, using the Gretty plugin

With proper configuration and build.gradle file, you can simply use the Gretty Gradle plugin to launch wars. Gretty comes pre-configured in the sample quickstarter VoK HelloWorld App, so you can grab the Gradle configuration from there:

You can configure Gretty to launch your app either in Jetty or Tomcat, please read more here: http://akhikhl.github.io/gretty-doc/Gretty-configuration.html . To launch it in cloud, just ssh to your virtual server, install openjdk 8, git clone your app to the server and run ./gradlew appRun.

### From Docker, using the Tomcat image

Really easy - just head to the folder where your my-fat-app-1.0-SNAPSHOT.war file is, and run the following line:

This command will start the Tomcat docker image and will mount your local folder with your war app into Tomcat's webapps/ folder. Your app will then run at http://localhost:8080/my-fat-app-1.0-SNAPSHOT . To run at http://localhost:8080 just rename your war to ROOT.war. To launch in your virtual server, just copy the WAR into your server, install docker and run the abovementioned command.

You can also create a Tomcat-based Docker image with your app easily. Just drop the following Dockerfile next to your war file:

Then, just run this in the directory with the Dockerfile:

Or even better, just use docker-compose.yml:

Then all you need to run is just

(--build will always rebuild the image so that you can play around with the Dockerfile; --force-recreate will delete old containers and create new ones so that Tomcat won't try to restore sessions from previous run).

### Fat jar

It is possible to package Jetty or Tomcat into the WAR itself, add a launcher class and then simply run it via java -jar your-app.war, thus making an executable WAR. You can read more about this option here: https://stackoverflow.com/questions/13333867/embed-tomcat-with-app-in-one-fat-jar . Unfortunately I have no experience in this regard.

Beware though: fat jars may not work for apps that package multiple files into the same location: for example there will be only one MANIFEST.MF. You can read about the pitfalls here: http://product.hubspot.com/blog/the-fault-in-our-jars-why-we-stopped-building-fat-jars

It is possible to embed Jetty - just check out this launcher class: https://github.com/mvysny/vaadin-on-kotlin/blob/master/vok-example-crud-jpa/src/test/kotlin/com/github/vok/example/crud/Server.kt

6 months ago

## Java Is Not Dead, Java Is Obsolete

Obsolete as in Cobol - used widely, but on a descendant trajectory. Let's ask a very simple question:

How many freshmen, when faced the question which language/web framework to learn, would pick Java (with all of its complexity) when there are countless of other languages/frameworks to pick from?

To build a full-stack web apps in Java you need to:

• learn Mother Of All Frameworks: JavaEE or Spring
• learn Mother Of All (Leaky) Abstractions: JPA
• Pay for Intellij, use Netbeans or use Eclipse (which has more controls than a freaking flight simulator, and is next to impossible to launch a WAR with - that's why now we have Spring Boot)
• Use Java which is (let's face it) a bloody chatty feature-lacking language. And because of this feature (or lack thereof) it gave birth to monstrosities like JavaEE and Spring. Java 8 has streams() and Optional, sure, but let's face it: the former is chatty and not enough, and the latter usually just produces crappy code.
• When you will eventually learn JavaEE, you will have to work with Javists (complexity-infected happy bunch) on an enterprise (read uber-complex) variation of FizzBuzzEnterpriseEdition and will start all project with including Spring, regardless of whether it is actually relevant to the project itself or not.

That's a Mount Everest-grade of steep learning curve. Why climb Mount Everest when you have Groovy on Grails, Ruby on Rails, Node.js, Python, Vaadin-on-Kotlin? Oracle dumped JavaEE (oh, donated to the community, right) but:

• It's too late, non-Java replacements are in place and widely used,
• It's no longer "the cool thing",
• I don't think Oracle really cares for JavaEE now - they sell cloud VMs now and they don't care what actually runs on those VMs.
• There is no replacement. Spring? Yeah right:

AbstractSingletonProxyFactoryBean: Convenient proxy factory bean superclass for proxy factory beans that create only singletons.

Let's face it: even though Node.js is a hype like Ruby-on-Rails was before, it is gaining momentum and redirecting new faces away from Java. Schools teach Python instead of Java. Java's stream of new programmers grows thin and old ones are retiring. And that's a recipe for extinction.

### The Next Generation of Tooling

Even if somebody would start to learn Java now, they would horribly lag with their knowledge behind people who hopped on the Java train 10 years ago. Isn't it thus better to bet on and hop on a promising (read hyped) frameworks of now, like node.js? Yes, JavaScript is horrible. It's a language with many pitfalls and horrible ==, but it's extremely popular. And to develop in Node.js, all you have to have is the node.js platform and a text editor (Atom). Compare that with the Java overwhelming ecosystem of tools, IDEs and libraries. Yes, JavaScript's rapid development produces https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f but Java Ecosystem has even longer history (e.g. you better avoid Struts, JSP, JSF etc).

### So how to save Java?

It's too late - the descent has begun and the Java language designers are running in the wrong direction. Consider Java streams: the authors of that API should shoot for simplicity of use instead of for purity of the design, and thus they managed to create a complex API which is pain to use. Use Kotlin's streams using extension methods producing plain lists for a week and you will not want to go back to Java, guaranteed.

### So how to save JDK?

So Java is obsolete, what about JDK? Is there somebody to save JDK? Well, definitely not Ceylon, since it has been dumped recently (sorry, DONATED to a scrap heap named Apache) and is effectively dead. Not Scala - it's too complex, not to mention dead. The only strongly-typed language that can save JDK is Kotlin. Yet, not to worry. JDK is used by popular dynamic languages like Groovy, JRuby, Jython, which are far from dead. So the JDK platform is alive and kicking, you just need to avoid Java and some of its ecosystem.

6 months ago

## The Fallacy of Future-proof

Or what-if-a-fucking-meteor-falls-down-and-swaps-1s-and-0s

Worst atrocities has been committed in the name of future-proof.

Hey, let's refactor this previously readable code using all design patterns we can find, so that, you know, what if somebody would want to add things in the future?

Ah, the dreaded "what if": it's easy to propose, hard to fight against, and thus the team usually gives up after several what-ifs and just nods their heads. In the better case those what-ifs are kept at the bottom of the backlog; the manager is satisfied and the code is not polluted. In the worst case they are actually implemented, twisting the code base into a spaghetti of undecypherable patterns.

The best future-proof strategy I've seen so far is to keep the code simple and understandable. If the code is simple, then any requirement is easy to integrate. You must thus strive to not to be future-proof, otherwise you will trade code readability immediately for some dubious future which may not even come. Remember: complexity kills, and it's easy to introduce complexity but hard to get rid of it.

I have just recently read parts of the Code Change book by Uncle Bob (he uses that nickname himself, so I will too). Ironically dubbed A Handbook of Agile Software Craftmanship, the book is infected with the what-if fallacy and it proposes to trade code simplicity for uncertain future. For example, the Sql class on page 147:

What's wrong with this class? Absolutely nothing! It actually looks like an EntityManager. It is simple to use, auto-completion works and offers a reasonable set of utility methods. Yet Uncle Bob claims that it violates Single Responsibility Principle and proposes the following 'solution':

Uncle Bob claims that

The code in each class becomes excruciatingly simple.

Wow, you have just fucked up the client API completely by scattering it into a bunch of undiscoverable classes, adding useless inheritance complexity, and you call that an improvement. Sure, go ahead and refactor your innard private classes as you see fit, I don't care as long as you give me the single Sql class to work with! Even more hilarious,

Equally important, when it's time to add the update statements, none of the existing classes need change!

Oh, awesome! The number of the SQL language statements has not been changed for 30 years, but let's be future-proof here because what if five completely new statements were suddenly invented?

This points out one of the tragedies of the Java world quite nicely. We have a simple problem, so let's invent a fucking framework around it which will "solve" an entire class of problems, complicating the world around in the process. The True Academic Way (tm) - I Don't Care About Usability As Long As I Have My Thesis.

### How DI Was Invented - The Ironic Version

The problem with Java 1.3: it was really dumb and tedious to do DB transactions:

Then some ingenious guy discovered that proxy interfaces could do that for us. But just having a single DB.wrap(interface) call was deemed too simple, too particular, not abstract enough and thus improper for a true academic soul, and thus a "proper" solution (read enterprise-fucking-level complicated solution) was invented by some smartass: the XML+AOP Java solution.

But there is no way to simply instantiate an interface, you need to instantiate a class implementing that interface, then remember to pass it to DB.wrap etc. This is obviously considered error-prone (because what if somebody forgets to call DB.wrap, right?) and thus it's obviously better to declare the construction chain in XML (because that's not error-prone at all). And thus we have wounded up with combining services (aka programming a pipeline of functionality) in XML.

Alas, the Dependency Injection was born, giving birth to Spring and JavaEE. All that simply because this Kotlin code:

was too much pain to write in a chatty Java 1.3, and because the thinking of Java guys is perverted with complexity.

Luckily, Oracle is dropping JavaEE, so that's one monstrosity down the drain; also Node.js without this DI nonsense (but with its own class of issues) is gaining momentum. Will we live to see a world without Spring and Java, but with Kotlin and a simple approach one day?