Saturday, December 30, 2017

Going Reactive with Spring - Spring WebFlux - Part 1

Spring is one of the most popular frameworks used by Java-Developers. Manageable learning curve of Spring has lift it to the top of most-used Java-Framework through out the world. The latest of Spring Family has arrived recently with the flavor of Reactive-Programming in-built to it. This article series is about building a robust-reactive API using spring-webflux.

What is Reactive-Programming ?


Reactive Programming is a programming paradigm where you program with asynchronous-data-streams. In Imperative-Programming we get the data and perform actions on it. But in Reactive-Programming we don't wait for data to present to perform actions rather we instruct what to do when data is available. If you are new to Reactive-Programming I would recommend you to first go through my-article on Reactive-Programming before you start here.

The basic-building blocks of Reactive-Programming is Data-Streams. Data-Stream is like a pipe. From one end we put-data into it and from the other end we will retrieve the data. But we will not pull out the data, but the data will be pushed when it is available. 

In Spring-Webflux, there are two types of Data-Streams, namely Mono and Flux. As the name infers Mono is a data-stream which contains at most one element. In the other hand Flux is a data-stream containing more-than one element. Mono and Flux are derived from Project-Reactor as Spring-Webflux is built on top of Reactor.

Starting with Reactor


Before we dive into Spring-Webflux we should first understand the concept of Mono and Flux
So, lets take a look at how we can compose a Mono.
  Mono<String> sampleMono = Mono.just("sample_mono");
As we can see, this is a Mono which is composed with a single String in it. If we can only use single elements in a data-stream then the concept becomes useless. So that is how Flux come into play. Lets see how we can compose a Flux.
Flux<String> sampleFlux = Flux.just("sample1", "sample2", "sample3");
So, we can compose a data-stream of any type(reference-type) using Mono.just(...) and Flux.just(...). But, in Reactive world a data-stream is the laziest person you can find. Even though you composes and apply some functions on the data, stream might not give you the result unless you have subscribed to the stream. This means data-stream would do nothing unless you have subscribed to it. Lets see how we can subscribe and get the data out.
sampleMono.subscribe(data -> System.out.println(data));
So, if you run the code you will see sample_mono will be printed out in the console. But, this is just a shorthand of writing a Subscriber. A Subscriber is composed with four-functions. onSubscription, onNext, onError and onComplete which will be called out in different stages in subscription. onSubscription will be called when the subscription is started. onNext will be called when the next data item is available in the stream. onError as the name propose will be called when an error occurred in the stream. And finally onComplete will be called when the subscription is completed.
In Reactor there is a Subscriber interface which you can implement and provide as a subscriber to stream. Lest see how we can implement a subscriber for our sampleFlux.
        Subscriber<String> subscriber = new Subscriber<String>() {
            @Override
            public void onSubscribe(Subscription subscription) {
                System.out.printf("Subscription Started");
            }

            @Override
            public void onNext(String s) {
                System.out.println("Next : "+s);
            }

            @Override
            public void onError(Throwable throwable) {
                throw new RuntimeException(throwable);
            }

            @Override
            public void onComplete() {
                System.out.printf("Subscription Completed");
            }
        };
        sampleFlux.subscribe(subscriber);
If you run this code you will see that onSubcription will be called in the first place. And for every element in the stream onNext will be called after every element is over onComplete will be called. You can find out some interesting samples on reactor in this article.

Monday, September 11, 2017

Spring MVC : The Framework - Part 2

Spring-MVC Sample


As I described in the previous segment, spring-mvc is a framework that is really useful in developing web-applications. So, to demonstrate the abilities of Spring-MVC lest start with a sample application for library-management-system and understand the building boxes of Spring-MVC

Initializing Project

  1. In this sample project we will use 'Maven' as our dependency management tool. So, initialize a maven-project and add the dependency for 'spring-mvc' in the 'pom' file.
  2. Then Create a directory-structure as follows :


Configurations for Spring-MVC


First of all as I explained in the last chapter we have to map the servlet which our application going to fit. To that we have to create a 'web.xml' file inside 'spring-mvc-sample/src/main/webapp/WEB-INF' directory and add the following configurations to it : 



This configuration will tell the 'DispatcherServlet' to handle the requests coming from the configured URL pattern. After initializing the 'DispatcherSevlet' the frame-work will try to load the 'application-context' from a file named '[servlet-name]-servlet.xml' file which should also be located at 'webapp/WEB-INF' directory by default (to configure this spring-mvc has a mechanism which I will describe in the next chapter).  So, for the application-context to load add a file named 'spring-sample-servlet.xml' into spring-mvc-sample/src/main/webapp/WEB-INF' directory and add the following lines to it.


'context-component-scan' is the place Spring starts searching for the configurations. Usually we will give the 'group-ID' or the 'Base-Package' of our project as base-package. 

The next configuration is for the view-resolver which resolves views when a view-name is given. So, according to this configurations it will resolve views in the path 'WEB-INF/jsp' and with the '.jsp' prefix.

Then add a controller class 'HomeController' inside the 'spring-mvc-sample /src /main /java /com /springmvc /sample /controller' direcotory and add the following lines to it. 


@Controller annotation will tell that this class should be setved as 'Spring-MVC-Controller'. @RequestMapping annotation on top of the 'getHomePage' method will inform Spring where to map the request and according to which HTTP-method.  

And then create a 'home.jsp' file inside 'webapp/WEB-INF' directory and add sample HTML content into it.

And the sample app is done. You can checkout the full-project here














Sunday, September 10, 2017

Git Commit Messages

Why Messages ?



Git is a Version-Control system to track the  changes to the files in your computer. It is a tool to control and keep track of the changes to software products.  Git Commit  is where you put some specific changes to files into the Git Local Repository.  It is compulsory to put message when you do a Git-Commit. 

A message is a communication  medium. What are we going to communicate through a 'Git-Message' ? Is it really important to put a message to a commit ? To whom are we going to communicate ? 

When talking about git we always remember a software-project where multiple developers are working. So, a commit-message is going to communicate the group of developers about what has been changed in the project. In a software project a group of people works to achieve a common goal. So, it is really important to all of them to know what has happened to the project. But the message should be much more meaningful and descriptive. 

Some Standards


If we search internet we could find some standard ways to put git-messages. In this article I would cover some basic standards which I use. 

A change to the software project can be a new-feature, update to an existing feature or a bug-fix. So, if you to write a commit message it would be much easier to others if we could let them know to which category of above was the change belongs to. So, when you write a message always start it with either one of these three prefixes. 
  1. New : (if a change was a new feature)
  2. Fix : (if change is a bug fix)
  3. Update :  (if change is an update to an existing feature)
After the  prefix then put a semi-colon and write your message. After the message you have to convey whether the change is finished or not. If the change is finished put a full-stop (.) after the message. If the change is unfinished you can put a comma (,) and wip which stands for 'work in progress'. 

Eg : 
       Fix : Login Page changed.
       New : User registration validation added, wip

Saturday, September 9, 2017

Spring MVC : The Framework - Part 1

What is Spring-MVC ?


Spring-MVC is a framework that offers Model-View-Controller Architecture to build loosely coupled and flexible web-applications. MVC Pattern separates the concerns of Business-Logic, Model and UI components so that  can evolve themselves without distracting other components.  Lets take a look at what is actually Model-View-Controller in this architecture.

  • The Model encapsulates the application data and in general they will consist of POJO.
  • The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret.
  • The Controller is responsible for processing user requests and building an appropriate model and passes it to the view for rendering.


Dispatcher-Servlet : What is happening ?


Whole Spring-MVC framework is build around the Dispatcher-Servlet  which handles HTTP Requests and HTTP Responses. It more likely to be the Global-Handler in Spring-MVC. The following diagram is to explain the request-handling-process of Spring-MVC.


After receiving an HTTP request, Front-Controller (DispatcherServlet) consults the handler-mappings and calls the appropriate controller. 

The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. 

Then Front-Controller checks with the view-resolver to find out which 'view' it should render back to the User. When the 'View' is selected, it binds the Modal data to the View and renders it.






Tuesday, May 2, 2017

All you need to know in GIT Branching

Git Branching


Git is a free and open source distributed version control system designed to handle from small to very large projects with efficiency. Git is really easy to use and learn.  In this article we are going to cover one important aspect of Git which is called Branching.

Git Branches are separate, independent line of development in a collaborative project. The first branch in every project is called 'master-branch'. Branching is very useful in a research and development project as many developers might work in many features of the final product. So, the developers can finally merge there independent work in to the 'Master' branch and develop a fully functional product without knowing what the other developer has done.  

Listing Branches


To list the branches and tags in the current project please use the following command.
git branch

Creating a Branch


Just use the following command with an appropriate branch name to 'branch-name'.
git branch <branch-name>
After creating the branch use following command to push the changes in the newly created branch into the remote-git-repository.
git push --set-upstream origin <branch-name> 

Renaming Branches 


To rename the branches we have first rename the local branch and push it to the remote repository. To rename the local branch we can use two methods.

If in the branch which need to be renamed we can use : 
git branch -m <new-name>
Otherwise you have to specify the old branch name also :
git branch -m <old-name> <new-name> 
(-m = option is stand to 'move')

Then we have to remove the old-branch from remote repository and add the new-branch.
git push origin: <old-name> <new-name>
Then finally we have to set the upstream to the new-branch.
git push  origin -u <new-name>

Deleting Branches 


To delete a branch you have to first remove the branch from the local repository and finally remove it from the remote repository. The latter step might need some privileges from the system-administrator unless you are the owner of the repository.

First remove the branch from the local repository.
git branch -d <branch-name>
(-d = stands for 'delete')

Then remove it from the remote repository.
git push --delete <branch-name>

Changing the Branch 


To change your current branch you can use 'checkout' command.
git checkout <branch-name>


Merging Branches
 


Merging meaning connecting components in two git branches into one. Following command will merge the content in 'another-branch' into the current branch.
git merge <another-branch>

Conclusion


I hope that this will be helpful when learning git branching. You can have more details from 'git' manual pages or git home page.


Monday, May 1, 2017

State Design Pattern

State Design Pattern


If you are a programmer, Design Pattern are some main aspects that you need to study and grow up on. Even though number of Design-Pattern exists in this article we are going to explore a Behavioral Design Pattern called State Pattern

According to Wikipedia  state pattern is a behavioral software design pattern that implements a state machine in an object-oriented way. With the state pattern, a state machine is implemented by implementing each individual state as a derived class of the state pattern interface, and implementing state transitions by invoking methods defined by the pattern's super-class.

If you are familiar with State Machines, then State Pattern is not a harder aspect that you cannot master. State Pattern is well suited when the behavior of an object changes in accordance with the internal state of the object.  So, if anyone wants to build an Object-Oriented State Machine, then the most suitable structure to be used is State Pattern.

Structure of State Pattern


In State Pattern we have an 'Context' class which interact with client. You can think of this like the 'State Machine'. Then define an 'State' Abstract Class. Implement this class for different states that the Machine should change. Define an Abstract State Specific Behavior in 'State' class and override it in every sub-class. Have a pointer to 'Current State' inside the 'Context' Class. When the internal state of the machine should change, adjust the 'Current State' pointer to the next specified state of the machine. 

State Pattern does not specify where state transitions will be defined. There are two choices: inside the 'Context' class or Each individual state derived class. Advantage of the latter is that we can add new states easily. But each State derived class has knowledge of its siblings, which introduces a dependency between sub-classes.  

Here is the Class Diagram for State Pattern.


Is it a Good Choice ? 


Any concept is a good choice in its own domain. So, use this Pattern if an only if the behavior of objects in the domain is dependent of the internal state of the object.
Here is a code example for State Pattern. 


Saturday, April 8, 2017

Why Go Reactive?

Reactive Programming


Computer Programming is the process of creating instruction that can tell a computer to execute some tasks. Basically we can identify three types of computer programs in modern world. Namely Transformational Programs, Interactive Programs and Reactive Programs. Transformational Programs are pretty simple. They take set of inputs and produce an output. Interactive is bit different which interacts with users and other programs in its own speed and produce outputs. Reactive is also interacting with users and produces outputs, this time around not in its speed but in the speed of the user. 

Reactive Programming is where you implement computer programs to be reactive. It is an Asynchronous Programming Paradigm which is oriented around Data Streams. Data Stream is like a pipe where some service inputs the data from one end and another service receives data in the other end. And most importantly Reactive also means that it is event-driven. In Reactive Programming the program reacts to any occurred event and fetches the relevant data when data is ready in the data-stream. 

For an example think about the expression [ a = b + c]. In Imperative Programming to take the value of [ a ] we have to recalculate the mentioned expression again and again whenever the values of [ b ] and [ c ] are changed.  But in Reactive whenever the values of [ b ] and [ c ] changes the value of [ a ] will be automatically update without executing the expression. Whenever the change-event for [ b ] or [ c ] occurs the [ a ] which is listening to the data-stream then will automatically update it-self.

Reactive Principles


There are four major principles to be applied when programming re-actively. More than principles we can think of these are constraints on Reactive Realm.
  • Responsive
    • Reactive mean responding to interactions. The program has to respond to user interactions in the speed of user.
  • Resilient
    • Program should be able to maintain and run the service with the occurence of faults.
  • Scalable
    • The service should be able to scale-up and scale-out with maintainig the responsiveness.
  • Event-Driven
    • Reactive is always works whenever event occurs. Program should listens to interactions and works accordingly.

Push or Pull


In programming, there are three mechanisms to take inputs. Push, Pull or Pull-and-Push. Pulling is when the program needs the data it waits until data is ready. Pushing is program executes asynchronously and fetch the data whenever data is ready. Hence Reactive Programming uses data-streams it uses 'Pulling' to fetch data. 

More on Data Streams


Data-Streams are extremely powerful. They are asynchronous. You can execute expressions on data when they are in a data-stream. Executing expressions or functions on data-streams means you can shape the data into the shape which applications needs it to be. Linux pipe-lining is a good example for a data-stream where you inject output from one function into another. And Java-Streaming API is another good example. 

Should or Should Not ?   

There are some good frameworks for Reactive Programming. ReactiveX has produced Reactive Extensions for major programming languages. React is another good Reactive JavaScript Framework. 

Even-though lot of programming paradigms available we should use them very carefully only in accordance with the requirement. So, it is not good to go 'reactive' every where. But if the requirement is event-driven, responsive program then it is better to use 'reactive'.  Please refer to this blog post and ReactiveX home page for more details.