Tuesday, November 21, 2017

Template method design pattern

This is another very important design pattern in Java and another core design pattern which is used in Spring framework.Template method design pattern is a behavioral design pattern. This is used to define a the flow of execution of the application.

Just think you need to build a building. Then you should begin it with foundation. You can't begin it with the roof. Likewise you can define the flow using this design pattern. 

Look at the following example. 


package com.app.designPatterns;

abstract class Building {

    abstract void makeFoundation();
    abstract void makeWalls();
    abstract void makeRoof();

    public final void build(){
        makeFoundation();
        makeWalls();
        makeRoof();
    }
}


class OfficeBuiding extends Building{

    @Override
    void makeFoundation() {
        System.out.println("Make foundation");
    }

    @Override
    void makeWalls() {
        System.out.println("Make walls");
    }

    @Override
    void makeRoof() {
        System.out.println("Make roof");
    }
}

public class TemplateDemo{

    public static void main(String args[]){
        Building building = new OfficeBuiding();
        building.build();
    }
}


Here you can see three classes. If you going to build a office building, it will be done in certain way. This flow cannot be changed. So if you want to create another building, you can do the same way. 

As you can see, the template method is final. That is why it cannot be changed. Look at the following class diagram for two buildings.


When it uses ?
  • javax.servlet.http.HttpServlet doGet() and doPost() methods.
  • In Spring framework - In Spring framework, it uses so many templates. These templates are created based on template method design pattern. 
  • All non abstract methods of followings
    1. java.io.InputStream
    2. java.io.OutputStream
    3. java.io.Reader
    4. java.io.Writer 
  • All non abstract methods in followings too.
    1. java.util.AbstractList
    2. java.util.AbstractSet
    3. java.util.AbstractMap
  • JDBC template uses this design pattern - In JDBC template we don't need to care about the open, close connections and so on. This is automatically done by the template itself. It executes the core workflow, we don't need to manage it. 



Compile-time polymorphism vs Run-time polymorphism



This is very important interview question. Simply Compile-time polymorphism is known as overriding and Run-time polymorphism is known as overloading. I think you may know about the differences between both of overloading and overriding. (OOP concepts)


But question is this, If someone asked why it is called compile-time polymorphism and run-time polymorphism ? Lets try to find out the answers by examples.

Overriding is called run-time polymorphism. WHY ???


Look at the following example.

//Parent class
class Parent {
    public void eat(){
        System.out.println("Parent - eat()");
    }
}

//Child class
class Child extends Parent {

    @Override
    public void eat() {
        System.out.println("Child - eat()");
    }
}

public class OOPDemo {

    public static void main(String args[]){
        Parent obj = new Child();
        obj.eat();
    }
}



In this example I've created a parent class, child class and the main class. Then I've created a Child object by Parent reference. 

Compile time
  • In compile time it takes care about the Parent reference. Because objects are created in the run time
  • First it checks is there any eat() method in Parent class. 
  • In this example Parent class has eat() method. 
  • So it doesn't give any exception in the compile time and compilation will be success.
Run time
  • In run time it takes care about the Child reference and it creates new Child object.
  • Then it checks is there any eat() method in Child class. 
  • There is a eat() methods in Child also. Then this method will be called in the run time. 
  • It means object creation is happen at the run time by JVM and Run time is responsible to call which eat() method to call.
  • That is why it is called run-time polymorphism (Dynamic polymorphism)

Overloading is called compile-time polymorphism. WHY ???

Look at the following example.

class Animal{

    public void eat(){
        System.out.println("Eat method");
    }

    public void eat(int quantity){
        System.out.println("Eat method with quantity");
    }
}


public class ReferenceDemo {
    public static void main(String args[]){
        Animal animal = new Animal();
        animal.eat();
    }
}



In this case single class has same methods with two different parameters. As you know it is called method overloading. 

Compile time
  • In compile time it checks animal.eat() method in Animal class. 
  • No arg eat() method is there in the animal class.
  • According to the parameter list it will call which method should be called.
  • Then compilation is OK.

Run time
  • In run time it creates same Animal type object.
  • Then it checks the same thing what is did in the compile time.
  • It means compile time is enough to check which method should be called.
  • That is why it is called Compile time polymorphism ( Static polymorphism).


Finally

Overriding    = run-time polymorphism         = dynamic polymorphism
Overloading  = compile-time polymorphism  = static polymorphism




Wednesday, November 15, 2017

Monolithic architecture vs Microservices architecture

If you need to create an enterprise application according to your needs, first of all you should think about the architecture which your application depends. Mainly there are two approaches to begin.



  1. Monolithic architecture
  2. Micro services architecture

Monolithic architecture

  • It is just like a laptop. All things are packed as a single unit.
  • Monolithic architecture means, it makes your application as a single unit. 
  • It looks just create a single jar or war.
  • This is the easiest way to create an application. 
  • If the process goes with waterfall model, this can be the best choice.
  • But if you have a heavy project, application code base will be huge.
  • Still if you want to go with it, you should have a proper coding standards with comments. Otherwise it won't be easy to for future developments. 

Advantages of Monolithic architecture
  • Easy to develop
  • Easy to deploy
Disadvantages of Monolithic architecture
  • Not easy to expand services (Continuous development is difficult).
  • It is really hard to go with Agile method.
  • Huge code base. It is really hard to understand for new developers in future.
  • In this architecture all of the services are connected to one single database. So it will make huge server load.
  • Sometimes it will take a long time to start the web application because of the overloaded web container. 

Microservice architecture


  • It is just like a desktop computer. Several units work together. 
  • I described about Microservices in my previous post. 
  • Microservice architecture makes your application as a set of loosely coupled services.
  • There are a small set of services connecting each other as a one application. 
  • Simply it is not a one single project which is connected to one single database.


Advantages of Microservices
  • It is easy to handle errors. Because services are independent.
  • Easy understanding curve for developers for future developments.
  • Each services can be developed independently.
  • One of the best option for Agile development.
  • Application starts fast and runs smoothly.

Disadvantages of Microservices

  • Creating a microservice based application is really complex.
  • Testing is more difficult.
  • It should have a better communication between developers. Because several services will hit only one front end.
When to use Microservices ?

This is totally depend on the organizational requirements. Microservices produce a pack of services and enables fast delivery with easy testable units. If your company needs to go faster than ever, it may be a reason to change system with microservices. 

Other reason is, if your system is still growing with adding new functionalities, it is better to use microservices. Because microservices are small components of services, You can add new components according to your requirements. 


Tuesday, November 14, 2017

Maintain server logs

Maintain logs in very important thing. There are lot of ways to do this. Here I'm not going to do hard things. This is just a simple example of maintain server logs using a shell script.

Here I'm planing to do some tasks.
  1. Delete old log files
  2. Save last log file 
  3. Zip it and save in another place.
This can be used in your local server to maintain logs and it will be very easy because you need not to delete logs every time and save logs.


#!/bin/bash
# Delete files

#file path for logs
file_path='/opt/tomcat/logs/';

#file path for eventspace default log
file_path_myApp='/opt/tomcat/logs/myApp/';


#files to be deleted
file1='catalina.2017-*';
file2='host-*';
file3='localhost*';
file4='manager*';

#Get the yesterday
yesterday=$(date -d '-1 day' '+%Y-%m-%d');

#get the full file name of last day server.log
lastLogFile="server.log.$yesterday"

cd $file_path;

#remove files in file_path

rm $file1
rm $file2
rm $file3
rm $file4

cd $file_path_eventspace;

if [ -s $lastLogFile ]
then 
 #backup the last log file as zip
 tar -zcvf $lastLogFile.tar.gz $lastLogFile;

 #move file to var/logs/myAppLogs
 mv $lastLogFile.tar.gz /var/log/myAppLogs/
 
 #remove last log file
 rm $lastLogFile;
else
 echo "Last log file canot be found";
fi

#end



Sometimes it will be not easy to understand if you are a beginner. Let me explain.

There are two file paths.

  • file_path - Location of default log file located.
  • file_path_myApp - Location of application log file located

Then I've defined four file types that needs to be deleted. 

  • file1='catalina.2017-*';
  • file2='host-*';
  • file3='localhost*';
  • file4='manager*';

Then I get the date of yesterday because I need to to zip yesterday log file with the date as a file name (lastLogFile).

Then I remove files using rm command in Linux. 

  • rm $file1

Then I zip the yesterday file using tar -zcvf command.

  • tar -zcvf $lastLogFile.tar.gz $lastLogFile;

Then I move file to another location using mv command. 

  • mv $lastLogFile.tar.gz  /var/log/myAppLogs/



There are many file paths, you need to change all those file names with your locations. All commands are simple Linux commands. 

How to run a shell script file

Once you create your .sh file, you need to run it from terminal.
  • Go to your file location and right click and open terminal in same location( Otherwise you will need to change the path ).
  • Give file permission to the file.
                    chmod +x fileName.sh
  • Run your sh file.
                  ./fileName.sh



Add a cronjob

Another special thing is you can add your script as a cronjob and it will run automatically according to the parameters which are given. For example if you need to run it in every minute, you can add following line to system crontab.

* * * * * /media/ravi/Data/Cronjob/deleteLogs.sh

Open you terminal and type crontab -e




Add your cronjob (Above mentioned line)



Save file.

  • Ctrl + X
  • Type y
  • Enter

You will be able to see like this.





You can change your cronjob with your requirements. 


Data access object design pattern



This is another very important design pattern. Before you learn about this design pattern, it is better to understand about following points. 

What is DAL (Data Access Layer) ?

  • Simply data access layer is used to handle database access in applications.
  • In Layered Architecture, it is a best practice to use a separate layer for data access.
  • Data access layer is being used to achieve this.
  • DAO design pattern and Repository design pattern can be used to implement that Data access layer.


What is DAO (Data Access Object) ?
  • Usually this is used to connect both service layer and database layer as I mentioned above.
  • The main purpose of using DAO is to hide implementation data with the usage of interfaces.
  • Normally we define DAOs for each and every entity. Eg: UserDao.java
  • DAOs return data as object state.

What is DTO (Data Transfer Object) ?
  • Simply this can be a JSON object that can be used to get request data and send response data. 
  • If you design APIs, JSON objects are being used as request and response objects. Eg: UserRegRequestJson.java, UserRegResponseJson.java

Look at the following UML diagram to understand about the way of using DAO design pattern. 




Advantages of using DAO 

  • Hide implementation data.
  • Reduce code complexity.
  • Centralized data access to separate layer called Data Access Layer.

Disadvantages of DAO

  • This is not the smartest way to achieve those advantages, if you are using a framework like Spring with Spring Data JPA, it can simplify everything than using DAO.




Wednesday, June 28, 2017

Spring Boot Hello World project

What is Spring Boot ?


Spring Boot is an awesome framework which was created by Pivotal team to built Spring based applications. I assume you've already created at least one spring based application in older approach. Unless, try this Spring MVC hello world project  to understand about it before learning Spring Boot. 

Spring Boot can be used vastly to create Microservices. Then you need to have an idea about Microservices. Before you learn about Microservices, it is better to understand about SOA (Service Oriented Architecture).


What is a SOA (Service Oriented Architecture) ?

  • Service Oriented Architecture is a architectural design.
  • It makes your project into several loosely coupled services. 
  • It make your code easier to develop, run and test. Because it makes a huge code into separate layers.

What is a Microservice ?

  • Microservice is a kind of Service Oriented Architecture. 
  • As to Pivotal they define it as "Loosely coupled service oriented architecture with bounded context".
  • It improves resilience and component re-usability. 
  • Actually microservices are not simple things to implement and it should be done in well organized way.
  • It takes high cost and it is really depend on your company and the project needs which you are going to develop.
  • Look at the following image to identify the difference between Monolith vs Microservices 
Image credit : https://dzone.com/articles/comparing-microservices-and-monolithic-application
Read more about Monolithic vs Microservices

Why Spring Boot ?

  • Spring Boot has developed to achieve loosely coupling concept.
  • Spring Boot acts as a template which can be used to implement Spring applications easily. 
  • As you know, Spring framework is based on loosely coupling. Microservices are also used to create applications with loosely coupling concept. 
  • Now you will be able to understand what is the link between Microservices and Spring Boot. 

If you familiar with Spring framework, it will be  very easy to work with Spring Boot because Spring Boot can simplify whatever the thing that you develop with pure Spring. 

Why does it say Spring Boot is easy ?


  • Easy dependency management
Once you create Spring Starter project, it will automatically download related dependencies according to your need and what you've selected.  

  • Embedded servlet container
Spring Boot comes with Apache Tomcat embedded server which is running on http://localhost:8080.  If you need any other servlet container, just you can exclude tomcat and add any other container that you need. Again if you want to change the listening port, you can change it on application.properties file very easily.
  • Automatic configurations
If you are familiar with Spring MVC, I think you can remember dispatcher-servlet.xml, application-context.xml...etc. In Spring Boot, those configurations are automatically done by itself. You don't need to worry about it.

  • Easy configuration management
Spring Boot is very powerful with application.properties file.

  • Spring Boot Dev tools

Spring Boot Hello world


Step 01

Create a new Spring Starter project. Look at the fields that I've filled. You can choose build type, package type, Java version...etc. Otherwise you can create you project online with https://start.spring.io/



Step 02

Once you've clicked Next, following configuration window will be appeared. You can choose whatever the dependencies that you need according to your project. It is really easy to insert dependencies than older way. I've selected web. It automatically download the related dependencies into your project.



Step 03

Finally your project structure will be look like this. 



Step 04

I created a controller class called "RestController.java" in a separate package and created just a simple method called "showHello()".

package com.app.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;

@org.springframework.web.bind.annotation.RestController
public class RestController {

 @GetMapping("/hello")
 public String showHello(){
  return "Hello world";
 }
 
}


I think you are familiar with @Controller annotation. In here I've used @RestController annotation. This makes a class as a controller and methods in this class will return only domain objects instead of views. Then you don't need to worry about view. Just you can run this.

I have used @GetMapping annotation too. This can be used instead of using @RequestMapping (method=RequestMethod.GET, value="/hello"). Both are same. You can use @GetMapping to GET requests and @PostMapping to POST requests.  

Step 05

I've mentioned String Boot is packed with embedded server. You can use it very easily. Right click on the project, go to Run As and then select Spring Boot project.




Once server is started you can run your simple Hello world application as follows.

http://localhost:8080/hello



How easy is this. You need not to create server instances, adding projects, build projects...etc. Just you can run it. 

Look at the following server log.



Sometimes you will get an error with server port. you can check listening server ports by hitting netstat -ao on command prompt. It will show Local address, port , status and PID(Process Identification Number). You can terminate current listening port or you can change the embedded server port using application.properties file.
  1. If you want to terminate the current process of 8080 port, just you can hit netstat -ao and then identify the PID of related listening port. Then you can hit taskkill /F /PID {PID number} For example "taskkill \F \PID 10920". Then you can run your application again. 
  2. Other way, you can simply change the embedded server port. In you application.properties file, add server.port=8083 line. Then it will run on 8083 port. This is very simple. As I mentioned above, Spring Boot provides a lot of simple configurations in application.properties file. 
Or else you can kill the java process using Task Manager.

This is a simple demonstration of hello world application in Spring Boot. There are some other ways to do the same.



Advantages of Spring Boot

  • Spring Boot is simple.
  • Automatic configurations and easy to change properties.
  • It can be created runnable jars with embedded tomcat. (mvn spring-boot:run)
  • Very easy dependency management.
  • Very good solution to create Micro services.
  • Strong support for related Spring applications.
  • Spring Boot Dev Tools provides a bunch of advantages.
  • Good production support (Health checking, jvm metrics...etc)

Disadvantages of Spring Boot

  • Even though Spring Boot is simple, you need to know the concepts of Spring.