Archive

Archive for the ‘Technical’ Category

GitLab, the overlooked Git solution in the cloud

April 25th, 2016 7 comments

When one thinks about hosting one’s Git repository online, one’s first choice is just Github, no questions asked. It’s so successful that it has become the de facto standard of Git solutions in the cloud. It’s so well-entrenched that developers are advised to use it as their portfolio. At first glance, Github has it all: public repositories, group collaboration, metrics, page hosting, on-premise install option, etc.

Major players host their Open-Source code on Github: Spring, Netflix, Google, SAP, etc. I’m also a huge Github user. I use it to share my code for my blog article and also when speaking at conferences when live-coding. Another great feature of Github is Github Pages. For those not familiar with Pages, it’s a great way to host your static – or Markdown-based, websites. In the later case, Github takes automatically care of the Markdown – HTML conversion. Here’s an example of mine: the Github repository and its child moorevaadin.com website.

However, I found myself more and more frustrated with Github’s limitations. I’m not complaining since I don’t pay anything but stating a fact. It started very simply: non-paying users can only have public repositories, yet, sometimes, I need to host code that I don’t want to keep to myself. For that, I used Atlassian’s Bitbucket. Non-paying users of Bitbucket enjoy 5 private repositories. That’s not a lot, but that was enough for my needs.

Recently, I needed to host another blog on Github Pages. However, I wanted it to use Asciidoctor format instead of Markdown. I’ve used Markedown exclusively for my last book and it has nothing regarding linking to code snippets. Basically, it’s just copy-paste and you have to keep everything in sync yourself. On the contrary, Asciidoctor has such a feature, either by line-number or by tagging in the original source code. Good news, Asciidoctor offers a Jekyll plugin. Bad news, this isn’t supported by Github out-of-the-box. Github will render Asciidoctor files in HTML when browsing Github but will not generate the website as with Markdown.

Of course, there are workarounds – or to be specific, at least one that I know of. As the Github Pages build is private, you can plug in the Travis build tool and hack around it. I stumbled upon this article that describes how to do it. As you can see, this unfortunately is not trivial. I was really disappointed to have to sign in to Travis just to achieve that and started looking for alternatives.

It didn’t take me long to find GitLab, another Git cloud solution. Where Github needs a dedicated third-party build tool, GitLab has its own tool, fully integrated. Even better, generation of the site just takes this very short file:

And this week, I just discovered that Github cannot protect branches – especially master, against direct pushes. What it can do is prevent force pushes and/or check for a number of build statuses before merging. However, Gitlab offers that option. Finally, it also provides unlimited private repositories for an unlimited of users.

Probably, there are many more options to explore on GitLab. Be sure I’ll do that in the following weeks. And I’d advise you to do that too, you might find something missing in more well-known solutions.

Send to Kindle
Categories: Technical Tags: , , ,

Code improvements with Kotlin

April 17th, 2016 2 comments

This week, I tried to improve my pet Android application developed in Kotlin. As I was very new to Kotlin when I started it, most of the code just looks like Java written in Kotlin.

Starting simple

Here’s one such snippet, that needs to initialize both a template message and its argument:

val messageTemplate: String
val params: Array
when (shownCount) {
	0 -> {
		messageTemplate = noItem
		params = arrayOf()
	}
	1 -> {
		messageTemplate = itemShowSingle
		params = arrayOf(totalCount)
	}
	else -> {
		messageTemplate = itemShowCount
		params = arrayOf(shownCount, totalCount)
	}
}
Pair
Kotlin versions after M3 don’t offer Tuple anymore, but specialized versions like Pair and Triple in the stdlib. Also, the to() extension function can create such pairs on the fly, without resorting to the constructor.
Destructuring declarations
Kotlin allows to initialize multiple variables at once when the function returns a Pair, a Triple or any data class for that matter.

This is the new improved code:

val (messageTemplate, params) = when (shownCount) {
	0 -> noItem to arrayOf()
	1 -> itemShowSingle to arrayOf(totalCount)
	else -> itemShowCount to arrayOf(shownCount, totalCount)
}

stdlib also known as Kotlin’s toolbelt

A common task in Android is to send data to the SQLite database through ContentValues instances. Naive Java ports look like the following snippet:

val taskValues = ContentValues()
taskValues.put(T_NAME_COL, task.name)
taskValues.put(T_DESC_COL, task.description)
taskValues.put(T_PRIO_COL, task.priority)
taskValues.put(T_DONE_COL, if (task.done) 1 else 0)
taskValues.put(T_LIST_COL, list.id)
if (task.imagePath != null) {
	taskValues.put(T_IMG_COL, task.imagePath.toString())
}

Kotlin’s stdlib provides a number of interesting functions.

apply()
apply() is an extension function set on Any type. It accepts a null-returning function as a parameter, applies it to the receiver and return the later. Note that in the scope of the lambda, this is the receiver.

let()
let() is another extension function set on Any type. It accepts a transforming function as a parameter and calls it with the receiver as the parameter.

Null-safe call operator
The .? operator will only called the right-hand operand if the left-hand operand is not null. It’s Kotlin’s idiomatic way for null checking

Using them in combination gives the following code:

val taskValues = ContentValues().apply {
	put(T_NAME_COL, task.name)
	put(T_DESC_COL, task.description)
	put(T_PRIO_COL, task.priority)
	put(T_DONE_COL, if (task.done) 1 else 0)
	put(T_LIST_COL, list.id)
	task.imagePath?.let { put(T_IMG_COL, it.toString()) }
}

Going further

Another common Android task it to read data stored in UI components:

val id = nameView.tag as Long?
if (id != null) {
	task.id = id
}
Safe cast
Casts are handled in Kotlin with the as operator. However, nullable and non-nullable types don’t belong to the same hierarchy. Hence, if one casts null to a non-nullable type, a ClassCastException will be thrown at runtime. To avoid that, us the as? smart cast operator.

Using let() and the .? operator in conjunction with smart cast produces the next improvement:

(nameView.tag as? Long)?.let { task.id = it }

The whole shebang

The final common snippet is related to querying SQLite databases. Basically, the usual flow is to create the object, create the cursor, iterate over it to read values and set object’s attributes from them. It looks like this:

fun findById(id: Long): Task {
	val cursor = readableDatabase.rawQuery("SELECT A LOT FROM TABLE", arrayOf(id.toString()))
	cursor.moveToFirst()
	val name = cursor.getString(1)
	val description = cursor.getString(2)
	val imagePath = cursor.getString(3)
	val task = Task(name, description)
	if (!cursor.isNull(4)) {
		val date = cursor.getLong(4)
		task.alarm = Date(date)
	}
	cursor.close()
	task.id = id
	if (imagePath != null) {
		task.imagePath = Uri.parse(imagePath)
	return task
}
Local functions
Methods in Java are about visibility and scoping. Basically, if one wants a method not reused in other classes, one sets the private visibility. If this method is used only in another method, it just pollutes the class namespace. Embedded functions are a way to declare a function inside another one to avoid this pollution. Kotlin (as well as Scala) allows that.
with()
Another useful function from stdlib is with(). Available on any type, it takes 2 parameters: the first is the receiver, the second a transforming function and calls the later on the former.

Combining those with some of the above features can improve the code a lot:

 fun findById(id: Long): Task {

	fun toTask(cursor: Cursor): Task {
		with(cursor) {
			moveToFirst()
			val name = getString(1)
			val description = getString(2)
			val imagePath = getString(3)
			return Task(name, description).apply {
				if (!isNull(4)) {
					val date = getLong(4)
					val alarm = Date(date)
					this.alarm = alarm
				}
				this.id = id
				imagePath?.let { this.imagePath = Uri.parse(it) }
				close()
			}
		}
	 }

	return readableDatabase.rawQuery(
			"SELECTA LOT FROM TABLE",
			arrayOf(id.toString())).let { toTask(it) }
}

Conclusion

Learning a new programming language is easy: many books promise to do that in 21 days. The hard part is how to write idiomatic code in that new language. This is a long and arduous journey, that needs a lot of reading such idiomatic code, writing “bad” code yourself and improving it over the course of many iterations.

To go further:

Send to Kindle
Categories: Development Tags: ,

Maze-walking algorithm

April 10th, 2016 2 comments

Last week, a colleague pointed out to my team an online developer recruitment challenge. As I find it fun and there was no need to disclose one’s email, I decided to try, just to check if I could to it.

The problem is quite simple but not easy: consider a rectangular maze of finite size. One has to find a specific cell on the board – the exit, starting from the origin. One has 2 move options: one cell at a time in one of the 4 cardinal points or jumping to any previously visited cell. Of course, it wouldn’t be a maze if there was no obstacle: each cell provides information on the 4 adjacent cells, whether it’s unvisited, blocked by a wall or already explored. There’s one final constraint: each maze is alive for a finite amount of time. If the end cell is not reached after the timeout, it’s a failure.

After reading the page dedicated on maze solving algorithms on Wikipedia, I decided to implement the wall follower. It’s very simple, basically, you always follow the left (or right) wall.

My first implementation did just that. The problem with this solution is once a dead end has been reached – a cell with one visited direction and all other blocked, one has to move back again cell by cell. This implementation always failed because of the timeout.

I tried to be smarter for my second try. Instead of going back cell by cell, I thought about jumping to the last cell which offered a choice between at least 2 unexplored adjacent cells. In order to do that, I put such cells on a stack when I moved in one. When in a dead end, I just need to pop the top cell on the stack and jump to it in one single move. It’s queried again and updated as one less direction is considered unexplored and the process continues.

It happened to be a good enough solution: I succeeded 2 times (and failed a few times too), got both the secret message and the URL of the page you could apply to. Too bad, it’s in Canada but it was fun. To make it even more fun, I developed in Kotlin with the Fuel library.

Send to Kindle
Categories: Development Tags:

Experimental: Kotlin and mutation testing

April 3rd, 2016 1 comment

Since about a year and a half, I do a lot of presentations on Mutation Testing. In those, my point is to show that Code Coverage‘s only benefit is that it’s easy to compute but that it’s meaningless – hence Mutation Testing.

Since some time, I’ve been interested in Kotlin, a language from JetBrains that runs on the JVM. It’s only natural that I wanted to check how Mutation Testing could be applied to the Kotlin language. As Kotlin is too young to have its own dedicated mutation testing tool, I used Pit, a Java dedicated tool. I didn’t expected much, here are my findings.

I started with a Kotlin-port of my demo project. It has two simple classes and an associated test for each. In the first one, assertion is missing and in the second, the boundary condition of the < operator is not tested. This is the perfect use-case for Mutation Testing. It’s a Maven project, so the command is quite straightforward:

mvn org.pitest:pitest-maven:mutationCoverage

Interestingly enough, this works perfectly well, in terms of mutation coverage execution, but also regarding referencing the lines that are the source of the problem.


I wanted to go further, to use a real project. The Kotlin folks were kind enough to redirect me to KTor, a Kotlin-based web framework. I tried the same command, but limited on a single module – ktor-features/ktor-server-sessions (I have no clue what it does, that is not relevant anyway). Aye, there’s the rub.

First, Pit cannot correctly parse the generated bytecode at some places:

PIT >> WARNING : Found more than one mutation similar on same line in a finally block. Can't correct for inlining.

Worse, there are a lot of timeout errors. Since there’s some threading involved, that’s not really a blocker.

PIT >> WARNING : Slave exited abnormally due to TIMED_OUT

For this project, reports are really long, but some errors are really similar to what you’d expect from Java code, for example:

removed call to kotlin/jvm/internal/Intrinsics::checkParameterIsNotNull → NO_COVERAGE

Here’s a sample of the report:

Again, Pit is able to bind the real lines to the problems found. Isn’t life good? If you stop at this point, it probably is. But running Pit on another project – say, ktor-features/ktor-locations fails miserably.

The class org.jetbrains.ktor.locations.Locations$WhenMappings does not contain a source debug information. All classes must be compiled with source and line number debug information

It seems using the when construct in Kotlin generates an inner class that doesn’t contain debug information, which Pit need to works its magic. Let’s exclude the offending class and its inner mappings class:

mvn org.pitest:pitest-maven:mutationCoverage -DexcludedClasses=org.jetbrains.ktor.locations.Locations*

It works again and produces expected results:

There are no mutation testing tools for Kotlin (yet), and considering Java ecosystem’s history, there might never be one. However, mutation testing is an invaluable tool to assert the real quality of your tests. Even if Pit is not a perfect match for Kotlin, it would be foolish to discard it.

Send to Kindle
Categories: Development Tags: , ,

Feedback on customizing Vaadin HTML template

March 28th, 2016 No comments

Last week, my post was about how you could customize the default Vaadin HTML template so you could add a lang attribute for example. I didn’t ask for feedback, but I got it anyway, so let’s use the occasion to analyze it.

First, I must admit that my solution was not Vaadin-esque as I used AOP to get the job done. My friend Matti Tahvonen from the Vaadin team was kind enough to provide not only one but 2 alternatives to my proposal. Thanks Matti!

Alternative solutions

The first solution – also the one I got the last, was submitted by AMahdy AbdElAziz:

Evil but it works and couldn’t be simpler!

The second solution uses Matti’s own framework – Viritin, to achieve that. I haven’t looked at the framework yet (but it’s in my todo list) so I cannot comment it but here is the snippet:

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

However, this one I can analyze and comment 🙂

Flow decomposition

Note: readers who are more interested in possoble improvements can skip directly to that section.

The first part is quite easy. It just registers a new SessionInitListener (the proposed code uses a lambda to do that):

The second part happens when a request is made and Vaadin notices a new session must be created:

The end of the previous sequence diagram is designed in a generic way in Vaadin. In our specific case, it’s rendered as such:

Improvements

I think a couple of improvements can be made.

  • The code is awfully verbose – even using Java 8’s lambda
  • Two objects are created each time a session is initialized, the session listener and the bootstrap listener
  • Setting the servlet class as an internal class of the UI sends shiver down my spine. Though I understand this is a Gist, this is unfortunately what you get by using the Vaadin Maven archetype. This is very far from the Single-Responsibility Principle.

Since my initial example uses both Spring Boot and Kotlin, here’s my version:

With Spring Boot, I can manage the SessionInitListener as a singleton-scoped Bean. By passing it as a servlet parameter, I can create only a single instance of SessionInitListener and BootstrapListener each. Of course, it’s only possible because the language value is set in stone.

Thanks to Kotlin, I co-located the overriden servlet class within the configuration file but outside the configuration class. Since the servlet is used only by the configuration, it makes sense to put them together… but not too much.

Finally, note that SessionInitListener is a functional interface, meaning it has a single method. This single method is the equivalent of a function taking a SessionInitEvent and return nothing. In Kotlin, the signature is (SessionInitEvent) -> Unit. Instead of creating an anonymous inner class, I preferred using the function. It’s not an improvement, but a more functional alternative. At runtime, both alternatives will allocate the same amount of memory.

The complete source code can be found on Github in the manage-lang branch.

Send to Kindle
Categories: JavaEE Tags: ,

Customizing Vaadin HTML template

March 20th, 2016 2 comments

This week, I had an interesting question on Twitter: “How in Vaadin do you add a lang attribute to the html element?”, like this:

<html lang="fr">

While it’s quite easy to customize individual components on the page, the outer html tag is outside our control. In this article, I’ll describe a possible solution to this problem. Note that I think this is too specialized for morevaadin.com. However, this should still be my reference site for all things Vaadin.

My first (wrong) thought, was that the html element is generated by the UI widget client-side. It’s not the case – as there’s no such widget. In order to find the answer, I had to understand how the framework works. Here’s a short summary of the sequence when one makes a request to a Vaadin application.

Basically, the Vaadin Servlet delegates to the Vaadin Service. In turn, the service loops over its internal list of Request Handlers until one of them is able to handle the request. By default, the Vaadin Service registers the following handlers:

  1. ConnectorResourceHandler
  2. UnsupportedBrowserHandler: returns a specific message if the browser is not supported by Vaadin
  3. UidlRequestHandler: handles RPC communication between client and server
  4. FileUploadHandler: handles file uploads achieved with the FileUpload component
  5. HeartbeatHandler: handles heartbeat requests
  6. PublishedFileHandler
  7. SessionRequestHandler: delegates in turn to request handlers that have been registered in the session

This is implemented in VaadinService.createRequestHandlers(). However, notice that VaadinService is abstract. There’s a subtle changed introduced in the concrete VaadinServletService subclass that is used. It registers a new request handler – the ServletBootstrapHandler, in order for Vaadin to run transparently in both a servlet and a portlet context. In this later case, only a fragment :

The servlet boostrap handler is responsible to generate the initial HTML page at the start of the application, including the desired outer html tag. Next requests to the application will just update part of the page via AJAX, but the outside HTML won’t change. Thus, this is the class that needs to be updated if one wishes to add a lang attribute. A quick glance at the class makes it very clear that it’s quite hard to extend. Besides, it delegates HTML generation to the JSoup and more precisely to the Document.createShell() static method.

At this point, you have 3 options:

  1. Forget about it, what is it worth anyway?
  2. Rewrite a large portion of the BootstrapHandler and add it before the BootstrapHandler in the handlers sequence
  3. Be lazy and apply Ockham’s razor: just use a simple AOP‘s aspect

In order to be of any use, I chose the latest option. It’s quite straightforward and very concise, you only need the following steps.

Create the aspect itself. Note that I’m using Kotlin to be coherent with the existing project but Java or any other JVM-based language would be the same.

@Aspect
open class UpdateLangAspect {

    @Pointcut("execution(static * org.jsoup.nodes.Document.createShell(..))")
    fun callDocumentCreateShell(): Unit {}

    @AfterReturning(pointcut = "callDocumentCreateShell()", returning = "document")
    fun setLangAttribute(document: Document): Unit {
        document.childNode(0).attr("lang", "fr")
    }
}

As the method to instrument is static, it’s not possible to use simple Spring proxies, but we need AspectJ class instrumentation via LTW. In order to activate it in Spring Boot, I just have to update the application.properties file:

spring.aop.proxy-target-class=true

Also, one has to tell Aspect’s weaver what needs to be instrumented in the META-INF/aop.xml:

<?xml version="1.0" encoding="UTF-8"?>
<aspectj>
  <aspects>
    <aspect name="ch.frankel.blog.bootvaadinkotlin.UpdateLangAspect" />
  </aspects>
  <weaver options="-XnoInline -Xlint:ignore -verbose -showWeaveInfo">
    <include within="org.jsoup.nodes.Document" />
    <include within="ch.frankel.blog.bootvaadinkotlin.UpdateLangAspect" />
  </weaver>
</aspectj> 

The first section is about the aspect, the second is about what classes need to be instrumented. Note that weaving section needs also to reference the aspect too.

Finally, one has to update the POM so that launching the application through the Spring Boot Maven plugin will also use the aspect.

<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
  <configuration>
    <agent>${settings.localRepository}/org/aspectj/aspectjweaver/1.8.8/aspectjweaver-1.8.8.jar</agent>
  </configuration>
</plugin>

For sake of completeness, the code is available on Github with the manage-langv1 tag.

At this point, generating the page will display the desired change. Job done!

Send to Kindle
Categories: JavaEE Tags: ,

Feedback on the Josephus problem

March 13th, 2016 1 comment

My last week article was about the solving the Josephus problem in Kotlin. For ease of comparison, here’s the version I wrote originally:

class Soldier(val position: Int) {
    var state = State.Living
    lateinit var next: Soldier
    fun suicide() {
        state = State.Dead
    }
    fun isDead() = state == State.Dead
}

enum class State {
    Living, Dead
}

class Circle(private val size: Int, private val step: Int) {

    private val first = Soldier(0)

    init {
        var person = first
        while (person.position < size - 1) {
            person = createNext(person)
        }
        val last = person
        last.next = first
    }

    private fun createNext(soldier: Soldier): Soldier {
        val new = Soldier(soldier.position + 1)
        soldier.next = new
        return new
    }

    fun findSurvivor(): Soldier {
        var soldier: Soldier = first
        var numberOfDead = 0
        while (numberOfDead < size - 1) {
            var count: Int = 0
            while (count < step) {
                soldier = nextLivingSoldier(soldier)
                count++
            }
            soldier.suicide()
            numberOfDead++
        }
        return nextLivingSoldier(soldier)
    }

    private fun nextLivingSoldier(soldier: Soldier): Soldier {
        var currentSoldier = soldier.next
        while (currentSoldier.isDead()) {
            currentSoldier = currentSoldier.next
        }
        return currentSoldier
    }
}

The post ended with an open question: was the code the right way to do it? In particular:

  • Is the code idiomatic Kotlin?
  • Lack of for means using while with vars
  • Too many mutability (var) for my own liking

I’ve received great feedback from the community on many different channels, including Ilya Ryzhenkov from JetBrains, Cédric Beust, Peter Somerhoff and Gaëtan Zoritchak. Thanks guys!

I think the most interesting is this one, very slightly modified from the original Gist by Gaëtan:

class Soldier(val position: Int, var state:State = State.Living) {
    fun suicide() {
        state = State.Dead
    }
    fun isAlive() = state == State.Living
}

enum class State {
    Living, Dead
}

class Circle(val size: Int, val step: Int) {

    val soldiers = Array( size, {Soldier(it)}).toList()

    fun findSurvivor(): Soldier {
        var soldier = soldiers.first()
        (2..size).forEach {
            (1..step).forEach {
                soldier = soldier.nextLivingSoldier()
            }
            soldier.suicide()
        }
        return soldier.nextLivingSoldier()
    }

   tailrec private fun Soldier.nextLivingSoldier():Soldier =
            if (next().isAlive())
                next()
            else
                next().nextLivingSoldier()

    private fun Soldier.next() = soldiers.get(
            if (position == size - 1)
                0
            else
                position + 1
    )
}

I like this code a lot because it feels more Kotlin-esque. Improvements are many.

  • The code is shorter without any loss of readability
  • It’s entirely functional, there’s only a single var involved:
    • the 2 while loops with their associated var counter have been replaced by simple forEach on Int ranges.
    • Chaining Soldier instances is not handled in the Soldier class itself through the next() method but by the containing Circle. Thus, a simple backing array can store them and there’s no need for custom code with mutable variables.
  • The recursive nextLivingSoldier() function has been “annotated” with tailrec in order for the compiler to run its optimization magic.
  • The Soldier class doesn’t know about its container Circle‘s size, so functions using it have been moved inside the Circle class as extension functions to the Soldier class. This is a great usage of Kotlin’s extension functions.

This experience reinforced my belief that learning a language by just reading about it is not enough. To truly make it yours, steps should be those:

  1. obviously, learn the syntax of the language – and its API,
  2. code a solution or an app with this language,
  3. ask for feedback,
  4. read, analyze and understand the feedback,
  5. rinse and repeat.
Send to Kindle
Categories: Development Tags: ,

Solving the Josephus problem in Kotlin

March 6th, 2016 2 comments

I recently stumbled upon a post telling about the Josephus problem and trying to solve it in different scripting languages. For the sake of brevity, here’s the problem (taken from the referenced post):

Flavius Josephus was a roman historian of Jewish origin. During the Jewish-Roman wars of the first century AD, he was in a cave with fellow soldiers, 40 men in all, surrounded by enemy Roman troops. They decided to commit suicide by standing in a ring and counting off each third man. Each man so designated was to commit suicide…Josephus, not wanting to die, managed to place himself in the position of the last survivor.

In the general version of the problem, there are n soldiers numbered from 1 to n and each k-th soldier will be eliminated. The count starts from the first soldier. What is the number of the last survivor?

It seemed like a good challenge to test my building Kotlin skills. Here’s the solution I’ve come up with. First, the test class, using TestNG and a data provider – it’s the perfect use-case:

class JosephusTest {

    @DataProvider
    fun data(): Array<Array<Int>> {
        return arrayOf(
                arrayOf(2, 1, 0),
                arrayOf(3, 1, 0),
                arrayOf(10, 1, 0),
                arrayOf(3, 2, 0),
                arrayOf(4, 2, 1)
        )
    }

    @Test(dataProvider = "data")
    fun circle_of_size_and_step_should_survive_position(size: Int, step: Int, expectedPosition: Int) {
        val circle = Circle(size, step)
        val survivor = circle.findSurvivor()
        assertEquals(survivor.position, expectedPosition)
    }
}

Now, the code:

class Soldier(val position: Int) {
    var state = State.Living
    lateinit var next: Soldier
    fun suicide() {
        state = State.Dead
    }
    fun isDead() = state == State.Dead
}

enum class State {
    Living, Dead
}

class Circle(private val size: Int, private val step: Int) {

    private val first = Soldier(0)

    init {
        var person = first
        while (person.position < size - 1) {
            person = createNext(person)
        }
        val last = person
        last.next = first
    }

    private fun createNext(soldier: Soldier): Soldier {
        val new = Soldier(soldier.position + 1)
        soldier.next = new
        return new
    }

    fun findSurvivor(): Soldier {
        var soldier: Soldier = first
        var numberOfDead = 0
        while (numberOfDead < size - 1) {
            var count: Int = 0
            while (count < step) {
                soldier = nextLivingSoldier(soldier)
                count++
            }
            soldier.suicide()
            numberOfDead++
        }
        return nextLivingSoldier(soldier)
    }

    private fun nextLivingSoldier(soldier: Soldier): Soldier {
        var currentSoldier = soldier.next
        while (currentSoldier.isDead()) {
            currentSoldier = currentSoldier.next
        }
        return currentSoldier
    }
}

This code works fine and the tests are successful.

However, while trying to code the solution, I realized that there were no data-structure implementing circular linked lists neither in Java nor in Kotlin. I had thus to implement my own circular data-structure, but without implementing common collection features.

Now, my problem with the above code is that while the Soldier class looks fine by me, the Circle class doesn’t. There are too many vars in Circle and it feels too much like imperative programming. The lack of for(;;) in Kotlin forces me to use a while with an outside variable – twice: count and numberOfDead.

I’ve been thinking that I could improve the situation by changing the data-structure. I just don’t know how… Now, Kotlin and FP gurus, do you have any proposal?

Send to Kindle
Categories: Development Tags: ,

Log management in Spring Boot

February 21st, 2016 1 comment

Logging is for sure not a glamorous subject, but it’s a critical one – at least for DevOps and Ops teams. While there are plenty of material on the Web describing how to change your ASCII banner, there is not much on how to efficiently manage the log output.

By default, Spring Boot will output log on the console and not use any file at all.

However, it’s possible to tell Spring Boot to log in an output file. At the simplest level, the path where Spring Boot will put the spring.log file can be easily configured in the application.properties under the logging.path key:

logging.path=/var/log

Note that another alternative is to use the logging.file key in order to not only set the file path but also the file name.

logging.file=/var/log/myapp.log

While this works very well for development purposes, it’s not an acceptable process for the Ops team to unzip the final jar, update the application.properties file and repackage it – this for each and every different environment.

Spring Boot allows to override the value set in the packaged file (if any) on the command-line as a standard system property when launching the jar:

java -jar -Dlogging.path=/tmp  myapp.jar

Finally, it’s also possible to override this value when invoking the Spring Boot Maven plugin on the command line. However, directly using the system property doesn’t work for the plugin will spawn another JVM. One has to use the run.jvmArguments system property and delegate it the wanted value:

mvn spring-boot:run -Drun.jvmArguments="-Dlogging.path=/tmp"

Note that this works for every available property!

To go further:

Send to Kindle
Categories: Java Tags: ,

Designing your own Spring Boot starter – part 2

February 14th, 2016 2 comments

In the last post, I tried to describe the internal working of Spring Boot starter. It’s now time to develop our own!

As an example, we will use XStream, a no-fluff just-stuff XML/JSON (de)serializer offered by Thoughtworks. Readers who only use JAXB and Jackson are advised to have a look at XStream, it’s extremely efficient and its API is quite easy to use.

As seen in our last post, the entry-point of a starter lies in the META-INF/spring.factories file. Let’s create such a file, with the adequate content:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=ch.frankel.blog.xstream.XStreamAutoConfiguration

Now, let’s create the class referenced above. As we have seen previously, an auto-configuration class is just a regular configuration class. It’s ok to keep it empty for the time being.

@Configuration
public class XStreamAutoConfiguration {}

XStream is build around the aptly-named XStream class, which is an entry-point into its serialization features. Thoughtworks designed it to avoid static methods, so that you need an XStream instance. Creating an instance is a boring repetitive task with no value: it looks like it’s a perfect target for a Spring bean. Let’s create this instance in the auto-configuration class as a singleton bean so that client applications can use it. Our configuration class becomes:

@Configuration
public class XStreamAutoConfiguration {

    @Bean
    public XStream xstream() {
        return new XStream();
    }
}

There are other alternatives to the XStream no-args constructor documented on XStream’s website e.g. one for StaX, another for JSON, etc. Our starter should allow client applications to use their own instance, thus creating it only if there are none provided in the context. That sounds a lot like a conditional on missing bean:

@Configuration
public class XStreamAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(XStream.class)
    public XStream xstream() {
        return new XStream();
    }
}

XStream is based on converters, a way to convert from one typed value to a JSON/XML formatted string (and the other way around). There are a lot of out-of-the-box pre-registered converters but clients can register their own. In that case, it should be possible to provide them in the context so that they get registered with the provided instance.

To do that, create a @Bean method that takes both an XStream instance and a collection of converters as injected arguments. This method should only be called if there’s at least one Converter instance in the context. This can easily be configured with the @ConditionalOnBean annotation.

@Bean
@ConditionalOnBean(Converter.class)
public Collection<Converter> converters(XStream xstream, Collection<Converter> converters) {
    converters.forEach(xstream::registerConverter);
    return converters;
}

At this point, any custom converter provided in the Spring context by client applications will be registered in the XStream instance.

This concludes this post on creating Spring Boot starters. It’s quite easy and straightforward! Before going forward with your own, don’t forget to check existing starters, there are already quite a lot provided out-of-the-box and by the community.

UPDATE: the code is available on Github

Send to Kindle
Categories: Java Tags: