Saturday, May 6, 2017

Using Mapstruct with Protobuf3

Mapstruct works pretty nice for mapping protobuf3 Builders. The List get a suffix of "...List" in the Builder. As they are immutable and the adder method does not match that name I created a NamingStrategy to fix that:

Monday, March 6, 2017

Multitenancy with Hibernate, Postgres, Vaadin 8 & Kotlin

This example application uses Postgres Table Inheritance to setup a Multi-Tenant Database with separate schemas for each tenant.
It is built using Kotlin, Hibernate, Spring Boot, and Vaadin8 for the UI and includes several Selenium Tests that could be used as a starter for testing Vaadin applications.
Hibernate switches tenants with a proxied EntityManagerFactory/Datasource and has an additional TenantFilter Column to allow cross-tenant selects from the master schema.
The example app allows you to register for an account, login and has a simple user management.
There are examples for mapping Pojos to Postgres JSON Columns for Hibernate and JOOQ inside.
There is a docker postgres image included.
Run it with docker run -p5433:5432 eiswind/postgresql:9.6 to execute the Integration Tests or just to try the app.

Sunday, January 29, 2017

Migrating to Vaadin 8 (beta, continued)

Today I finished my migration of a (small) demo app to the new Vaadin 8 API.

First of all: Vaadin 8 has a compatibility layer. Everything you may have used with Vaadin  7 will still work with Vaadin 8, you just have to change some package names in your import statements. (for e.g. ui gets ui.v7) and everything will work out of the box with Vaadin 8.

But my goal was to completely remove the compatibility layer. That needed quite a bit of work, as the new DataBinding API focuses on binding bean properties. My app used the PropertySetItem in a bunch of places. To move these I created backing beans and used the new API.

binder.forField(passwordMatchField)
        .withValidator(PasswordMatchValidatorV8(passwordField))
        .bind(LostPasswordBean::passwordMatch)

This was not too hard, but there was more work to be done as I had to migrate all of my custom Validator implementations. The new Validator signature tastes better than the v7 one, but changing them introduces even more work:

class PasswordMatchValidatorV8 constructor(private val src: PasswordField) : 
    Validator<String> {

    override fun apply(value: String, ctx: ValueContext): ValidationResult {
        val pw: String = src.value        
        if (pw != value) {
            return ValidationResult.error(NO_MATCH)
        }
        return ValidationResult.ok()
    }

    companion object {
        const val NO_MATCH = "Passwords don't match"    }
}

That did make up for most of the fields. Another place where I had to change the code was the old BeanItemContainer  that I used to bind Collections to Grids etc. Here we have new API too that looks like this:

grid = Grid()
grid.addColumn{ u -> u.email }.setCaption("Username")

dataProvider = ListDataProvider(users)
grid.dataProvider = dataProvider
That's it. Took me about a day for 9 View Classes, but remember I was very slow getting used to the new binding style.

For my personal taste the new binding api is a great step forward, and it makes heavy use of SAM types. Using it with Kotlin is a breeze. It's is still far away from beeing as powerful as the good old eclipse databinding api, which is still my personal favorite when it comes to ui databindings.


Sunday, January 15, 2017

Kotlin Properties and the Vaadin 8 BeanBinder

Vaadin 8 (currently in beta) comes with a whole new DataBinding API that makes heavy use of the Java 8 Lambda Features.

Unfortunately Java has no concept of a Property, so one of the new ways to bind a Bean Property is writing something like (Taken from the documentation):

binder.bind(nameField, Person::getName, Person::setName);

Since Kotlin has a concept for a property you may want to write something like:

binder.forField(nameField)
        .bind(Person::name)


Thats possible with an extension method for the Vaadin Binder that could probably look like this:

fun <BEAN, T> Binder.BindingBuilder<BEAN, T>.bind(prop: KMutableProperty<T>) {
    this.bind(
            ValueProvider { bean: BEAN -> prop.getter.call(bean) },
            Setter { bean: BEAN, v: T -> prop.setter.call(bean, v) })
}

Have fun with Kotlin & Vaadin!




Wednesday, September 14, 2016

Hibernate JSON Types in Kotlin: A TypeCasting puzzler and generic collections

Trying to persist JSON types in Postgresql using Hibernate I came across the excellent post from Vlad Mihalcea How to map JSON objects using generic Hibernate Types.

I just wanted to have it as Kotlin code, as mostly all of my project is coded in Kotlin. So I used the Java-to-Kotlin conversion which as usual left me with some puzzlers, one of them I'd like to mention:

class JsonBinarySqlTypeDescriptor : AbstractJsonSqlTypeDescriptor() {

    override fun <X : Any> getBinder(
            javaTypeDescriptor: JavaTypeDescriptor<X>): ValueBinder<X> {

        return object : BasicBinder<X>(javaTypeDescriptor, this) {
            @Throws(SQLException::class)
            override fun doBind(
                    st: PreparedStatement,
                    value: X,
                    index: Int,
                    options: WrapperOptions) {
                st.setObject(index,
                        javaTypeDescriptor.unwrap<X>(
                                value,
                                (JsonNode::class.java as Class<X>),
                                options),
                        getSqlType())
            }

The most puzzling research was up, when it came to passing the JsonNode type to

protected abstract void doBind(PreparedStatement st, J value, ...
in BasicBinder. I had to cast it to Class<X>, it's still an unchecked conversion, but at last it works.


Ome thing I would wish I had a starting idea for is how to persist generic collections,  Let's start with passing in the TypeReference Jackson needs as a Hibernate Type Parameter (String only...)

private lateinit var jsonObjectClass: Class<*>
private var jsonTypeReference: TypeReference<*>? = null
override fun setParameterValues(parameters: Properties) {
    jsonObjectClass = (parameters.get(
            DynamicParameterizedType.PARAMETER_TYPE)

            as DynamicParameterizedType.ParameterType)
            .getReturnedClass()
    val jsonTypeParam = parameters.get("json.typereference") as String?
    if (jsonTypeParam != null) {
        jsonTypeReference = Class.forName(jsonTypeParam)
                .getConstructor().newInstance() as TypeReference<*>
    }
}

Now, when we set this on a Collection like this:

@Type(type = "jsonb",
 parameters = arrayOf(Parameter(name = "json.typereference",
 value = "de.eiswind.xino.datalayer.entities.PermissionTypeReference")))
var permissions: MutableList<Permission> = ArrayList<Permission>()
We can pass in any custom TypeReferene instance to Jackson to deserialize generic collections!
class PermissionTypeReference :
        TypeReference<MutableList<Permission>>() {
}
At last we need to make the proper call to Jackson for the deserialization:
override fun fromString(string: String): Any {
    if (jsonTypeReference == null) {
        return JacksonUtil.fromString(string, jsonObjectClass)
    } else {
        return JacksonUtil.fromString(string,
                jsonTypeReference as TypeReference<*>)
    }
}
JacksonUtil has the corresponding overloaded methods:
fun <T> fromString(string: String, clazz: Class<T>): T {
    try {
        return OBJECT_MAPPER.readValue(string, clazz)
    } catch (e: IOException) { ...
fun <T> fromString(string: String, reference: TypeReference<T>): T {
    try {
        return OBJECT_MAPPER.readValue(string, reference)
    } catch (e: IOException) { ...
There's one thing that hit me terrible in the next morning hours, we have to think about clone()!
fun <T : Any> clone(value: T): T {
    return when (value) {
        is ArrayList<*> -> {
            val newList = ArrayList<Any?>()
            for (elem in value) {
                newList.add(fromString(
                        toString(elem), elem.javaClass))
            }
            newList as T        }
        else ->
            fromString(toString(value), value.javaClass)
    }
}

Using Mapstruct with Protobuf3