Skip to main content

Posts

Showing posts from 2019

Decorator Design Pattern In Java

Greetings!

Decorator desgin pattern is a structural design pattern.
This is a pretty standards pattern in Java, especially in code related to input/output classes such as FileReader, BufferedReader.

Full source code for this blog post is at my github account. [source-code]

GoF definition.
"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality."


This is very powerful pattern to add extra funtionality to an object through composition. Interestingly, we are doing it at runtime.
This gives us an alternative to subclassing.

"Subclassing adds behaviour at compile time, decorator adds behaviour at run time."
When we use inheritance to add additional functionality, we may end with long heirarchy with too many classes. With decorator design pattern, we only need to create base and additional functionality can be added by decorating that base.
This is sometimes called as wrapper. Term …

Template Method Design Pattern In Java

Greetings!

Template Method pattern is a behavioral pattern.
We put our businesss logic in abstract in a super class and let the sub classes override specific steps without changing the original structure.

Source code for this post can be found in my github account. [source-code]

When we have a common steps to do something but some steps vary, we can do it using bunch of if else statements. But the problem is things are tightly coupled and when new things need to be added we have to change our class. This leads our class difficult to main. For these kind of problems Template Method can be used.

Definition of Gof;
"Defines the skeleton of an algorithm in a method, deferring some steps to sub-classes. Template Method lets sub-classes redefine certain steps of an algorithm without changing the algorithm's structure."

"Don't call us, we'll call you. - allow low-level components to hook themselves into a system, but the high-level components determine when they are …

Strategy Design Pattern

Greetings!

Strategy pattern is a behavioral pattern. It is one of the easiest patterns to learn and one of the most used pattern.

Source code for this blog post can be found in my github account. [source-code]

Let's see the GoF definition;
"Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."

"Algorithm" in this definition is not necessarily a mathematical algorithm. It is something that do a thing. Basically algorithm is just another name for a strategy.
This leads us to;

A class should be configured with an algorithm instead of implementing an algorithm directly.An algorithm should be selected an exchanged at run time.
When we start OOP, we are fond of inheritance. But when it comes to separating the code into more manageable way, we choose composition over inheritance.
"Consider 'has-a' instead of 'is-a'"
We achieve this by extracti…

Factory Method Design Pattern

Greetings!

Factory method design pattern is a creational design pattern which deals with creating objects.
Many misunderstand this pattern with simple factory helper class.

Source code for this post can be found in my github account. [source-code]

This is the definition given by GoF.
"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses."
As in original GoF design pattern, we define an interface (abstract class) to create objects that lets the sub-class to decide how to create the object.


Let's see the actors in this design pattern.
Product - This is the final object we need to create. We are dealing only with abstraction here because we can have multiple types of products.Factory - A class to create Product. But it doesn't directly create object. Instead it provides abstract method to create the Product. Sub classes of the Factory needs to implement that creation…

Builder Design Pattern In Java

Greetings!

Builder design pattern is a creational design pattern which helps us creating objects.

According to GoF, Builder design pattern;
"Separate the construction of a complex object from its representation so that the same construction processes can create different representations."
Eventhough the original pattern description talked about complex object creation, most used scenario is to help constructing objects fluently.
Builder design pattern helps us to assemble objects part by parts hiding inner states.

In this post i'm going to talk only about normal object creation using this pattern.



As I said earlier, this is a convienient way to construct objects with many parameters. Let's say you have a class which needs 10 parameters. Are you going to create a constructor with 10 arguments? Which is very difficult to maintain and use. This is where i'm giong to use Builder design pattern.
Help to create objects with multiple parametes in simple way.
Create immuta…

Observer Design Pattern In Java

Greetings!

Greetings!

Observer design pattern falls into behavioral category.

Observer design pattern is useful when we have multiple objects doing things according to another objects changes.
This main object is callsed Subject and depending objects are called Observers.

Subject and observers are loosely coupled and have no knowledge of each other. Subject(one) ----> Observer(many)
Swing event listner, Spring listner are some examples for Observer desgin pattern.

Observer design pattern according to GoF,
"Define a one-to-many dependency between objects so that when one object changes state, all its dependencies are notified and updated automatically."


Subject Maintain a list of observers who are interested in getting notified when something useful is happend.
This provides methods to register the Observer, unregister the Observer and a method to notify all Observers at once.

Observer Object which is interested in Subject's changes. Has a method to get updates from the …

How to dockerize a spring boot application

Greetings!

Spring boot helps us to create application very quickly. Docker provides us a way to "build, ship and run" our applications. In a world of Microservices, combining these two gives us powerful ways to create and distribute our Java applications.

I assume you have enough Spring boot and Docker knowledge and want study further to dockerize Spring boot applications.

https://github.com/slmanju/springtime/tree/master/spring-boot-docker

Let's create a simple rest service and dockerize it.

Step 1: Create Spring boot application Go to https://start.spring.io and fill it as you want. Then add Spring Web Starter as a dependency. This is enough for us create a simple rest service. Download and extract the application. Then add below controller (or anything you like).
package com.slmanju.springbootdocker; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HomeController { …

How to use Spring Boot with MySQL database

Greetings!

Spring Framework simplifies working with databases by auto configuring connections, handling transactions, using ORM tool like hibernate, abstract sql by Spring Data Repository. We are going to focus on how to connect MySQL database with Spring Boot application.

Sprint Boot has many defaults. For databases, H2 in-memory database is the default database. It auto-configures in-memory databases even without connection url. Those are good for simple testing. For production use we need to use a database like MySQL.

Spring Boot selects HickariCP Datasource due to it is performance. When spring-boot-starter-data-jpa dependency in classpath it automatically pick HickariCP.

complete source code this blog post is here.

How to configure a database Obviously, to use a database in our application we need;
Database driver to connect to databaseConnection urlDatabase username and password In Spring Boot application we need to provide atleast connection url, otherwise it will try to configu…

Microservices - Distributed tracing with Spring Cloud Sleuth and Zipkin

Greetings!

Microservices are very flexible. We can have multiple microservices for each domain and interact as necessary. But it comes with a price. It becomes very complex when the number of microservices grow.
Imagine a situation where you found a bug or slowness in the system. How do you find the root cause by examinig logs?

Collect all the logs from related microservices.Pick the starting microservice and find a clue there using some id (userid, businessid, etc).Pick the next microservice and check whether the previous information are there.Keep going until you find which microservice has the bug.
I have followed that practise in one of my previous projects. It is very difficult and takes a lot of time to track an issue.
This is why we need to use distributed tracing in microservices. One place where we can go and see the entire trace.

It helps us by;
Asign unique id (correlation id) to all request.Pass unique id across all the microservices automatically.Record time information.Log…

Cracking Java8 Stream Interview Question

Greetings!

I have faced many interviews (too many to be frank) in my career as a software developer. In most of those interviews I have been asked to write a pseudo code for a given problem and implement it in Java. With Java8, this implementation mostly should be in Java8.
When I look back all those questions it can be simplified as below. (difficulty may be vary though).

Iterate over a given collection (stream)Filter the given data (filter)Transform into another format (map, reduce)Collect data into a collection (collect)or End the stream (forEach, min, etc)
Is this familiar to you? This should be. This is what we do in our daily work. But, if you are blindly using it you will see it as a difficult question to answer.
You need to have good understanding about intermediate and terminal operations. And, you need to really practise and use in daily work. It is meaningless to pass an interview without knowing these.
java-8-streams-intermediate-operations
java-8-streams-terminal-operations

Angular - Let's create a starter project

Greetings!

Angular has many things to learn though we can skip those and directly create simple project. It will be harder to study all the features first. So here, i'm going to directly create a simple starter project.

This is the end result of this tutorial.



Install Angular CLInpm install -g @angular/cli ng version
Create a projectng new angular-store --routing --style=scss cd angular-store npm install
This will create a basic app structure.
Run the projectng serve --open # short form ng s -o
With zero code, we have a running template. That's some power.

Angular Material Let's add material UI design into our project. For more information visit https://material.angular.io/
Below command will add angular material into our project and update neccessary files.
ng add @angular/material
We want to use material design component in our project. To add material components in a single place let's create a separate module named material and update it with neccessary materaial …

Microservices - Api Gateway

Greetings!

I was too busy past couple of days and lost my way of continuing Microservices series. So I decided to add simple dummy services service-a and service-b. Other than that, there is no change except the github repo.

https://github.com/slmanju/simple-microservice

In Microservices architecture we are dealing with many apis which work along or work with other services. Imagine that we are going to create a mobiile client using these client it will be very difficult to manage all services by that client. Or, imagine we expose our apis so that anyone can create their own client.
This is a good place to introduce a another service which act as a gateway to all other services. Third party clients will know only about this api.
Not only this, we can solve some other problems using Api Gateway.

Single entry point to all the services.Common place to log request and responses.Authentication users in single place.Rate limits.Add common filters.Hide internal services.

To create our api gate…

Kafka - Spring Boot

Greetings!

In this blog post i'm going to explain how to integrate Kafka with Spring boot. We use Spring boot configuration to send Kafka message in String format and consume it. Let's begin.
(complete example can be found here.)

Starting up Kafka First of all we need to run Kafka cluster. For this i'm using landoop docker image.
Here is the docker command to run landoop docker container.
docker container run --rm -it \ -p 2181:2181 -p 3030:3030 -p 8081:8081 \ -p 8082:8082 -p 8083:8083 -p 9092:9092 \ -e ADV_HOST=127.0.0.1 \ landoop/fast-data-dev
Generate the applicationI'm using Intellij idea IDE to generate the Spring boot application. I have selected web, lombok and
kafka dependencies.
Let's rename application.properties to application.yml to use yaml format.
Here is my application.yml file configuration values.
server: port: 9000 spring: kafka: producer: bootstrap-servers: localhost:9092 key-serializer: org.apache.kafka.common.serialization.St…

Docker - Dockerfile

Greetings!

We used Docker images to create containers multiple times. We used images from Docker Hub to create those containers. Ever wondered how to create a Docker image? Docker can build images automatically by reading the instructions from a Dockerfile.

Dockerfile A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Think of it as a shellscript. It gathered multiple commands into a single document to fulfill a single task.
build command is used to create an image from the Dockerfile.

$ docker build . You can name your image as well.
$ docker build - my-image .
Let's first look at a Dockerfile and discuss what are those commands.
This is extracted from official MySQL Dockerfile.

FROM debian:stretch-slim # add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added RUN groupadd -r mysql && useradd -r -g mysql mysql RUN apt-get update &&…