2019-01-10

Not so easy functional programming in JavaScript

Introduction

JavaScript allows for operating on arrays in a functional way, e.g. using filter or map functions. As an argument for these functions we can pass lambda expression or function reference. Is there a difference between them? The answer is yes.

What's the problem?

In our project we are builing a mapping using String.fromCharCode function. To simplify the usage of this function looked similar to:

[66, 67, 68].map(v => String.fromCharCode(v))

When we run this code with node we received [ 'B', 'C', 'D' ], but when we decided to refactor it to use function reference the result was different:

> [66, 67, 68].map(String.fromCharCode)
[ 'B\u0000\u0000', 'C\u0001\u0000', 'D\u0002\u0000' ]

What happened?

To find the reason of this behavior, let's first play with function String.fromCharCode alone:

> String.fromCharCode(66)
'B'
> String.fromCharCode([66, 67, 68])
'\u0000'
> String.fromCharCode(66, 67, 68)
'BCD'

String.fromCharCode deals with various types and numbers of arguments.

Now, let's examine the function map:

> [66, 67, 68].map(v => v)
[ 66, 67, 68 ]
> [66, 67, 68].map((v, u) => [v, u])
[ [ 66, 0 ], [ 67, 1 ], [ 68, 2 ] ]
> [66, 67, 68].map((v, u, w) => [v, u, w])
[ [ 66, 0, [ 66, 67, 68 ] ],
  [ 67, 1, [ 66, 67, 68 ] ],
  [ 68, 2, [ 66, 67, 68 ] ] ]

map, like many other array functions, passes always three arguments to function. First is current value, second is the index of current value and third is the whole array.

It means that passing String.fromCharCode to map function under the hood looks like this:

> [66, 67, 68].map((v, u, w) => String.fromCharCode(v, u, w))
[ 'B\u0000\u0000', 'C\u0001\u0000', 'D\u0002\u0000' ]

and it is equal to the initial example.

Conclusion

We have to be careful when we want to use a function which can take more than one argument, but we want to pass only the value. We have to pass the function as a lambda expression:

> [66, 67, 68].map(v => String.fromCharCode(v))
[ 'B', 'C', 'D' ]

or create another function which ensures that only the first argument will be passed to desired function:

> const useOnlyValue = f => v => f(v);
undefined
> [66, 67, 68].map(useOnlyValue(String.fromCharCode))
[ 'B', 'C', 'D' ]

2019-01-03

Loops performance in Groovy

Introduction

In the 2018 Advent of Code challenged I solved all the puzzles in Groovy. It is pretty obvious, that choosing good data structure is the most important to obtain performant solution. However, the way we iterate over those structures is also very significant, at least when using Groovy.

Measuring performance

I want to measure how long it takes to sum some numbers. For testing performance of loops I prepared a small function that simply sums some numbers:

void printAddingTime(String message, long to, Closure<Long> adder) {
    LocalTime start = LocalTime.now()
    long sum = adder(to)
    println("$message: $sum calculated in ${Duration.between(start, LocalTime.now()).toMillis()} ms")
}

Pseudo code for summing functions is below:

for i = 1 to n
  for j = 1 to n
    sum += i * j
  end
end

Loops types

Let's implement the summing function in various ways.

collect and sum

First loop type is to use built-in (by Groovy) function collect and sum on collections (Range it this example):

(1..n).collect { long i ->
  (1..n).collect { long j ->
    i * j
  }.sum()
}.sum()

each

Next, let's write the same function using each built-in function on collections (Range it this example) and then add results to accumulator variable:

long sum = 0
(1..n).each { long i ->
    (1..n).each { long j ->
        sum += i * j
    }
}
return sum

times

Now instead of using each we could use the function times built-in on Number by Groovy:

long sum = 0
n.times { long i ->
  n.times { long j ->
    sum += (i + 1)*(j+1)
  }
}
return sum

We have to add 1 to i and j because times generates numbers from 0 to n exclusive.

LongStream with sum

Java 8 came with a new feature - streams. One example of streams is LongStream. Fortunately, it has sum built-in function, which we can use:

LongStream.range(0, n).map { i ->
    LongStream.range(0, n).map { j ->
        (i + 1) * (j + 1)
    }.sum()
}.sum()

LongStream generates numbers in the same way as times function, so we also have to add 1 to i and j here.

LongStream with manual sum

Instead of sum function on LongStream, we can add all numbers manually:

long sum = 0
LongStream.range(0, n).forEach { i ->
    LongStream.range(0, n).forEach { j ->
        sum += (i + 1) * (j + 1)
    }
}
return sum

while

Of course since Groovy inherits from Java a big part of its syntax, we can use the while loop:

long sum = 0
long i = 1
while(i <= n){
    long j = 1
    while(j <= n){
        sum+= i*j
        ++j
    }
    ++i
}
return sum

for

As we can use while, we can also use for loop in Groovy:

long sum = 0
for (long i = 1; i <= n; ++i) {
    for (long j = 1; j <= n; ++j) {
        sum += i * j
    }
}
return sum

Results

My tests I run on Java 1.8 and Groovy 2.5.5. Script loops.groovy was fired using bash script:

#!/bin/sh
for x in 10 100 1000 10000 100000; do
  echo $x
  groovy loops.groovy $x
  echo
done

Values are in milliseconds

Loop  n 10 100 1000 10000 100000
collect + sum 7 22 216 16244 1546822
each 12 17 118 7332 706781
times 2 10 109 8264 708684
LongStream + sum 7 17 127 7679 763341
LongStream + manual sum 18 35 149 6857 680804
while 8 20 103 3166 301967
for 7 10 25 359 27966

As you can spot, for small amount of iterations using built-in Groovy functions is good enough, but for much bigger amount of iterations we should use while or for loops like in plain, old Java.

Show me the code

Code for those examples are available here. You can run those examples on your machine and check performance on your own.

2018-09-27

Testing Kotlin with Spock Part 3 - Interface default method

Kotlin allows you to put method implementation in an interface. The same mechanism can be found in Java interfaces as default methods (and also Groovy or Scala traits). Let's see the difference between the Kotlin and Java default methods in interface by testing it with Groovy and Spock.

What do we want to test?

We often have an interface for access object from the database. In domain, they might look similar to this KotlinOrderRepository:

interface KotlinOrderRepository {
    fun save(order: Order)

    fun find(orderId: OrderId): Order?

    fun get(orderId: OrderId): Order =
            find(orderId) ?: throw NotFound()
}

How to fake it with Groovy?

When we want to use such interface in tests, we can, of course, mock it. However, it is far better to fake repositories with a simple, in-memory implementation. Let's create FakeKotlinOrderRepository in Groovy:

class FakeKotlinOrderRepository implements KotlinOrderRepository {
    private Map<OrderId, Order> data = [:]

    @Override
    void save(Order order) {
        data[order.id] = order
    }

    @Override
    Order find(OrderId orderId) {
        return data[orderId]
    }
}

Unfortunately, this causes a compilation error

/testing-kotlin-in-spock/src/test/groovy/com/github/alien11689/testingkotlinwithspock/defaultmethod/FakeKotlinOrderRepository.groovy: 3: Can't have an abstract method in a non-abstract class. The class 'com.github.alien11689.testingkotlinwithspock.defaultmethod.FakeKotlinOrderRepository' must be declared abstract or the method 'com.github.alien11689.testingkotlinwithspock.defaultmethod.Order get(com.github.alien11689.testingkotlinwithspock.defaultmethod.OrderId)' must be implemented.
 @ line 3, column 1.
   class FakeKotlinOrderRepository implements KotlinOrderRepository {
   ^

1 error

The compiler doesn't see the implementation of the get method in the Kotlin interface. We have to use some magic to make it work in groovy.

Solution

To solve the problem, let's look into the generated classes:

$ ls build/classes/main/com/github/alien11689/testingkotlinwithspock/defaultmethod/
JavaOrderRepository.class
KotlinOrderRepository.class
KotlinOrderRepository$DefaultImpls.class
NotFound.class
Order.class
OrderId.class

The KotlinOrderRepository$DefaultImpls class is the one we're looking for as we can use it in Groovy to implement the missing operation.

class FakeKotlinOrderRepository implements KotlinOrderRepository {

    // ...

    Order get(OrderId orderId) {
        return KotlinOrderRepository.DefaultImpls.get(this, orderId)
    }
}

Now the code compiles and tests pass:

class KotlinRepositoryWithDefaultMethodTest extends Specification {
    OrderId orderId = new OrderId(UUID.randomUUID() as String)
    Order order = new Order(orderId, 'data')
    KotlinOrderRepository kotlinOrderRepository = new FakeKotlinOrderRepository()

    def 'should get order from kotlin repository'() {
        given:
            kotlinOrderRepository.save(order)
        expect:
            kotlinOrderRepository.get(orderId) == order
    }

    def 'should throw NotFound when order does not exist in kotlin repository'() {
        when:
            kotlinOrderRepository.get(orderId)
        then:
            thrown(NotFound)
    }
}

Is there the same problem with Java?

Let's have a quick look at how this works with Java interfaces. If we write a similar repository in Java:

public interface JavaOrderRepository {
    void save(Order order);

    Optional<Order> find(OrderId orderId);

    default Order get(OrderId orderId) {
        return find(orderId).orElseThrow(NotFound::new);
    }
}

and create a fake implementation in Groovy:

class FakeJavaOrderRepository implements JavaOrderRepository {
    private Map<OrderId, Order> data = [:]

    @Override
    void save(Order order) {
        data[order.id] = order
    }

    @Override
    Optional<Order> find(OrderId orderId) {
        return Optional.ofNullable(data[orderId])
    }
}

there is no compilation error and the tests pass:

class JavaRepositoryWithDefaultMethodTest extends Specification {
    OrderId orderId = new OrderId(UUID.randomUUID() as String)
    Order order = new Order(orderId, 'data')
    JavaOrderRepository javaOrderRepository = new FakeJavaOrderRepository()

    def 'should get order from java repository'() {
        given:
            javaOrderRepository.save(order)
        expect:
            javaOrderRepository.get(orderId) == order
    }

    def 'should throw NotFound when order does not exist in java repository'() {
        when:
            javaOrderRepository.get(orderId)
        then:
            thrown(NotFound)
    }
}

Groovy can implement Java interfaces with the default methods without any problems.

Show me the code

Code is available here.

2018-05-28

Testing Kotlin with Spock Part 2 - Enum with instance method

The enum class with instance method in Kotlin is quite similar to its Java version, but they are look a bit different in the bytecode. Let's see the difference by writing some tests using Spock.


What do we want to test?

Let's see the code that we want to test:
enum class EnumWithInstanceMethod {
    PLUS {
        override fun sign(): String = "+"
    },
    MINUS {
        override fun sign(): String = "-"
    };

    abstract fun sign(): String
}
Obviously, it can be written in a better way (e. g. using enum instance variable), but this example shows the case we want to test in the simplest way.


How to test it with Spock?

The simplest test (that does not work)

First, we can write the test like we would do it with a Java enum:
def "should use enum method like in java"() {
    expect:
        EnumWithInstanceMethod.MINUS.sign() == '-'
}
The test fails:
Condition failed with Exception:

EnumWithInstanceMethod.MINUS.sign() == '-'
                             |
                             groovy.lang.MissingMethodException: No signature of method: static com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethod$MINUS.sign() is applicable for argument types: () values: []
                             Possible solutions: sign(), sign(), is(java.lang.Object), find(), with(groovy.lang.Closure), find(groovy.lang.Closure)


    at com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethodTest.should use enum method like in java(EnumWithInstanceMethodTest.groovy:11)
Caused by: groovy.lang.MissingMethodException: No signature of method: static com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethod$MINUS.sign() is applicable for argument types: () values: []
Possible solutions: sign(), sign(), is(java.lang.Object), find(), with(groovy.lang.Closure), find(groovy.lang.Closure)
    ... 1 more
Interesting... Why is Groovy telling us that we are trying to call a static method? Maybe we are not using the enum instance but something else?. Let's create a test where we pass the enum instance to method:
static String consume(EnumWithInstanceMethod e) {
    return e.sign()
}

def "should pass enum as parameter"() {
    expect:
        consume(EnumWithInstanceMethod.MINUS) == '-'
}
Error message:
Condition failed with Exception:

consume(EnumWithInstanceMethod.MINUS) == '-'
|
groovy.lang.MissingMethodException: No signature of method: static com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethodTest.consume() is applicable for argument types: (java.lang.Class) values: [class com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethod$MINUS]
Possible solutions: consume(com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethod)


    at com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethodTest.should pass enum as parameter(EnumWithInstanceMethodTest.groovy:29)
Caused by: groovy.lang.MissingMethodException: No signature of method: static com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethodTest.consume() is applicable for argument types: (java.lang.Class) values: [class com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethod$MINUS]
Possible solutions: consume(com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethod)
    ... 1 more
Now we see that we passed the class com.github.alien11689.testingkotlinwithspock.EnumWithInstanceMethod$MINUS, not the enum instance.


But it works in Java...

Analogous code in JUnit works perfectly and the test passes:
@Test
public void shouldReturnSign() {
    assertEquals("-", EnumWithInstanceMethod.MINUS.sign());
}
Java can access Kotlin's instance method without problems, so maybe something is wrong with Groovy...
But the Java enum with instance method, e. g.
public enum EnumWithInstanceMethodInJava {
    PLUS {
        public String sign() {
            return "+";
        }
    },
    MINUS {
        public String sign() {
            return "-";
        }
    };

    public abstract String sign();
}
works correctly in the Spock test:
def "should use enum method"() {
    expect:
        EnumWithInstanceMethodInJava.MINUS.sign() == '-'
}


What's the difference?

We can spot the difference just by looking at the compiled classes:
$ tree build/classes/main/
build/classes/main/
└── com
    └── github
        └── alien11689
            └── testingkotlinwithspock
                ├── AdultValidator.class
                ├── EnumWithInstanceMethod.class
                ├── EnumWithInstanceMethodInJava$1.class
                ├── EnumWithInstanceMethodInJava$2.class
                ├── EnumWithInstanceMethodInJava.class
                ├── EnumWithInstanceMethod$MINUS.class
                ├── EnumWithInstanceMethod$PLUS.class
                ├── Error.class
                ├── Ok.class
                ├── ValidationStatus.class
                └── Validator.class
Java generates anonymous classes (EnumWithInstanceMethodInJava$1 and EnumWithInstanceMethodInJava$2) for the enum instances, but Kotlin names those classes after the enum instances names (EnumWithInstanceMethod$MINUS and EnumWithInstanceMethod$PLUS).
How does it tie into the problem with Groovy? Groovy does not need the .class when accessing class in code, so when we try to access EnumWithInstanceMethod.MINUS, Groovy converts it to EnumWithInstanceMethod.MINUS.class, not the instance of the enum. The same problem does not occur in Java code since there is no EnumWithInstanceMethodInJava$MINUS class.


Solution

Knowing the difference, we can solve the problem of accessing Kotlin's enum instance in our Groovy code.
The first solution is accessing the enum instance with valueOf method:
def "should use enum method working"() {
    expect:
        EnumWithInstanceMethod.valueOf('MINUS').sign() == '-'
}
The second way is to tell Groovy explicitly that we want to access the static field which is the instance of enum:
def "should use enum method"() {
    expect:
        EnumWithInstanceMethod.@MINUS.sign() == '-'
}
You can choose either solution depending on style of your code and your preferences.


Show me the code

Code is available here.

2018-03-13

Testing Kotlin with Spock Part 1 - Object

The object keyword in Kotlin creates singleton in a very convenient way. It can be used for example as a state of an operation. Spock Framework is one of the most expressive and readable test framework available in the Java ecosystem. Let's see how Kotlin object can be used in the Spock tests.

What do we want to test?

We have a single method validate in Validator interface which returns validation status: Ok or Error.

sealed class ValidationStatus
object Ok : ValidationStatus()
object Error : ValidationStatus()

interface Validator<T> {
    fun validate(value: T): ValidationStatus
}

We also provide a simple implementation of this interface:

class AdultValidator : Validator<Int> {
    override fun validate(value: Int) = if (value >= 18) Ok else Error
}

How to test it with Spock?

First - silly approach

First, let's write a parameterized test for the validator:

AdultValidator sut = new AdultValidator()

def 'should validate age #age'() {
    expect:
        sut.validate(age) == result
    where:
        age | result
        0   | Error
        17  | Error
        18  | Ok
        19  | Ok
}

We expect it to pass, but it fails... Error and Ok are classes in the code above.

Second - naive approach

We need instances instead, so we modify the test a little:

def 'should validate age #age'() {
    expect:
        sut.validate(age) == result
    where:
        age | result
        0   | new Error()
        17  | new Error()
        18  | new Ok()
        19  | new Ok()
}

And again, this one fails as well. Why? It is because Error and Ok classes do not have overridden equals method. But why? We expects Kotlin objects (those created with object keyword, not plain object) to have it implemented correctly. What is more, it works correctly in Kotlin:

fun isOk(status:ValidationStatus) = status == Ok

Third - correct approach

Let's look into the class file:

$ javap com/github/alien11689/testingkotlinwithspock/Ok.class
Compiled from "Validator.kt"
public final class com.github.alien11689.testingkotlinwithspock.Ok extends com.github.alien11689.testingkotlinwithspock.ValidationStatus {
  public static final com.github.alien11689.testingkotlinwithspock.Ok INSTANCE;
  static {};
}

If we want to access the real object that Kotlin uses in such comparisson, then we should access the class static property called INSTANCE:

def 'should validate age #age'() {
    expect:
        sut.validate(age) == result
    where:
        age | result
        0   | Error.INSTANCE
        17  | Error.INSTANCE
        18  | Ok.INSTANCE
        19  | Ok.INSTANCE
}

Now the test passes.

Fourth - alternative approach

We can also check the method result without specific instance of the object class and use instanceof or Class#isAssignableFrom instead.

def 'should validate age #age'() {
    when:
        ValidationStatus result = sut.validate(age)
    then:
        result.class.isAssignableFrom(expected)
    where:
        age | expected
        0   | Error
        17  | Error
        18  | Ok
        19  | Ok
}

Show me the code

Code is available here;

2018-01-18

MapStruct mapper injection in OSGi Blueprint

What is MapStruct?

According to MapStruct website:
MapStruct is a code generator that greatly simplifies the implementation of mappings between Java bean types based on a convention over configuration approach. The generated mapping code uses plain method invocations and thus is fast, type-safe and easy to understand.

Inject MapStruct mapper in Blueprint OSGi

Such mappings are sometimes necessary in our integration projects. We also use OSGi to create our applications and Blueprint for dependency injection. Blueprin Maven Plugin makes it very easy to use, providing annotation support.
MapStruct supports component models like cdi, spring and jsr330, so generated classes could be used as beans. Fortunately, Blueprint Maven Plugin uses annotations from JSR 330, such as Singleton or Named.
The only thing we have to do is to add property componentModel with value jsr330 to a mapping interface:
@Mapper(componentModel = "jsr330")
public interface PersonMapper {
    Person toDomain(PersonDto personDto);
}
and now we can inject PersonMapper to our beans:
@Singleton
@AllArgsConstructor
public class CreatePersonHandler {
    private final PersonRepository personRepository;
    private final PersonMapper personMapper;

    // ...
}
Blueprint Maven Plugin will generate an XML file with bean PersonMapperImpl and inject it to CreatePersonHandler:
<?xml version="1.0" encoding="UTF-8"?><blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
    <bean id="createPersonHandler" class="com.github.alien11689.osgi.mapstructblueprint.CreatePersonHandler">
        <argument ref="personRepository"/>
        <argument ref="personMapperImpl"/>
    </bean>
    <bean id="personMapperImpl" class="com.github.alien11689.osgi.mapstructblueprint.PersonMapperImpl"/>
    <bean id="personRepository" class="com.github.alien11689.osgi.mapstructblueprint.PersonRepository"/>
</blueprint>

Generate all mappers with JSR 330 annotations

If you have multiple mappers and all of them should be beans, then you can simply add one compiler argument in configuration and all the mappers will have @Singleton and @Named annotations by default.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    ...
    <build>
        <plugins>
            ...
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgs>
                        <compilerArg>
                             -Amapstruct.defaultComponentModel=jsr330
                        </compilerArg>
                    </compilerArgs>
                </configuration>
            </plugin>
            ...
        </plugins>
    </build>
</project>

Try it on your own

The code is available at Github.

2017-11-14

Karaf configuration as Groovy file

Introduction

By deafault, Apache Karaf keeps configuration for bundles in the etc directory as flat properties files. We can override configuration for the storing mechanism by providing own implementation of the org.apache.felix.cm.PersistenceManager interface and use much more readable format for bundle properties, e. g. groovy config.

Turning off built-in Karaf persistence

As we can read in Karaf documentation:
Apache Karaf persists configuration using own persistence manager in case of when available persistence managers do not support that.
We will use our custom implementation of persistence, so Karaf persistence is not needed. We can turn it off by setting variable storage to an empty value:
$ cat etc/org.apache.karaf.config.cfg
storage=
This option is available since version 4.1.3 when this issue was resolved.

Registering custom Persistence Manager

First we have to create and register an OSGi service implementing org.apache.felix.cm.PersistenceManager. If we build and install the bundle with such service while Karaf is running (e.g. by putting jar in the deploy directory), then we should have at least two PersistenceManager services registered:
karaf@root()> ls org.apache.felix.cm.PersistenceManager
[org.apache.felix.cm.PersistenceManager]
----------------------------------------
 service.bundleid = 7
 service.description = Platform Filesystem Persistence Manager
 service.id = 14
 service.pid = org.apache.felix.cm.file.FilePersistenceManager
 service.ranking = -2147483648
 service.scope = singleton
 service.vendor = Apache Software Foundation
Provided by :
 Apache Felix Configuration Admin Service (7)
Used by:
 Apache Felix Configuration Admin Service (7)

[org.apache.felix.cm.PersistenceManager]
----------------------------------------
 osgi.service.blueprint.compname = groovyConfigPersistenceManager
 service.bundleid = 56
 service.id = 117
 service.pid = com.github.alien11689.osgi.util.groovyconfig.impl.GroovyConfigPersistenceManager
 service.ranking = 100
 service.scope = bundle
Provided by :
 groovy-config (56)
Used by:
 Apache Felix Configuration Admin Service (7)
Loaded configurations will be cached by configuration admin. We can use org.apache.felix.cm.NotCachablePersistenceManager interface if we want to implement custom caching strategy.

Creating a new properties file

Let's create a new properties file in groovy, e.g:
$ cat etc/com.github.alien11689.test1.groovy
a = '7'
b {
    c {
        d = 1
        e = 2
    }
    z = 9
}
x.y.z='test'
If we search for properties with pid com.github.alien11689.test1, Karaf will find these.
karaf@root()> config:list '(service.pid=com.github.alien11689.test1)'
----------------------------------------------------------------
Pid:            com.github.alien11689.test1
BundleLocation: null
Properties:
   a = 7
   b.c.d = 1
   b.c.e = 2
   b.z = 9
   service.pid = com.github.alien11689.test1
   x.y.z = test
If we make any change to the file they won't be mapped to properties, because there are no file watchers defined for it.
We could manage such properties using Karaf commands instead.

Managing configuration via Karaf commands

We can define a new pid using Karaf commands:
karaf@root()> config:property-set -p com.github.alien11689.test2 f.a 6
karaf@root()> config:property-set -p com.github.alien11689.test2 f.b 'test'
Since our PersistenceManager has higher service.ranking (100 > -2147483648), new pid will be stored as a groovy file:
$ cat etc/com.github.alien11689.test2.groovy
f {
    b='test'
    a='6'
}
We can also change/remove properties or remove the whole configuration pid using karaf commands and it will all be mapped to groovy configuration files.

Sources

Sources are available on github.

2017-08-24

Using Kotlin extensions in Groovy

Extensions in Kotlin and Groovy

Kotlin and Groovy have mechanisms for extending existing classes without using inheritance or decorators. In both languages, the mechanisms are called extension methods. Their source code looks different, but generated bytecode is quite similar. Thanks to that, Groovy is able to use Kotlin extensions just like its own.

Why would I want to use such extensions in Groovy? The main reason is that I want to test my extensions using the best testing framework available for the JVM - Spock Framework.

Code is available here.

Extensions in Kotlin

There are many types of extensions in Kotlin. I decided to focus only on extension functions and properties.

As an example, I extend the java.lang.String class. First, I create an extension function skipFirst, which skips first N characters:


Next, I create an extension property answer, which is the Answer to the Ultimate Question of Life, the Universe, and Everything:


Both extensions are declared in package com.github.alien11689.extensions, in file called StringExtensions. However, the generated class in target directory is named StringExtensionsKt and this is the name that must be used when accessing from other languages. Specific class name can be forced by annotation @file:JvmName.

Using Kotlin extensions in Groovy

There are two ways for using extensions in Groovy that are supported by good IDEs. First, you can declare scope where the extensions are available by use method:


It is acceptable, but is not very convenient. The second and much better way is to use an extension module definition. The extension module is defined in file org.codehaus.groovy.runtime.ExtensionModule in directory src/main/resources/META-INF/services/. The same directory is monitored by ServiceLoader, but the file format is completely different:


The tests look much better now:

2017-02-18

OSGi Blueprint visualization

What is blueprint?

Blueprint is a dependency injection framework for OSGi bundles. It could be written by hand or generated using Blueprint Maven Plugin. Blueprint file is only an XML describing beans, services and references. Each OSGi bundle could have one or more blueprint files.

Blueprint files represent architecture of our bundle. Let's visualize it using groovy script and graphviz available in my github repository and analyze.

Example generation

Pre: All you need is groovy and graphviz installed on your OS

I am working mostly with bundles with generated blueprint, so I will use blueprint file generated from Blueprint Maven Plugin tests as example. All examples are included in github repository.

Generation could be invoked by running run.sh script with given destination file prefix (png extension will be added to it) and path to blueprint file:

mkdir -p target

./run.sh target/fullBlueprint fullBlueprint.xml

Visualization is available here.

Separating domains

First if you look at the image, you see that some beans are grouped. You could easily extract such domains with tree roots: beanWithConfigurationProperties and beanWithCallbackMethods to separate blueprint files and bundles in future and generate images from them:

./run.sh target/beanWithCallbackMethods example/firstCut/beanWithCallbackMethods.xml
./run.sh target/beanWithConfigurationProperties example/firstCut/beanWithConfigurationProperties.xml
./run.sh target/otherStuff example/firstCut/otherStuff.xml

Now we have three, a bit cleaner, images: beanWithConfigurationProperties.png, beanWithCallbackMethods.png and otherStuff.png.

We also could generate image from more than one blueprint:

./run.sh target/joinFirstCut example/firstCut/otherStuff.xml example/firstCut/beanWithConfigurationProperties.xml example/firstCut/beanWithCallbackMethods.xml

And the result is here. The image contains beans grouped by file, but if you do not like it, you could force generation without such separation using option --no-group-by-file:

./run.sh target/joinFirstCutGrouped example/firstCut/otherStuff.xml example/firstCut/beanWithConfigurationProperties.xml example/firstCut/beanWithCallbackMethods.xml --no-group-by-file

It will generate image with all beans from all files.

Exclusion

Sometimes it is difficult to spot and extract other domains. It will be easier to do some experiments on blueprint. For example, bean my1 is a dependency for too many other beans. You could consider converting my1 bean to OSGi service and extracting it to another bundle.

Let's exclude my1 bean from generation via -e option and see what happens:

./run.sh target/otherStuffWithoutMy example/firstCut/otherStuff.xml -e my1

Result is available here. Now we see, that tree with root bean myFactoryBeanAsService could be separated and my1 could be inject to it as osgi service in another bundle.

You could exclude more than one bean adding -e switch for each of them, e. g. -e my1 -e m2 -e myBean123.

Conclusion

Blueprint is great for dependency injection for OSGi bundles, but it is easy to create quite big context containing many domains. It is much easier to recognize or search for such domains using blueprint visualizer script.


YOUR CODE HRER

2016-08-16

Deploy WSDL file as OSGI Bundle in Apache Karaf

Introduction

WSDL file describes webservices. Java classes are often generated from WSDL. For this purpose, we could use command line tools (e. g. wsdl2Java or wsimport) or using maven plugin.

From the other side, we have Apache Karaf which is OSGI container. Karaf has installed by default many deployers for creating OSGi bundles from files, e. g. Blueprint deployer, Spring deployer or War deployer.

It is easy to generate java classes from WSDL file and also to create custom deployer for Karaf, so why do not join these two features?

Installation of WSDL deployer

Source code of my WSDL deployer is provided here. You can download and build it:

mvn clean install

We also need Karaf. I will use the newest version 4.0.5. It could be download from Karaf website. When you download and unpack it, you can run it:

$ cd PUT_PATH_TO_KARAF_DIR_HERE
$ ./bin/karaf
    __ __                  ____      
   / //_/____ __________ _/ __/      
  / ,<  / __ `/ ___/ __ `/ /_        
 / /| |/ /_/ / /  / /_/ / __/        
/_/ |_|\__,_/_/   \__,_/_/         

Apache Karaf (4.0.5)

Hit '<tab>' for a list of available commands
and '[cmd] --help' for help on a specific command.
Hit '<ctrl-d>' or type 'system:shutdown' or 'logout' to shutdown Karaf.

karaf@root()>

and install commons-io and wsdl-delpoyer bundles:

karaf@root()> install -s mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.commons-io/1.4_3
Bundle ID: 52
karaf@root()> install -s mvn:com.github.alien11689.karaf/wsdl-deployer/1.0.0-SNAPSHOT
Bundle ID: 53

Install WSDL from Karaf shell

I will test deployer using WSDL file named exampleService-2.0.0.wsdl (provided WSDL is similar to this, but has another namespace in types schama for testing purpose):

<?xml version="1.0"?>
<wsdl:definitions
  xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
  xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
  xmlns:tns="http://Example.org"
  xmlns:sns="http://Example.org/schema"
  xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
  xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
  xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract"
  xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
  xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
  xmlns:wsa10="http://www.w3.org/2005/08/addressing"
  xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex"
  targetNamespace="http://Example.org"
  xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
  <wsdl:types>
      <xsd:schema targetNamespace="http://Example.org/schema" elementFormDefault="qualified" >
  <xsd:element name="Add">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element minOccurs="0" name="a" type="xsd:int" />
        <xsd:element minOccurs="0" name="b" type="xsd:int" />
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="AddResponse">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element minOccurs="0" name="result" type="xsd:int" />
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="Subtract">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element minOccurs="0" name="a" type="xsd:int" />
        <xsd:element minOccurs="0" name="b" type="xsd:int" />
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
  <xsd:element name="SubtractResponse">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element minOccurs="0" name="result" type="xsd:int" />
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="ICalculator_Add_InputMessage">
    <wsdl:part name="parameters" element="sns:Add" />
  </wsdl:message>
  <wsdl:message name="ICalculator_Add_OutputMessage">
    <wsdl:part name="parameters" element="sns:AddResponse" />
  </wsdl:message>
  <wsdl:message name="ICalculator_Subtract_InputMessage">
    <wsdl:part name="parameters" element="sns:Subtract" />
  </wsdl:message>
  <wsdl:message name="ICalculator_Subtract_OutputMessage">
    <wsdl:part name="parameters" element="sns:SubtractResponse" />
  </wsdl:message>
  <wsdl:portType name="ICalculator">
    <wsdl:operation name="Add">
      <wsdl:input wsaw:Action="http://Example.org/ICalculator/Add" message="tns:ICalculator_Add_InputMessage" />
      <wsdl:output wsaw:Action="http://Example.org/ICalculator/AddResponse" message="tns:ICalculator_Add_OutputMessage" />
    </wsdl:operation>
    <wsdl:operation name="Subtract">
      <wsdl:input wsaw:Action="http://Example.org/ICalculator/Subtract" message="tns:ICalculator_Subtract_InputMessage" />
      <wsdl:output wsaw:Action="http://Example.org/ICalculator/SubtractResponse" message="tns:ICalculator_Subtract_OutputMessage" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="DefaultBinding_ICalculator" type="tns:ICalculator">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="Add">
      <soap:operation soapAction="http://Example.org/ICalculator/Add" style="document" />
      <wsdl:input>
        <soap:body use="literal" />
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal" />
      </wsdl:output>
    </wsdl:operation>
    <wsdl:operation name="Subtract">
      <soap:operation soapAction="http://Example.org/ICalculator/Subtract" style="document" />
      <wsdl:input>
        <soap:body use="literal" />
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal" />
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="CalculatorService">
        <wsdl:port name="ICalculator" binding="tns:DefaultBinding_ICalculator">
            <soap:address location="http://localhost/ICalculator" />
        </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

We could install it via command:

karaf@root()> install -s wsdl:file:PUT_PATH_TO_WSDL_HERE/exampleService-2.0.0.wsdl\$package=org.github.alien11689.example&s1=http://Example.org/schema&t1=org.github.alien11689.example.schema
Bundle ID: 54

File must have format ${bundleSymbolicName}-${version}.wsdl.

Provided options are:

  • package - allows to change package of generated interface
  • pair s1 and t1 - maps schema in WSDL to package (WSDL deployer is in draft verion nowadays provides options to map only one schema).

Karaf has installed this file:

karaf@root()> headers 54

Bundle 54
---------
Manifest-Version = 2

Bundle-ManifestVersion = 2
Bundle-SymbolicName = exampleService-2.0.0.wsdl
Bundle-Version = 2.0.0

Export-Package =
    org.github.alien11689.example.schema;version=2.0.0,
    org.github.alien11689.example;version=2.0.0
Import-Package =
    javax.jws,
    javax.jws.soap,
    javax.xml.bind.annotation,
    javax.xml.namespace,
    javax.xml.ws

Install WSDL by putting it into Karaf drop folder

You can also install WSDL file by copying it to deploy directory:

cp PUT_PATH_TO_WSDL_HERE/exampleService-2.0.0.wsdl PUT_PATH_TO_KARAF_DIR_HERE/deploy/deployedExampleService-2.0.0.wsdl

It is much more simple to do, but do not allow for customization (e. g. namespace to package mapping). It creates bundle:

karaf@root()> list | grep deployedExampleService
55 | Active |  80 | 2.0.0          | deployedExampleService-2.0.0.wsdl
karaf@root()> headers 55

Bundle 55
---------
Manifest-Version = 2

Bundle-ManifestVersion = 2
Bundle-SymbolicName = deployedExampleService-2.0.0.wsdl
Bundle-Version = 2.0.0

Export-Package =
    org.example;version=2.0.0,
    org.example.schema;version=2.0.0
Import-Package =
    javax.jws,
    javax.jws.soap,
    javax.xml.bind.annotation,
    javax.xml.namespace,
    javax.xml.ws

How does it work?

Deployer uses wsimport command to create in temporary directory and compile generated java classes. Compiled class are packed with MANIFEST.MF into service.jar and such jar is really installed in OSGi container. For example, my temporary directory is /tmp/4ff81631-3c08-487a-b731-1f95c568026f:

$ tree /tmp/4ff81631-3c08-487a-b731-1f95c568026f
/tmp/4ff81631-3c08-487a-b731-1f95c568026f
├── Jaxb-binding.xml
├── Jaxws-binding.xml
├── service.wsdl
├── src
│   └── org
│       └── github
│           └── alien11689
│               └── example
│                   ├── CalculatorService.java
│                   ├── ICalculator.java
│                   └── schema
│                       ├── Add.java
│                       ├── AddResponse.java
│                       ├── ObjectFactory.java
│                       ├── package-info.java
│                       ├── Subtract.java
│                       └── SubtractResponse.java
└── target
    ├── org
    │   └── github
    │       └── alien11689
    │           └── example
    │               ├── CalculatorService.class
    │               ├── ICalculator.class
    │               └── schema
    │                   ├── Add.class
    │                   ├── AddResponse.class
    │                   ├── ObjectFactory.class
    │                   ├── package-info.class
    │                   ├── Subtract.class
    │                   └── SubtractResponse.class
    └── service.jar

And my service.jar contains:

$ jar tf /tmp/4ff81631-3c08-487a-b731-1f95c568026f/target/service.jar
META-INF/
META-INF/MANIFEST.MF
org/
org/github/
org/github/alien11689/
org/github/alien11689/example/
org/github/alien11689/example/schema/
org/github/alien11689/example/schema/Add.class
org/github/alien11689/example/schema/ObjectFactory.class
org/github/alien11689/example/schema/Subtract.class
org/github/alien11689/example/schema/SubtractResponse.class
org/github/alien11689/example/schema/package-info.class
org/github/alien11689/example/schema/AddResponse.class
org/github/alien11689/example/ICalculator.class
org/github/alien11689/example/CalculatorService.class

Conclusion

WSDL generation and Karaf deployers could be easily joined and simplified creation of OSGi bundles without explicite creation of jar. Provided WSDL deployer is just draft, but could be very useful when we have many WSDLs and do not want to create separate artifacts for them.

Source code of WSDL deployer is provided here.