Wednesday, August 17, 2016

DSL example with Scala

As you know I just started to learn Scala few months ago, and I have to say that each time I am developing in Scala I see in it a lot of powerful utilities.

 Today I want to implement a simple DSL (Domain Specific Language).

Imagine we want to design a language to communication our software with an external hardware, in this case a robot. We are going to be able to communicate with our robot in this way:


There are some key concepts applied in the code showed above:

  • Syntax sugar. In Scala there are several situations where ',' and '()' are optionals. For example when the method has only one parameter.
  • Builder pattern. To make a fluent Api you can use the Builder pattern which consists in return the object 'this', then in this way, you can concatenate the calls to the different methods in one line. 
  • Implicit conversions. Implicit Conversions are a set of methods that Scala tries to apply when it encounters an object of the wrong type being used. To use implicit conversions, you need to import the class that contains the implicit methods to do the conversions.
The main application.

The Robot class.

Finally the Speed class that enriches the Int type.
You can find all the code in the my github account here

Sunday, July 31, 2016

Fast Scala: Constructing a Rational

Today I am going to summarize the chapter 6 of the Programming in Scala book of Martin Odersky. This chapter guide you through several technical aspects of Scala, implementing a real example. In concrete implementing the class Rational.

 A specification for class Rational

A rational number is a number that can be expressed as a ratio n/d, where n and d are integers, except that d cannot be zero

Constructing a Rational

Note that the Scala compiler will compile any code you place in the class body, which isn't part of a field or a method definition, into the primary constructor. In our case, every time you construct a Rational a message "My Rational is created" will be printed.

Another interesting thing is the 'require' method. The 'require' method takes one boolean parameter. If the passed value is true, require will return normally. Otherwise, require will prevent the object from being constructed by throwing an IllegalArgumentException. The require method belongs to the Predef object which is imported by default by the Scala compiler.

Finally we added an implementation of the toString method. By default the toString method prints the memory location where lives the object in the heap.

Adding Rationals

For example, to add 1/2 + 2/3, you multiply both parts of the left operand by 3 and both parts of the right operand by 2, which gives you 3/6 + 4/6. Adding the two numerators yields the result 7/6.


Note that we added two fields named num and denom, and initialized them with the values of class parameters n and d. This is because you cannot access in this way : that.n or that.d, because n and d are in scope in the code of your + method, you can only access their value on the object on which + was invoked.

With our defined method +. You can write code like that: x + y , where x and y and rational objects.
And is equivalent to write that: x.+(y). Of course, write x + y is more natural instead of write something like x.add(y)

Another thing to note, is that it would be great do things like that: x + x * y , where x and y are Rationals. Of course is not the same to that : (x + x) * y than that : x + (x * y). Scala has defined by default rules for operator precedence and for this reason, expressions involving + , * and / operations on Rationals will behave as expected.

Auxiliary constructors

Sometimes, you need multiple constructors in a class. In Scala, constructors other than primary constructors are called auxiliary constructors. For example, a rational number with a denominator of 1 can be written more succinctly as simply the numerator. Instead of 5/1, for example, you can just write 5. Therefore instead of write new Rational(5, 1) simply write new Rational(5). But this requires an auxiliary constructor. Auxiliary constructors in Scala start with def this(...).


Method overloading

Now you can add Rationals, but cannot add an Integer and an Rational. For this, we have to overload the method +. Then you could write code like x + 4 , where x is a Rational

Implicit conversions

Now that you can write r + 2, you might also want to swap the operands, as in 2 + r. Unfortunately this does not work  yet. Because the Int class doesn't have any method tu add Rationals.

However, there is a way to solve this problem in Scala. You can  create an implicit conversion that automatically converts integers to rational numbers when needed. The implicit conversion could be in the companion object.

I hope it was interesting for you, I will try to summarize some interesting chapters of Programming in Scala, in the next posts. We keep Scaling!

Sunday, July 24, 2016

5 minutes of Scala: Prefix unary operators

Well, I am reading the book Programming in Scala, and I am discovering new capabilities of this  language. Today I want to talk about unary operators (also called prefix operators).

The only identifiers that can be used as prefix operators are +, -, ! and ~
Then you have to define your method using unary_<here your operator>, and you could invoke that method using prefix operator notation, such as <your operator><your variable>.

I know maybe all of this, is a bit confusing but seeing code all will be more easy.

Imagine, we want to implement our class Color. This class defines a color using three pixels (red, green, blue). Also we want operate with our Color class, and one required operation is the capability to inverting the color. As Java programmer, I would define a method called inverse, and I would call it in this way : myColor.inverse() . It is a good approach, totally acceptable, but here is when the magic of unary operators comes, you can do the same in Scala with this : !myColor


Note the definition of the method using unary_!. Also remember that only there are 4 supported unary operators: +, -, ! and ~


Sunday, July 17, 2016

Sending messages to your Akka Actors from JMX

Lately I was a bit busy learning new technologies like Scala, Akka and changing my mind to start to think in functional way. As I promised, my next posts will be about Scala and all technologies related to this language.

 Today I want to show you how to combine an old friend like JMX with and application done with Akka. Scala runs on the JVM so you have all the tools available in the Java platform. To follow this tutorial, it is necessary to have an idea about what does it means the Actor Model

Also you need to have installed Scala. Please follow this instructions if you don't have any installation. I recommend to you IntelliJ as a development environment, it provides a cool support to work with Scala.

Cool! We are ready to start. Our application is very simple, we are going to create an Actor called Pong, and this actor will be waiting a message from a JMX client. This client will be able to send messages to our actor Pong. If the message sent is "end", Pong will be terminated. Otherwise the message will be stored in memory. From our JMX client, we can ask for the last message received by the actor Pong. Let's see some code.

First of all , our support to code actors with JMX support. Extending this trait the actor will be registered in our MBeanServer automatically using the methods preStart and postStop. Note that method getMXTypeName is an abstract method and is implemented by the child class.

Is time to define our MBean. By convention the MBean is defined with the suffix MBean. Here is the trait that exposes the operations available from our MBean.


Finally the actor Pong implements the trait showed above and extends from our ActorWithJMXSupport.

Then we need a main application to start up the actor Pong.

Ok! The hard work is done. Now you have to start your application passing to the JVM this parameters:

-Dcom.sun.management.jmxremote 
-Dcom.sun.management.jmxremote.port=1617 
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false

At this point, you have the application running with the actor Pong waiting for requests. As you can see the MBean server is listening in port 1617.

Finally executing jmc in a console, the JMX client provided by the jdk, will be opened. Then you can browse in the MBean browser to find our MBean registered. In the tab operations, you can execute the operations defined by the PongMBean. In the next video, you can see this last part clearly.



Sunday, June 12, 2016

Distributed configuration with Spring Cloud

Move from your Monolithic Architecture to a Microservices Architecture style, it implies to deal with some challenges. One of them, is the configuration of all your backend services. Every microservice requires the injection of its configuration. If you don't centralize your configuration, probably you are duplicating a lot of configuration along all your microservices infrastructure.

To make this task easy, it seems that put all your configuration in one place could be a good idea. In fact, it is. When your services are starting up, one of the things that they will do first is to ask for its configuration.

In the next picture you can see the basic workflow of this communication.



Configuration service

To do that, we are going to use Spring Cloud config support. First of all, we need to create a configuration service, that it will expose a Rest API to be able to do the communication that is showed in the picture above. To achieve that is so simple like add in your pom.xml the spring-cloud-config-server dependency as follows:

And in your application.properties add the follow properties:

Finally you have to annotate your class with @EnableServerConfig.

Now we have running our configuration service on port 8888, and is ready to serve configurations to other backend services. Work is almost done.

Client service

Now we are going to do a demo service and configure it as a client of our configuration service.

First of all, to configure a client of the configuration service you have to add the follow dependency in your pom.xml :

Now you have to tell to Spring context that the required configuration is loaded in remote mode. To do this, you need to replace the application.properties by the file bootstrap.properties with the following contents:

Note that in the git repository, the configuration is stored in a hierarchy way. Each backend service has an identifier defined in their bootsrap.properties. For example, a backend service with identifier 'service_1' , its configuration is stored in the file service_1.properties. Also you can define a common configuration called application.properties that is inherited by all services, and also they can override it in their configuration files.

Now when our service_1 is starting, it will ask to configuration service for its configuration before configure the Spring application context.

Then we can create a Rest service which accesses to one property (message.hello) provided by the configuration service.


Ok, we have the work done. But we can improve our solution, with Spring Actuator. If we annotate our Rest service with the annotation @RefreshScope, Spring Actuator can refreshes this bean, and then you can reload the configuration without restart your backend service. Let's see how.

Add the dependency :


After that make sure your class is annotated with @RefreshScope. Finally your can refresh your beans using the endpoints that exposes Spring Actuator in this way:

curl -d {} http://localhost:8080/refresh

And that is all. I hope you found it interesting. See you in the next post.

You can find all the code in the listed links:

Tuesday, May 24, 2016

Multitenancy with Spring Boot

For those who are not familiar with the term Multitenancy, let me start answering some questions that may be come to your mind.

What is multitenancy?

It is a software architecture where the same instance of the software serves multiple tenants. You can see a tenant as an organization. For example, if I have a software platform to sell TV's, my tenants could be Samsung, Philips and Sony. The good thing is that with this approach you are sharing resources, and if you work with cloud platforms this could be a good idea. On the other hand, as you know nothing is free, you have to be aware about the security and the isolation of the data and other things. Before you decide if this kind architecture matches with your requirements, you have to study in deep your requirements.

How to implement that?

I will not delve into the details that motivate the choice of a strategy or another. There are three approaches to do that:
  • Separate database per tenant (picture 2).
  • Separate schema per tenant.
  • Share database and schema.

Ok, we are ready to start. In this example, I am going to implement the first option (separata database per tenant). Note that in this example, the tenants will be added dynamically, this means that only adding the configuration of the tenant in the application.yml will be enough for the application be aware of the new tenant.

I remember you, that this example is using Spring Boot and Hibernate.

First of all we have to add in the application.yml the multitenancy configuration we want. In this case, I have two tenants.

Also we have to exclude the default data source configuration that provides Spring Boot.

The next step, is to provide a mechanism to determine, in runtime, which tenant is accessing to the application instance. To do that, Spring provides an interface to implement it.

RequestContextHolderUtil is a class which determines the tenant based on a pattern contained in the Uri of the request.

Now we need a mechanism to select the correct database (DataSource object) based on the current tenant which is accessing to the application. Once you have the tenant id (above step), you only have to extend the class AbstractDataSourceBasedMultiTenantConnectionProviderImpl provided by Spring.

Note that the object Map (attribute of class AbstractDataSourceBasedMultiTenantConnectionProviderImpl) is configured when the Spring context is loaded reading the multitenancy properties from application.yml. This configuration is performed in a class annotated with @Configuration. You can see the code below.


The last step is to implement a Rest controller to access to the data. Note that the Uri of the endpoint contains the 'tenantId' pattern. Of course, there are different ways to do that. For example using domains or subdomains and so on.

Finally, you can find all the implementation in my GitHub profile here


Feel free to contact me for questions or any doubt.

Happy codying

Sunday, May 22, 2016

Template method and Builder pattern using lambdas

Today I want to show you how easy is to implement a Template method pattern using lambdas and Consumer functional interface in Java 8. To illustrate our example, we are going to develop a software to send commands to a robot.

 Before the command is sent, it is required to establish the connection with the robot and set the robot to status ready (ready to receive commands). Finally after the command execution the robot must be set to idle status. Then each command execution requires 4 steps listed below.

  1. Establish connection with the robot.
  2. Set the robot to ready status.
  3. Execute the command.
  4. Set the robot to idle status.
Take a look how to implement this, with Java 8 using lambdas.

As you can see in the above code, the client is not worried about how to obtain a robot connection, it only sends the command it want to execute on the robot. At the same time, we are using the lambda to provide a fluent interface to configure the command (Builder pattern).

The method 'executes' acts as template method, and you can see how the RobotCommand object is instantiated locally. Then using the method 'accept', the created RobotCommand is passed to the lambda context.

You can find the complete code here