Saturday, 3 June 2017

Prelude to Functional Paradigm.

When we talk about Functional Programming, then Functions holds the key to computing instead of Variables.

Functions are the first class citizen of Functional Programming Paradigm. Whether it is Lambdas in Java8 or Closures in Groovy both aid to Functional programming and in the best possible way.

Does the features that Java8 embeds, shifts its paradigm to Functional Programming Horizon? Basically being a beginner with these tools that has been introduced in Java8, I would try to answer it in the following way: It's true that java 8 provides the platform for Functional Programming now but the imperative style too is dominant. I think may be It is the Best of Both Worlds that we all will be trying to look into and incorporate as per our needs. With all the new features in Java 8 like Lambdas, Monads, Functor, Upgraded collection API with Streams etc., Java now extend its support for Functional Programming.

But the question arises why Functional Programming is gaining popularity more and more.

The main idea behind functional programming is that Functions are being considered as the First Class Citizen here. It is the Function(or Method) reference that we pass as arguments (which we will see in a while) and upon when needed we apply arguments to those function references and evaluate them.

Data Invariance lies at the heart of any Functional Programming language which we can describe as that each function produces results without affecting/modifying the environment and by this way we can go for parallel programming without any side-effects.

Basically what I have experienced that following Functional Style makes the application inherently Thread safe as every Function upon invocation returns an Immutable Object (following Data Invariance) which again is passed to some other function. Monads, Functor and other constructs mainly contribute to these.

Basically a Pure Functions acts on its arguments passed and produce results without any side effects (i.e. without the interference of any State Variables or other types) and thus helps in building Thread Safe apps.

Groovy is a Functional Programming Language which is Dynamic in Nature but can be Static typed too.

So, Lambdas in Java8 and Closures in Groovy are those two facets which seems structurally similar at their first sight, but the underlying implentation and their applicability provides a clear distinction.

So, how Lambdas differ from Closures? We have a Functional Interface:


@FunctionalInterface
public interface Func1 {
    R transform(T t);
}

and we invoke it as:
 
    static Func1 stringIntegerFunction = s -> s.length();
    Assert.assertEquals(stringIntegerFunction.transform("Mickey"), new Integer(5));
 
 
The Functional Interface implentation is done with a Lambda expression and then invoked from within main method. A Functional Interface basically follows SAM (Single Abstract Method) Rule.
Similarly if we need to declare a Closure that Takes a String as input and has Integer as return type, then we can define that as:
   Closure func1 = {String str -> str.length()}
 
and even as:
  Closure func2 = { str -> str.length()}
 
The difference being one being Typed and other not. For Groovy Closure we dont need to define any Functional Interface.

We can then invoke them as:
  Assert.assertEquals  func1('Mickey'), 5
  Assert.assertEquals func2('Mickey'), 5
 
If take a closer look at the Lambdas, then Lambdas are basically anonymous implentations of mostly Java 8 Functional Interfaces, But on the other hand Closure in Groovy is class, that Groovy Runtime Dunamically generates an instance of it (Closure class) when it encounters Closure expressions.

The feature that really impressed me is the Delegation Starategy of the closure, which adds a lot to the type nature of the groovy along with the type inference feature of the closure, which too is awesome. We do not need to decalare any type while declaring the closure, it deduces the type based on the parameter passed at runtime (Duck Typing), however we can can Strongly type a Closure too. These feature often turns out to be source Of Confusion too.

The Delegation strategy may seem a bit confusing at first, but it is really interesting as we learn more about it.

Since Groovy documentation has detailed explantion of Closure and all other features (as said above and Many more) so we will restrict our discussion in that direction.

Another feature is that Groovy closure can access any variable from it enclosing context, while Java lambdas can access only variables which are final or effectively final. This post is not intended in any way to mark out the differences between Groovy or Java.

But it is all about how I am experiencing Functional Programming paradigm when I am just starting to learn the best of both these worlds. And also a bit explaining how Lambdas and Closures and used interchageably. Almost everything that Lambdas does can be achieved with Closures and Perhaps More!!!

We will try to point out some cool Closure features through some unit tests.
class ClosureSpec extends Specification {
 
 def "test closure"(){
 
  when:
   def retVal = function([1,"Mic"],{str1,str2 -> str1.size()+" Paul "+ Arrays.asList(str2)})
  
  then:
   retVal('Mic') == "2 Paul [Mic]"
 
 }
 
 def function(str,cl){
        return { name->
            cl(str,name)
        }
    }
 
}
 

Here the Function named function takes two parameters and returns a Closure.

We have passed List as the first parameter and a closure as the second parameter. Now this closure takes two parameters in its input and does some processing. As a return type we have returned a Closure which again takes another parameter as its input.

Now when we have invoked the function:
  def retVal = function([1,"Mic"],{str1,str2 -> str1.size()+" Paul "+ Arrays.asList(str2)})
a closure is returned i.e. retVal and then we have called the Closure with 'Mic' to get the desired output.
retVal('Mic') == "2 Paul [Mic]"
Here no Type has been mentioned with any parameters, the types are being deduced based on the data passed.Now if we pass something to str1 where the method size() cannot be allowed say an Integer then we will be getting an error for sure. Now in the second demo:
we have defined a List as:
def names = ['Mickey','Mic',100]
and a Closure as:
 def cls = {str ->  println "My New Name is: $str"}
 
This Closure takes a String as an argument and prints out a message bearing that argument.
Now if we need to pass this closure to the each() of the List, then we would do something like this.
  names.each (cls)
or
names.each {cls(it)}

Now if we want a method reference to be passed as argument to each() method of List class we would declare the method as:

 def transform(str){
        println "My Name is: $str"
    }

and pass it as:

 names.each {this.&transform(it)}
Or

names.each(this.&transform)

Now if we want to do the same in Java8 we would do something like this:
List list = Arrays.asList("Mickey", "Mic", "Donald");
and invoke them as:
 list.stream().forEach(s -> System.out.println(s));
 
Or:
 
 public void printEach(String str){
        System.out.println(str);
    }
 
  list.stream().forEach(this::printEach);
 
 
forEach() method expects an argument of Consumer Type which is a Functional Interface.
So Closures and Lambdas almost goes side by side. Now to find the interoperability between these two, lets declare a Method in Java which takes a Fnctional Interface and try to invoke it passing a Closure from Groovy.
 
 Class A{
 public static Integer getMeLength(Func1 func1, String str){
        return func1.transform(str);
    }
 }
 
Then we can invoke it as:
  Assert.assertEquals  LambdaTest.getMeLength({str -> str.length()}, "Donald Duck"), 11
  Assert.assertEquals  LambdaTest.getMeLength(func1, "Donald Duck"), 11
  Assert.assertEquals  LambdaTest.getMeLength(func2, "Donald Duck"), 11
 
Please Note: func1 and func2 are the closures that we had defined earlier.

Groovy Closures do not bind themselves specifically to any Functional Interfaces or any interface that confirms to SAM, we can represent both SAM or implement any interface (be it SAM or not) with a Groovy Closure, thats the flixibility that Closure comes with.

However, Lambdas are more centric towards Functional Interface or SAM.

This is in short and very basic note on Java8 Lambdas and Groovy Closures.
View Subhankar Paul's profile on LinkedIn

Sunday, 15 January 2017

A Vert.x Perception - WebSockets Revisited

Websockets has always been an interesting subject to me and I always believe there is more to explore. Every time I spend time with it accompanied with information from various other beautiful, informative blogs and posts I learn something new, and when it is complemented by Vert.x toolkit it becomes more interesting.

In my Previous Post, We discussed about implementing WebSockets with SOCKJS and used SOCKJS handler at the server side along with SOCKJS event bus at the client end.

In this post we will look forward to explore how WebSocket Handler handles requests and generates responses with the help of Web Socket protocol. Here is the GITHUB CODEBASE for reference.

We are citing an exmaple to see things in action.

Within SockJSVerticle the request handler for path /sendToSocket is the main Actor in Action here.
Within the Handler we have perfomrmed the following Tasks:

1) Creating an HttpClient and opening WebSocket Stream with the Client.


 HttpClient httpClient = vertx.createHttpClient(new HttpClientOptions())
 httpClient.websocketStream(8084,"localhost","/sendToSocket")

2) Writing the Data to be sent to with a Websocket.


handler({websocket->.......
...........
 .write(Buffer.buffer("Send Data to Server...".toUpperCase().getBytes()))
 ......

3) Using the Websocket to receive data with the help of WebSocketFrame.

 .frameHandler({webSocketFrame -> println "The Data at the Client Socket is:${webSocketFrame.textData()}"})
Now when we write data to the Websocket as described in Point 2, the control passes on to the WebSocketHandler that we have already registered with the Vert.x server in SockJSVerticle.groovy

 httpServer1.websocketHandler(new WebSocketHandler());
If we peek into this Handler we can see that it implements Handler which is MUST MUST for any Handler handling WebSocket requests, as the handle() method which has a ServerWebSocket is used to receive requests as well as create and sent reponses too (Here we have used WebSocketFrame to do the same).

 .frameHandler(new WebSocketFrameHandler({buf->serverWebSocket.writeBinaryMessage(buf)}))
Within WebSocketFrameHandler we have passed Consumer function. This function is being used to send the response from the request that we have received in the handle method of WebSocketFrameHandler

 void handle(WebSocketFrame frame) {
    println "The Data at the Server Socket is:${frame.textData()}"
    consumerbuffer.accept(frame.binaryData())
    }
The data that is sent from handler method of the path /sendToSocket is received by WebSocketFrame at the handle() method of WebSocketFrameHandler and which is being sent again with the help of the Consumer function, this function sends the data with the help of ServerWebSocket as the definition of the function contains:

{buf->serverWebSocket.writeBinaryMessage(buf)}...
This is in short about WebSocket.

Please share your comments and feedback.
View Subhankar Paul's profile on LinkedIn

Sunday, 8 January 2017

A Vert.x Perception - Service Registration N Discovery

Service Publishing and Service Discovery is the integral part of any Microservice Architecture. So it is for Vert.x .

Publishing and Discovering Service can be done very easily with Vert.x and it also provides fault tolerance mechanism with Vert.x's own Circuit Breaker implementation or with the help of Hystrix.

Let's start with Service Publishing and Discovery first.

Vert.x does provide a variety of service types to be published, for Ex:

1) HttpEndpoint
2) EventBusService
3) MessageSource
4) JDBCDataSource

Our discussion will focus mainly on HttpEndpoint, JDBCDataSource. The Service Discovery Codebase can be accessed here.

Let's Start with Service Publishing part first. Service publishing requires two steps to be followed.

1) Creating the required Service Instance.
2) Publishing the Service with the help of a Service Discovery.

For Publishing Service we are using the Server3.groovy verticle. Please note we are publishing the service only after the Server3 verticle is being successfully deployed.

 
                                    if(!server2AsyncResult.succeeded())
                                        server2AsyncResult.cause().printStackTrace()
                                    else{
                                        println "The Server 2 Deployed Successfully... \n\n So, " +
                                                "Publishing the Service..."
                                        publishService(startFuture,serviceDiscovery,"Server2")
                                        publishJDBCService(startFuture,serviceDiscovery,jdbcConfig,"MY-H2-DB")
                                    }
 
 
publishService() method publishes HttpEndpoint with the name Server2 while publishJDBCService() method publishes JDBCDataSource with the name MY-H2-DB.

HttpEndpoint Service:

The HttpEndpoint is being created with:
 
 HttpEndpoint.createRecord(....
 
 
by passing service name, hostname, port and the relative URI for which the endpoint should be created.

JDBCDataSource Service:

Similarly, the JDBCDataSource service is created with:
 
  JDBCDataSource.createRecord(....
 
 
by passing the service name, DataBase Config and the DB name as the parameter.
The DataBase config basically consists of URL, Driver_Class, user, password and other DB specific parameters.

The error handling during publishing can be handled with the Handler provided as part of publish(.... method.
This is in short a very Basic description of the Service Publishing in Vert.x

Now, Any Service that is published is meant to be consumed.
So, let's move on to Service Discovery and subsequent Service consumption.

As said earlier, Fault Tolerance is an integral part any Microservice Architecture to isolate points of access to remote systems, services and 3rd party libraries and hence stop cascading failures and enable resilience in complex distributed systems where failure is inevitable.

With Service Discovery section Fault Tolerance is inherently related, but we will take it as a separate topic. within codebase, fault tolerance related work could be observed, I would discuss those sections again in our next post related to Circuit Breaker .

HttpEndpoint Discovery

We have defined a Handler for /dataServer2 in Server2.groovy Verticle, because this the relative URI for which HTTPEndpoint is created.

Upon invoking the this endpoint with the corresponding client the Handler will get executed which we will see very shortly.

The Discovery of any service has the following generic steps to be followed:

1) Fetch the the corresponding Record with the Service name with which it is published.

   serviceDiscovery.getRecord(....
 
 
2) Upon Successful Record fetch (as verified from the Hnadler), we get the Service Reference Type

 def reference = serviceDiscovery.getReference(ar.result())
 
3) From the Service reference we fetch the client that will be used in invoking of consuming the service.

 def client = reference.get()
 
4) Finally we consume the service and fetch the result. The Result in this case will be fetched from Handler for /dataServer2 as described above.

The HttpEndpoint service discovery can be found at Server3.groovy under the method invokeServer2() and this method is being invoked as part of the request handler for the URI /getServer2 i.e.

 
   router.route(HttpMethod.GET,'/getServer2').handler({routingContext->
            println " ***** Invoking Server2 with Service Discovery ***** "
            invokeServer2(routingContext,serviceDiscovery,circuitBreaker);})
 
 
The Codebase can be accessed here.

JDBCDataSource Discovery

For JDBCDataSource Service the steps to be followed for Service consumption is same as above the only difference is we use this service to fetch a JDBC connection and carry out some DataBase activities.

The HttpEndpoint service discovery can be found at Server3.groovy under the method fetchJDBC() and this method is being invoked as part of the request handler for the URI /getJDBC i.e.

   router.route(HttpMethod.GET,'/getJDBC').handler({routingContext->
            println " ***** Fetching JDBC with Service Discovery ***** "
            fetchJDBC(routingContext,serviceDiscovery,circuitBreaker);})
 
This is short very Basic on Service Discovery. Please feel free to share your thoughts and feedback.

In our next post we will try to discuss on Circuit Breaker. Till then Keep Coding and Keep Sharing.

View Subhankar Paul's profile on LinkedIn

Monday, 2 January 2017

A Vert.x Perception - Websockets with Vert.x Basics

To learn and understand WebSocket operation in Vertx I have taken the reference of the blog

Blog

.
The codebase can be accessed

HERE



The starting point of this app is index.html which makes websocket request with the help of Vertx-Eventbus. To use Vertx Eventbus we have used here a js for sending the request through Eventbus.

The request is being sent with the help of a js function sendData which is a part of realtime-auctions.js and which is invoked while clicking the Button with the value bid.

In realtime-auctions.js there is a function registerHandlerForUpdateCurrentPriceAndFeed() where we have created a EventBus and registered a Handler to receive events.

When this function is triggered during onload of index.html, the handler for the path "/eventbus/*" (as described in SockJSVerticle.groovy) is invoked because of:

router.route("/eventbus/*").handler(eventBusHandler())
and the BridgeEventType.SOCKET_CREATED event is published.
Now we can say that the Event Bus Handler is ready to send and receive messages.
So on clicking the bid button from the index.html data 'price': '0007' is being sent to the Handler as described above and the BridgeEventType.SEND event is published and from there we are again publishing data to the eventbus and that is received by the handler registered during html page onload and which makes the necessary changes within the page.

Similarly we have also registered another Handler:

 router.route("/api/test").handler(new EventBusHandler().&generateSockData)
 
So, when we access the URL http://host:port/context/api/test it independently publish data to the event bus and that too being received by the handler at the html page in the same way as described above.

So once the client side handlers are being registered, then those are capable of receiving messages as published from the server end, provided the eventbus name which is here 'auction' needs to be mentioned correctly. So, If we need to send and receive data over a different eventbus Say, for example 'auction2' then we need to register handler at for this eventbus both at the client and server end separately to send and receive data.

Similarly, while sending request data also, Eventbus with the same name (i.e. aution) is being registered at the sever end end with the help of BridgeOptions as used in SockJSHandler which then is used to intercept the request data.

View Subhankar Paul's profile on LinkedIn