2015-12-13

Primitives and its wrapped types compatibility

Introduction

How often do you think about possible changes in your API? Do you consider that something required could become optional in future? How about compatibility of such change? One of this changes is going from primitive (e. g. int) to its wrapped type (e. g. Integer). Let's check it out.

API - first iteration

Let's start with simple DTO class Dep in our public API.

public class Dep {
    private int f1;

    public int getF1(){
        return f1;
    }

    public void setF1(int f1){
        this.f1 = f1;
    }

    // other fields and methods omitted
}

f1 is obligatory field that never will be null.

Let's use it in Main class:

public class Main {
    public static void main(String... args) {
        Dep dep = new Dep();
        dep.setF1(123);
        System.out.println(dep.getF1());
    }
}

compile it:

$ javac depInt/Dep.java
$ javac -cp depInt main/Main.java

and run:

$ java -cp depInt:main Main
123

It works.

API - obligatory field become optional

Now suppose our business requirements have changed. f1 is not longer obligatory and we want possibility to set it to null.

So we provide next iteration of Dep class where f1 field has type Integer.

public class Dep {
    private Integer f1;

    public Integer getF1(){
        return f1;
    }

    public void setF1(Integer f1){
        this.f1 = f1;
    }

    // other fields and methods omitted
}

We compile only the new Dep class because we do not want to change the Main class:

$ javac depInteger/Dep.java

and run it with old Main:

$ java -cp depInteger:main Main
Exception in thread "main" java.lang.NoSuchMethodError: Dep.setF1(I)V
    at Main.main(Main.java:4)

Wow! It does not work...

Why does it not work?

We can use javap tool to investigate Main class.

$ javap -c main/Main.class
Compiled from "Main.java"
public class Main {
  public Main();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String...);
    Code:
       0: new           #2                  // class Dep
       3: dup
       4: invokespecial #3                  // Method Dep."<init>":()V
       7: astore_1
       8: aload_1
       9: bipush        123
      11: invokevirtual #4                  // Method Dep.setF1:(I)V
      14: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
      17: aload_1
      18: invokevirtual #6                  // Method Dep.getF1:()I
      21: invokevirtual #7                  // Method java/io/PrintStream.println:(I)V
      24: return
}

The most important are 11th and 18th instructions of main method. Main lookups for methods which use int (I in method signature).

Next let's compile the Main class with Dep which has f1 of type Integer:

javac -cp depInteger main/Main.java

and use javap on this class:

$ javap -c main/Main.class
Compiled from "Main.java"
public class Main {
  public Main();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String...);
    Code:
       0: new           #2                  // class Dep
       3: dup
       4: invokespecial #3                  // Method Dep."<init>":()V
       7: astore_1
       8: aload_1
       9: bipush        123
      11: invokestatic  #4                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      14: invokevirtual #5                  // Method Dep.setF1:(Ljava/lang/Integer;)V
      17: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
      20: aload_1
      21: invokevirtual #7                  // Method Dep.getF1:()Ljava/lang/Integer;
      24: invokevirtual #8                  // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
      27: return
}

Now we see the difference. The main method:

  • converts int to Integer in instruction 11th,
  • invokes method setF1 which takes parameter of type Integer (Ljava/lang/Integer;) in instruction 14th,
  • invokes method getF1 which returns Integer in instruction 21st.

These differences do not allow us to use the Main class with Dep without recompilation if we change f1.

How about Groovy?

We have GroovyMain class which do the same as Main class written in Java.

class GroovyMain {
    static void main(String... args) {
        Dep dep = new Dep(f1: 123)
        println(dep.f1)
    }
}

We will compile GroovyMain class only with Dep which uses int:

$ groovyc -cp lib/groovy-all-2.4.5.jar:depInt -d main main/GroovyMain.groovy

It runs great as expected with int:

$ java -cp lib/groovy-all-2.4.5.jar:depInt:main GroovyMain
123

but with Integer... It works the same!

$ java -cp lib/groovy-all-2.4.5.jar:depInteger:main GroovyMain
123

Groovy is immune to such change.

With CompileStatic

But what if we compile groovy with CompileStatic annotation? This annotation instructs groovy compiler to compile class with type checking and should produce bytecode similar to javac output.

GroovyMainCompileStatic class is GroovyMain class with only CompileStatic annotation:

import groovy.transform.CompileStatic

@CompileStatic
class GroovyMainCompileStatic {
    static void main(String... args) {
        Dep dep = new Dep(f1: 123)
        println(dep.f1)
    }
}

When we compile this with Dep with int field:

$ groovyc -cp lib/groovy-all-2.4.5.jar:depInt -d main main/GroovyMainCompileStatic.groovy

then of course it works:

$ java -cp lib/groovy-all-2.4.5.jar:depInt:main GroovyMainCompileStatic
123

but with Dep with Integer field it fails like in Java:

$ java -cp lib/groovy-all-2.4.5.jar:depInteger:main GroovyMainCompileStatic
Exception in thread "main" java.lang.NoSuchMethodError: Dep.setF1(I)V
    at GroovyMainCompileStatic.main(GroovyMainCompileStatic.groovy:6)

Conclusion

Change from primitive to its wrapped java type is not compatible change. Bytecode which uses dependent class assumes that there will be method which consumes or returns e. g. int and cannot deal with the same class which provides such method with Integer in place of int.

Groovy is much more flexible and could handle it, but only if we do not use CompileStatic annotation.

The source code is available here.

2015-12-08

Spring autowire with qualifiers

Introduction

Autowired is great annotation, which by default inject beans by type to annotated element (constructor, setter or field). But how to use it, when there is more than one bean of requested type.

Autowired with one bean

Suppose we will work with small interface:

interface IHeaderPrinter {
    String printHeader(String header)
}

When we have only one bean implementing IHeaderPrinter:

@Component
class HtmlHeaderPrinter implements IHeaderPrinter{
    @Override
    String printHeader(String header) {
        return "<h1>$header</h1>"
    }
}

then everything works great and test passes.

@Autowired
IHeaderPrinter headerPrinter

@Test
void shouldPrintHtmlHeader() {
    assert headerPrinter.printHeader('myTitle') == '<h1>myTitle</h1>'
}

Two implementations

But what will happen, if we add another implementation of IHeaderPrinter, e. g. MarkdownHeaderPrinter?

@Component
class MarkdownHeaderPrinter implements IHeaderPrinter {
    @Override
    String printHeader(String header) {
        return "# $header"
    }
}

Now out test with fail with exception:

Error creating bean with name 'com.blogspot.przybyszd.spring.autowire.SpringAutowireWithQualifiersApplicationTests': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.blogspot.przybyszd.spring.autowire.IHeaderPrinter com.blogspot.przybyszd.spring.autowire.SpringAutowireWithQualifiersApplicationTests.headerPrinter; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.blogspot.przybyszd.spring.autowire.IHeaderPrinter] is defined: expected single matching bean but found 2: markdownHeaderPrinter,htmlHeaderPrinter

We have to decide which implementation we want to use in our test, so ...

Two implementations with Qualifier

Each bean is registered with name equal its class. For example HtmlHeaderPrinter is named htmlHeaderPrinter. The name is also its qualifier. We have to tell Autowired, that it should inject htmlHeaderPrinter:

@Autowired
@Qualifier('htmlHeaderPrinter')
IHeaderPrinter headerPrinter

Now our test passes again.

Two implementations qualified by field name

If field is names like implementing class (for example htmlHeaderPrinter), then this class implementation will be injected:

@Autowired
IHeaderPrinter htmlHeaderPrinter

And test passes:

@Test
void shouldPrintHtmlHeader() {
    assert htmlHeaderPrinter.printHeader('myTitle') == '<h1>myTitle</h1>'
}

Thanks to @marcinjasion.

Two implementation with Primary

We often have one implementation which we almost always want to inject, so do we still have to put Qualifier with its name wherever we want to use it? No.

We could mark one implementation as Primary and this bean will be wired by default (unless we explicit give another Qualifier to use injection point):

@Component
@Primary
class HtmlHeaderPrinter implements IHeaderPrinter{
    // ...
}
@Autowired
IHeaderPrinter headerPrinter

Summary

Autowired annotation allows us to inject dependencies to beans. It works great without additional configuration, when each bean could be uniquely find by type. When we have more than one bean, that could be injected, we have to use Qualifier or Primary annotation to help it find desired implementation.

Source code is available here.

2015-12-02

Scheduling tasks using Message Queue

Introduction

How to schedule your task for later execution? You often create table in database, configure job that checks if due time of any task occured and then execute it.

But there is easier way if only you have message broker with your application... You could publish/send your message and tell it that it should be delivered with specified delay.

Scheduling messages using ActiveMQ

ActiveMQ is open source message broker written in Java. It is implementation of JMS (Java Message Service).

You could start its broker with scheduling support by adding flag schedulerSupport to broker configuration:

<beans ...>
    ...
    <broker xmlns="http://activemq.apache.org/schema/core"
            brokerName="localhost"
            dataDirectory="${activemq.data}"
            schedulerSupport="true">
            ...
    </broker>
    ...
</beans>

Now, if you want to delay receiving message by few seconds, you could add property during message creation, e.g.:

message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 8000)

Delay unit is miliseconds.

Of course queue must be persisted.

When you listen for message on the same queue, then you will see that message indeed will be received with 8 second delay.

...
Send time: Tue Dec 01 18:51:23 CET 2015
...
Message received at Tue Dec 01 18:51:31 CET 2015
...

Scheduling messages using RabbitMQ

Scheduling tasks is not only the feature of ActiveMQ. It is also available with RabbitMQ.

RabitMQ is message broker written in Erlang. It uses protocol AMQP.

First you have to install plugin rabbitmq_delayed_message_exchange. It could be done via command:

rabbitmq-plugins enable --offline rabbitmq_delayed_message_exchange

You have to define exchange in RabbitMQ which will use features from this plugin. Queue for delayed messages should be bound to this exchange. Routing key should be set to queue name.

channel.exchangeDeclare(exchange, 'x-delayed-message', true, false, ['x-delayed-type': 'direct']);
channel.queueBind(queue, exchange, queue);
channel.queueDeclare(queue, true, false, false, null);

Of course queue must be persisted.

To test it just publish new message with property x-delay:

channel.basicPublish(exchange,
                    queue,
                    new AMQP.BasicProperties.Builder().headers('x-delay': 8000).build(),
                    "Message: $currentUuid".bytes)

Message will be delayed with 8 seconds:

...
Send time: Tue Dec 01 19:04:18 CET 2015
...
Message received at Tue Dec 01 19:04:26 CET 2015
...

Conclusion

Why you create similar mechanism for handling scheduled tasks on your own, when you could use your message brokers and delayed messages to schedule future tasks?

Sources are available here.

2015-11-14

Kotlin's extensions for each class

Extensions in Kotlin are very powerful mechanism. It allows for add any method to any of existing classes. Each instance has (as in Java) equals, toString and hashCode methods, but there is much more in Kotlin.

Example classes


Let's define some simple classes describing person: normal class and data class.

class PersonJaxb {
    var firstName: String? = null
    var lastName: String? = null
    var age: Int? = null
}

data class Person(val firstName: String, val lastName: String, val age: Int)

Normal class extensions


All instances have methods described below.

apply method


I often work with jaxb classes similar to PersonJaxb, which has not all arg constructor and all fields must be set via setters. Kotlin helps to deal with it via apply method. Target instance is provided as delagate to closure so we could define all fields values in it and returns this. The signature is T.apply(f: T.() -> Unit): T.

@Test
fun applyTest() {
    //when
    val person = PersonJaxb().apply {
        firstName = "John"
        lastName = "Smith"
        age = 20
    }

    //then
    assertEquals(20, person.age)
    assertEquals("John", person.firstName)
    assertEquals("Smith", person.lastName)
}

let method


Another extension is let method which is similar to map operation for collections. It has signature T.let(f: (T) -> R): R. this is passed as parameter to given closure/function.

@Test
fun letTest() {
    //when
    val fullName = Person("John", "Smith", 20).let {
        "${it.firstName} ${it.lastName}"
    }

    //then
    assertEquals("John Smith", fullName)
}

run method


run method looks like merge of apply and let methods: access to this is via delegate as in apply, but it also returns value as in let method. It has signature T.run(f: T.() -> R): R.

@Test
fun runTest() {
    //when
    val fullName = Person("John", "Smith", 20).run {
        "$firstName $lastName"
    }

    //then
    assertEquals("John Smith", fullName)
}

to method


Each instance has also defined to infix operator, which is used to create Pair. Pairs is helpful to create map entries. It has signature A.to(that: B): Pair<A, B>.

@Test
fun toTest() {
    //when
    val pair = Person("John", "Smith", 20) to 5

    //then
    assertEquals(Person("John", "Smith", 20), pair.first)
    assertEquals(5, pair.second)
}

Data class methods


Data class instances have also some other helpful methods (which are not extensions, but are generated for us).

componentX methods


Data class Person has three fields and it has component method generated for each of them: component1 for firstName, component2 for lastName and component3 for age.

@Test
fun componentsTest() {
    //when
    val p = Person("John", "Smith", 20)

    //then
    assertEquals("John", p.component1())
    assertEquals("Smith", p.component2())
    assertEquals(20, p.component3())
}

Why is it helpful? componentX methods are used in extracting (similar to Scala case classes extracting mechanism), e. g.:

@Test
fun extractingTest() {
    //when
    val (first, last, age) = Person("John", "Smith", 20)

    //then
    assertEquals(20, age)
    assertEquals("John", first)
    assertEquals("Smith", last)
}

copy method


copy method allows to create new instance based on current instance.

@Test
fun copyTest() {
    //when
    val person = Person("John", "Smith", 20).copy(lastName = "Kowalski", firstName = "Jan")

    //then
    assertEquals(Person("Jan", "Kowalski", 20), person)
}

Summary


Kotlin's extensions for each instances are very simple and help to solve many problems. The code written with these extensions is much more readable and concise than written in Java.

Sources are available here.

2015-10-11

Kotlin, Callable and ExecutorService

I've recently written about using Callable in Groovy, but how does it look like in kotlin?

Callable instance as separete class

First, let's create class which implements Callable interface:
class MyJob : Callable<Int> {
    override fun call() = 42
}

Now we could pass instance of this class to executorService:
fun callableAsClassInstance() =
    executorService.submit(MyJob()).get()

When we run it, as we expect, it returns 42. (Tests are written in groovy, not in kotlin).
def 'should submit callable as class instance from kotlin'() {
    expect:
        callableExample.callableAsClassInstance() == 42
}

Casting to Callable

If we create map with string "call" to closure or just closure and try to cast to Callable, we always obtain CastClassException:
fun callableAsMap() =
    executorService.submit(mapOf("call" to { 42 }) as Callable<Int>).get()

fun callableAsClosure() =
    executorService.submit({ 42 } as Callable<Int>).get()
def 'should submit callable as closure from kotlin'() {
    when:
        callableExample.callableAsClosure() == 42
    then:
        thrown(ClassCastException)
}

def 'should submit callable as map from kotlin'() {
    when:
        callableExample.callableAsMap() == 42
    then:
        thrown(ClassCastException)
}

It does not work as in groovy...

Pass instance method

So maybe passing an instance method which produces value will work?
private fun callMe() = 42

fun callableAsPassedFunction(): Int? {
    return executorService.submit(::callMe).get()
}

It does not even compile. Why? It moans that there is no submit method which could be called with such argument...

But, what interesting, if we create a value to which we assign closure and pass it to submit method then everything is ok and get returns 42.
private val callMe = { 42 }

fun callableAsPassedLocalFunction(): Int? {
    return executorService.submit(callMe).get()
}

Inline implementation

Of course, there is also an option to create Callable inline:
fun callableAsInlineImplementation() =
    executorService.submit(Callable<Int> { 42 }).get()

And this is IHMO the best and the most comfortable way to create Callable in kotlin, because its syntax is much nicer than in java or groovy.

Source code is available here.

2015-09-20

Easy configuration usage with ConfigSlurper

What's the problem?


We have to deal with properties in almost every projects that we write. Properties class, which we use in these cases, is just mapping key to value. Sometimes it is fine, but in many cases properties look like tree. Example of properties file is shown below:

systemName=test
endpoint.first.protocol=http
endpoint.first.address=localhost
endpoint.first.port=8080
endpoint.first.path=test
endpoint.second.protocol=ftp
endpoint.second.address=localhost
endpoint.second.port=21
endpoint.second.user=admin
endpoint.second.password=pass

Here we have simple properties like systemName and also complex endpoints definition (all properties which start with endpoint) and single endpoints definition (each endpoint properties starts with endpoint.<ENDPOINT_NAME>).

How simple could it be to treat this properties like a tree and simply extract subset of them?

The answer is using ConfigSlurper.

ConfigSlurper from properties


To use ConfigSlurper just parse properties object:

def 'should import configuration from properties'() {
    given:
        Properties p = new Properties()
        p.load(ConfigSlurperTest.getResourceAsStream('/configuration.properties'))
    expect:
        new ConfigSlurper().parse(p).systemName as String == 'test'
}

Parse method returns ConfigObject which is just very clever map Map.

Now you could get property using dot notation:

def 'should get nested property'() {
    expect:
        fromProperties.endpoint.first.protocol == 'http'
}

But there is a deal. If you use ConfigObject then you cannot use it like normal Properties and get property with dots.

def 'should not used nested property as one string'() {
    expect:
        fromProperties.'endpoint.first.protocol' != 'http'
}

ConfigObject allows you to extract subtree as Properties:

def 'should get first endpoint info from properties'() {
    expect:
        fromProperties.endpoint.first.toProperties() == [
            protocol: 'http',
            address : 'localhost',
            port    : '8080',
            path    : 'test'
        ]
}

and even:

def 'should allow for nested property as one string when toProperties called'() {
    expect:
        fromProperties.endpoint.toProperties()['first.protocol'] == 'http'
}

If you want to know how many endpoint you have and how they are named you could use keySet method:

def 'should get list of endpoints'() {
    expect:
        fromProperties.endpoint.keySet() == ['first', 'second'] as Set
}

ConfigSlurper do not return null even if property is not found, so you could get nested property without fear:

def 'should not throw exception when missing property'() {
    expect:
        fromProperties.endpoint.third.port.toProperties() == [:] as Properties
}

You have only to be careful, when have property named like begining of another property:

def 'should throw exception when asking for too nested property'() {
    when:
        fromProperties.endpoint.first.port.test
    then:
        thrown(MissingPropertyException)
}

fromProperties.endpoint.first.port returns String and do not have test property.

You could also print properties from ConfigObject:

println fromProperties.prettyPrint()

The output looks like this:

endpoint {
    first {
        path='test'
        port='8080'
        protocol='http'
        address='localhost'
    }
    second {
        password='pass'
        protocol='ftp'
        address='localhost'
        port='21'
        user='admin'
    }
}
systemName='test'

Hmm... It looks like DSL. Why do not keep your configuration in this manner?

ConfigSlurper from script

Your configuration could be a groovy script.

systemName = 'test'
endpoint {
    first {
        path = 'test'
        port = 8080
        protocol = 'http'
        address = 'localhost'
    }
    second {
        password = 'pass'
        protocol = 'ftp'
        address = 'localhost'
        port = 21
        user = 'admin'
    }
}
test.key = ['really': 'nested?'] as Properties

You could pass such configuration as resource stream or file content:

def 'should get config from script as url'() {
    given:
        ConfigObject config = new ConfigSlurper().parse(ConfigSlurperTest.getResource('/configuration.groovy'))
    expect:
        config.systemName == 'test'
}

def 'should get config from script as string'() {
    given:
        ConfigObject config = new ConfigSlurper().parse(ConfigSlurperTest.getResource('/configuration.groovy').text)
    expect:
        config.systemName == 'test'
}

What interesting all your properties do not have to be strings. It could be any object: String, long, int, etc.

def 'should get nested properties from script as int'() {
    expect:
        fromScript.endpoint.first.port == 8080
}

def 'should get really nested properties from script and continue digging'() {
    expect:
        fromScript.test.key.really == 'nested?'
}

Conclusion

You could deal with properties like simple Map, but why if you could instead use it like tree of properties?

Sources are available here.

2015-09-07

Groovy, Callable and ExecutorService

Suppose you want submit job to ExecutorService.

The Baroque version

You could create a class that implements Callable:
class MyJob implements Callable<Integer>{
    @Override
    Integer call() throws Exception {
        return 42
    }
}

and give it to the executor service:

def 'submit callable as MyJob object'() {
    expect:
        executorService.submit(new MyJob()).get() == 42
}

The response is, as expected, 42.

Map as Callable version

You want to use this job only in one place so why not inline this class:
def 'submit callable as map'() {
    expect:
        executorService.submit([call: { 42 }] as Callable).get() == 42
}

The response is again 42.

Groovy closure version

Why not use closure instead of map?
def 'submit callable as closure'(){
    expect:
        executorService.submit { 42 }.get() == 42
}

The response is ... null.

Condition not satisfied:
executorService.submit { 42 }.get() == 42
|               |             |     |
|               |             null  false
|               java.util.concurrent.FutureTask@21de60b4
java.util.concurrent.Executors$FinalizableDelegatedExecutorService@1700915

Why? It is because Groovy treats this closure as Runnable, not Callable and Future#get returns null when task is complete.

Groovy closure version with cast

We have to cast our closure before submiting to executor service:
def 'submit callable as closure with cast'() {
    when:
        int result = executorService.submit({ return 42 } as Callable<Integer>).get()
    then:
        result == 42
}

The response is, as expected, again 42.

What interesting, the same test with inlined result variable fails... Strange... It could be Spock framework error.

Source code is available here.

2015-09-06

Writing JAXB in Groovy

Suppose you want write a jaxb class in groovy. Why? Because you do not have to write these all getters, setters and other methods. You only have to write your fields down.

@XmlRootElement
@HashCodeAndEquals
@ToString
class Person {
 String firstName
 String lastName
 Integer age
}


Lets check if we could unmarshal xml to Person class:

def 'should unmarshall person xml to object'(){
    given:
        JAXBContext jc = JAXBContext.newInstance(Person)
        String xml = 'JohnSmith20' 
    expect:
        jc.createUnmarshaller().unmarshal(new StringReader(xml)) == new Person(firstName: 'John', lastName: 'Smith', age: 20)
}


When we try this, then we obtain an eception:

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
groovy.lang.MetaClass is an interface, and JAXB can't handle interfaces.
 this problem is related to the following location:
  at groovy.lang.MetaClass
  at public groovy.lang.MetaClass com.blogspot.przybyszd.jaxbingroovy.Person.getMetaClass()
  at com.blogspot.przybyszd.jaxbingroovy.Person

 at com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:91)
 at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:445)
 at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:277)
 at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:124)
 at com.sun.xml.internal.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1123)
 at com.sun.xml.internal.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
 at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:247)
 at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234)
 at javax.xml.bind.ContextFinder.find(ContextFinder.java:462)
 at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)
 at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:584)
 at com.blogspot.przybyszd.jaxbingroovy.PersonJaxbTest.should unmarshall person xml to object(PersonJaxbTest.groovy:10)



It is because groovy defines getMetaClass method for us. Marshaller and Unmarshaller use by default XmlAccessType.PUBLIC_MEMBER what means that public getters and setters should be used during marshalling/unmarshalling.

To solve this just add XmlAccessorType annotatnio with XmlAccessType.FIELD on jaxb class:

@XmlRootElement
@EqualsAndHashCode
@XmlAccessorType(XmlAccessType.FIELD)
class Person {
    String firstName
    String lastName
    Integer age
}


Of course if you want to apply this rule for each jaxb class in package, then you could put XmlAccessorType in pacakge-info.java file.

@XmlAccessorType(XmlAccessType.FIELD)
package com.blogspot.przybyszd.jaxbingroovy;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;


Great, it works.

Now let's check out marshaller:


def 'should marshall person'() {
    given:
        JAXBContext jc = JAXBContext.newInstance(Person)
        Person p = new Person(firstName: 'John', lastName: 'Smith', age: 20)
        StringWriter sw = new StringWriter()
    when:
        jc.createMarshaller().marshal(p, sw)
    then:
        String xml = sw.toString()
        GPathResult gPathResult = new XmlSlurper().parseText(xml)
        gPathResult.name() == 'person'
        gPathResult.firstName == 'John'
        gPathResult.lastName == 'Smith'
        gPathResult.age == '20'
}


And it also works.

Source is available here.

2015-08-16

All field constructor in Groovy

TupleConstructor annotation in Groovy generate constructors for class with each of its properties (eventually also fields). The class below

@TupleConstructor(includeFields = true)
class Person {
   String firstName
   String lastName
   private boolean male
}

will have constructors: Person(), Persion(String), Person(String, String) and Person(String, String, boolean). You could test it using code below.

class TupleConstructorTest extends GroovyTestCase{
    @Test
    void testSimpleTupleConstructorShouldGenerateConstructor() {
        assertScript '''
            import groovy.transform.TupleConstructor
            @TupleConstructor(includeFields = true)
            class Person {
                private final String firstName
                private final String lastName
                private final boolean male
                String toString(){ "$firstName $lastName $male" }
            }

            assert Person.constructors.size() == 4

            assert new Person().toString() == 'null null false'
            assert new Person('John').toString() == 'John null false'
            assert new Person('John','Smith').toString() == 'John Smith false'
            assert new Person('John','Smith', true).toString() == 'John Smith true'
        '''
    }
}

I almost always create classes with all private final fields and generate constructior with all fields using my IDE.

So I have prepared new transformation AllFieldConstructor which bases on TupleConstructor and generates only constructor with all fields as parameters.

class AllFieldConstructorTest extends GroovyTestCase{
    @Test
    void testSimpleTupleConstructorShouldGenerateConstructor() {
        assertScript '''
            import com.blogspot.przybyszd.transformations.AllFieldConstructor
            @AllFieldConstructor
            class Person {
                private final String firstName
                private final String lastName
                private final boolean male
                String toString(){ "$firstName $lastName $male" }
            }

            assert Person.constructors.size() == 1

            assert new Person('John','Smith', true).toString() == 'John Smith true'
        '''
    }
}

The sources are available here

2015-06-04

Git aliases for better Gerrit usage

What is Gerrit?

Gerrit is a web application for code review and git project management. You push commit to specific ref in Gerrit and your collaborators could comment your code, give you a score (-2, -1, 0, 1, 2) or merge it with specific branch. Gerrit generates also events, so yout CI server (for example Jenkins) could start build based on this commit and give the positive score if build is green or negative if it fails.

Pushing commits to gerrit

If you want to push commit to gerrit, then commit has to have generated Change-Id, which is uniq review identifier. You do not need to generate Change-Id on your own, because you could install pre-commit hook from Gerrit:

gitdir=$(git rev-parse --git-dir); scp -p -P <GERRIT_PORT> <GERRIT_SSH>:hooks/commit-msg ${gitdir}/hooks/

Of course, you have to set GERRIT_PORT and GERRIT_SSH to point to yout Gerrit.

To push a commit for review you should use command:

git push origin HEAD:refs/for/<BRANCH_NAME>

It means that your current HEAD should be pushed to remote reference on origin (if Gerrit remote repository is named as origin). BRANCH_NAME is the remote branch with which your code will be compared and to which your commit should be merged (if it pass review).

You often push to master so there is alias to push as review for master in alias section in ~/.gitconfig (globally) or .git/config (only in current repository):

[alias]
  ...
  push-for-review = push origin HEAD:refs/for/master
  ...

To execute it just type:

git push-for-review

If I want to push as review to another branch then I use another alias:

[alias]
  ...
  push-for-review-branch = !git push origin HEAD:refs/for/$1
  ...

and branch name could be pass as argument from command line:

git push-for-review-branch <BRANCH_NAME>

Pushing drafts

If you think that your commit is not ready to merge with remote branch, but you want to share it or just have it in remote repository, you could push it to draft reference. Draft on gerrit is available only for you and other users which are invited by you. Draft could be pushed via command:

git push origin HEAD:refs/drafts/<BRANCH_NAME>

Branch name must be given, because draft could be published and then merged, so branch have to be known before.

There also are simple aliases, which could be used in the same way as during push for review:

[alias]
  ...
  push-as-draft = push origin HEAD:refs/drafts/master
  push-as-draft-branch = !git push origin HEAD:refs/drafts/$1
  ...

Invite for review

After pushing for review or draft you could invite user or group, then they will be notified by Gerrit about new change. To invite from command line there should be added four aliases:

[alias]
  ...
  gerrit-remote = "!sh -c \"git remote -v | grep push | grep ssh | grep gerrit | head -1 | awk '{print $2}' | cut -d'/' -f3\""
  gerrit-host = "!sh -c \"git gerrit-remote | cut -d':' -f1\""
  gerrit-port = "!sh -c \"git gerrit-remote | cut -d':' -f2\""
  gerrit-invite = "!sh -c \"ssh -p `git gerrit-port` `git gerrit-host` 'gerrit set-reviewers --add' $1 `git log | grep Change-Id | head -1 | tr -d ' ' | cut -d':' -f2`\""
  ...

First alias selects remote repository which contains gerrit in name or url, could be used to push via ssh and extracts url to this repository.

Second and third alias uses the first to extract host and port from repository url. It is necessary for executing remote command via ssh.

The last alias extract Change-Id from HEAD and add user or group given form command line. Example usage:

git gerrit-invite <USER_OR_GROUP> 

Summary

Gerrit is a great tool for git management and code reviewing, but it is difficult to type all references by memory. Git aliases described here are great support and simplify Gerrit usage.

2015-03-29

All you need is docker (and fig)

Introduction

Suppose you want to run scala repl or groovy shell or any other repl-like executable. You should download executable, unpack it, set PATH environmnt variable and now you could use it. Can it be simple? Yes, dockerize everything.

Prepare containers

I expect that you have installed docker and fig on your machine.
Checkout this project from github and build containers:

$ cd docker-with-fig
$ fig build 

It could take several minutes, depends on your internet connection.

You could also build only some of available container, for example with scala and groovy:
$ fig build scala groovy

Available containers are:
  • haskell
  • scala
  • groovy
  • python27
  • python34
  • clojure

Run containers

Now you could start for example scala:
$ fig run scala
Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_40).
Type in expressions to have them evaluated.
Type :help for more information.

scala>

Or groovy:
$ fig run groovy
Mar 29, 2015 7:48:22 AM java.util.prefs.FileSystemPreferences$1 run
INFO: Created user preferences directory.
Groovy Shell (2.4.2, JVM: 1.8.0_40)
Type ':help' or ':h' for help.
-------------------------------------------------------------------------------
groovy:000>

Or clojure with lein:
$ fig run clojure
nREPL server started on port 52730 on host 127.0.0.1 - nrepl://127.0.0.1:52730
REPL-y 0.3.5, nREPL 0.2.6
Clojure 1.6.0
Java HotSpot(TM) 64-Bit Server VM 1.8.0_40-b25
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)
 Results: Stored in vars *1, *2, *3, an exception in *e

user=>

Or python 3.4:
$ fig run python34
Python 3.4.2 (default, Oct  8 2014, 13:08:17) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Or ghci haskell:
$fig run haskell
GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude>

You could also run command on docker container with use of files from your current directory because it is mapped to /project directory on docker. Container starts with /project directory as current directory.
For example you have a simple file in your current dir:
$ cat simplePrint.scala 
println("Hello World")

You could run command with this file:

$ fig -f PATH_TO_DOCKER_WITH_FIG_PROJECT/fig.yml run scala scala simplePrint.scala
Hello World

First 'scala' in command means that you want to run scala container and 'scala simplePrint.scala' means that you want to execute this command on container.

Conclusion

It is simple, isn't it? All you need is docker and fig and you could use repl or run command with scala, groovy, cojure and any other which are currently supported...