Andre's Blog

20160710 Reading Json Configurations In CISystem

[CISYSTEM] [GROOVY] [JSON]

To connect the nodes in CISystem I need to tell at least every node where to find one other node. When every node knows the address of one other node and there is a way from every node to every other node we have our network. The nodes can populate the network with information while connecting, at the end every node will know all other nodes.

Maybe it makes sense to start a node with information about more than one node. For example if the other node is not up and running you need a second or third connection to the network.

You also need to specify a port. If you choose one port for all of your nodes maybe on some PCs this port is already in use. Maybe there is a reason why you want to run more than one node on one PC. I want to be able to test my network on only one PC with several nodes, so the port must be configurable.

The next question is, how shall this configuration look like? Command line parameters, XML, an .ini file? Since I really making new experiences and I did work with with Json yet, I have decided to try using a Json configuration for it.

The only problem is, Java does not come with a JSON parser, you need to choose some third party jar like GSON or implement your own parser...

Or you use Groovy's JsonSlurper. It's really nice, elements are returned as maps or lists of maps and it is really easy to get the information out of the Json file.

The only problem is, how to execute Groovy code from Java and retrieving the information. Well, that is another thing I wanted to get my hands on. You only need the GroovyClassLoader and the GroovyObject class, both come with Groovy and you only need to import them and have the groovy-all-2.4.6.jar (or later) in your classpath and then you can parse the code of a Groovy script and execute it via GroovyObject.invokeMethod(). GroovyObject is the base class of all Groovy classes/scripts and so this is easy.

What I did was

  1. define my Json configuration
  2. implement a Java class representing my Json configuration
  3. implement a Groovy script to read my Json configuration and store it in my Java object
  4. implement a Java function to call my Groovy script

This has the benefit when Java is supporting Json in the future, then I can kick out my Groovy call/code and replace it with Java code and I don't need third party jars meanwhile.

I explain my implementation in detail in my Java/Groovy coding blog :

Calling Groovy From Java To Read Json

This is the complete example code including my build.gradle script : zipped example of Calling Groovy From Java To Read Json

Select where to go ...


The Blog
My Technical Blogs
Projects
Blogs Of Friends
RSS
CV/About
Me