Getting started with Spring Boot

This is a short tutorial about creating a simple REST webservice with spring boot. This assumes you have basic knowledge of Spring and Java.

To get started we will create a Spring project. The simplest way to do this is to go to and create a project.

This will give us a blank project on which we can build upon. Import the project as Maven project to Eclipse or any other ID. By default, it will provide a class which will look like

public class NewtestApplication {

	public static void main(String[] args) {, args);

As you can see this is the main class and all the execution starts here. Also, note the @SpringBootApplication annotation. Spring documentation states that

“The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes”

For this example, we will keep it simple and introduce a controller

public class HelloController {
	public String sayHello() {

Finally, Run the main class as a normal Java application, it will automatically start the Spring Boot server at 8080.

We can now access our application at http://localhost:8080/sayhello

Updating Java version in Linux

Recently I upgraded my Java version from 9 to 10 on a Linux machine. I was able to set JAVA_Home in .bashrc file properly but version did not get updated when checked java -version on shell.

Following commands helped to change the system’s Java version

sudo update-alternatives --install "/usr/bin/java" "java" "/path/to/jdk-10.0.1/bin/java" 1

And then

sudo update-alternatives --config java

This showed all the Java versions available and I was able to choose correct version i.e. 10.
Similary executed same commands for java compiler.

sudo update-alternatives --install "/usr/bin/java" "java" "/path/to/jdk-10.0.1/bin/javac" 1
sudo update-alternatives --config javac

Designing a Solution with AWS

When one goes for a Cloud based solution with solution provider like Amazon AWS, there are 2 things which are important. One, you need to have a clarity on what you are trying to achieve, and second is understanding of the services being provided by the provider.

Both the aspects are equally important. AWS provides plethora of services which can amuse at the same time confuse one. You might be tempted to use services which might not be required for your project and unnecessarily adds to the cost. At the same time if services not used with proper understanding, can backfire in terms of output and cost. For example, in one of my projects, incorrect implementation of autoscaling ended up running unused servers adding to cost instead of saving it.

Additionally, one need to be aware of all the capabilities of the service provider, for example, what all database and backup services we can use, can we use caching services, monitoring services provided by the service provider. Otherwise you will end up putting in unnecessary effort in rebuilding the wheel.

Here is a good starting point for AWS usage –

Features in Java 9

Java 9 might not be adding major changes like Java 8 which had features like Lambda or Streams or Interface modification, but it does have some good additions.

JShell: If you have worked in python or ruby, you might be aware of shell features these languages provide to quickly run and analyze commands and snippets. Java has come up with similar shell as JShell in Java 9 where you can evaluate the system.

Java Modules/ Jigsaw: Java has taken further step towards modularization. You can define your application in forms of modules and tell JVM what all modules will be used by current module, and what all modules will be exposed which can be used by others.

Private Methods in Interfaces: Java 8 gave us liberty to add method definitions in form of static and default implementations. With Java 9, one can add private methods to help us with organising our code better.

Additional Reads

AWS CloudFormation

When you are setting up an environment on AWS cloud, you need to go through many steps, like creation of IAM roles, Security groups, Databases, EC2 instances, load balancers etc. Often one resource is dependent on other and hence you have to create components one by one which can be time consuming. With Cloudformation scripts one can easily get the deployment steps automated. And most importantly, the script is reusable any number of times. So if I want to replicate a stage setup on production or another setup in another region, it is easily possible.

One can create template in JSON or YML formats. The template is submitted to cloud formation which executes the template and create the stack which is actual environment with all the mentioned components.

Another important thing is that you can not only create infrastructure, but also do required settings. For example, I needed to get setup for application done on EC2, which I was easily able to do with UserData section.

Here is an example

        Type: AWS::EC2::Instance
            InstanceType: XXXXX # type here
            ImageId: ami-XXXX # any ami here
            KeyName: XXXX # name of the key if already exising or create a new one
            IamInstanceProfile: !Ref InstanceProfile
            - AssociatePublicIpAddress: true
              DeleteOnTermination: true
              Description: ENI for bastion host
              DeviceIndex: '0'
              SubnetId: subnet-XXXXX
              - !Ref AppNodeSG
                "Fn::Sub": |
                  cd /root/
                  apt-get update
                  apt-get -y install awscli
                  aws s3 cp s3://XXXX/XXXX.XXX ~/some location
                  #One can install servers, download wars and deploy at runtime
        Type: AWS::EC2::Instance
            # create another instance
        # Security group to give access to ssh and port 80
        Type: AWS::EC2::SecurityGroup
            GroupDescription: SecurityGroup for new AppNode
            VpcId: vpc-XXXXX
            - IpProtocol: tcp
              FromPort: 80
              ToPort: 80
            - IpProtocol: tcp
              FromPort: 22
              ToPort: 22
        Type: AWS::IAM::InstanceProfile
            Path: /
            Roles: [S3FullAccess] # S3FullAccess Role created Manually, so that my EC2 instance can access S3.

Features added in Java 8

I have already talked about 2 most important features added in Java 8 in my last posts, i.e. Lambda and Streams. Apart from these there were few interesting additions.

Method definition in interfaces: For long time, Java has avoided multiple inheritance due to dreaded diamond problem. They had given us interfaces which did not had method definition, which could have been implemented by a class in multiple numbers. Now, Java has relieved the restriction a bit by allowing static and default methods definition in interfaces.
What about multiple inheritance diamond problem? Well if compiler cannot decide which implementation to use it will thrown an exception.

ForEach: For Collections like Lists, instead of creating an explicit iterator one can use forEach.

Optional: There can be a situation when a method can return null, in such situations the value can be saved in optional class.

Good reads:

Lambda expressions in Java

Lambda expressions in java is a way to implement functional interfaces. Functional interface is the one which only has single unimplemented method. This gives us freedom from creating a class or anonymous class. In addition Lambdas can be used with streams.

Here is an example. Download the code here

import java.util.ArrayList;
import java.util.List;

public class Jaba8Lambda {

	interface Operations{
		public int operate(int a, int b);
	public static void main(String s[]) {
		System.out.println("Welcome to Lambdas");
		// A simplest form of lambda, same interface, multiple implementations without a class
		Operations sum = (int a, int b)->a+b;
		Operations multiple = (int a, int b)->a*b;
		//Java8Lambda obj= new Jaba8Lambda();
		int mysum = sum.operate(2, 3);
		int myproduct = multiple.operate(2, 3);
		// Another example using Thread Runnable
		// Earlier you would create a Runnable
		Runnable myrun = new Runnable() {
			public void run() {
		new Thread(myrun).start();
		// With Labdas we can do away with anonymous classes
		Runnable myrunLambda = ()->{
		new Thread(myrunLambda).start();
		// Lambdas can be used with streams as well
		List intlist= new ArrayList();
		Stream stream =; 
			if(i%2==0) {
				System.out.println(i+" is even.");


Java Streams

Java had introduced streams in Java 8 to help us fasten the development by providing ways to perform operations on data streams (collections) without writing bulky code.

In short, stream can be thought of stream or pipeline of data, on which you need to perform some operations. There can be two types of operations, intermediate and terminal. Intermediate operations are the ones which transforms the data in the stream, but the output is still a stream, for example filter or map operations. On the other hand terminal operations are ones which are applied collectively on the stream and output is something other than stream for example sum or reduce methods.

Here is an example usage to make it more clear. Or Download code from git repo

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Java8Streams {
	public static void main(String s[]) {
		System.out.println("Welcome to streams!");
		//There are multiple ways to create streams
		Stream stream = Stream.of(new Integer[]{1,2,3,4}); 
		Stream intStream = Stream.of(1,2,3,4);

		// Using streams to find sum of a integer list
		List intlist= new ArrayList();
		Stream streamnew =; 
		// No more looping through the array
		Integer sum =>i).sum();
		System.out.println("Sum is :"+sum);
		// Lets check if the array contains even number, without looping
		boolean anyEven=>i%2==0);
		// Check if all elements are even in the list
		boolean allEven =>i%2==0);
		// Find first even number from the list
		Optional firsteven=>i%2==0).findFirst();
		// Now lets sum all even numbers
		int sumeven =>i%2==0).mapToInt(i->i).sum();
		// Lets use forEach to do operations on each element, say add a constant number to even numbers and print>{
			if(i%2==0) {
				i = i+100;
		//Better way to achieve the above>i%2==0).forEach(i->{
			i = i+100;
		// Simliar to filter, we gave map function
		List newlist =>{
			return i+100;
		// Use reduce to perform some custom operation
		Optional output =>{
			return i+10;
			return i*j;


Machine Learning- Additional Concepts

In last post I talked about Machine Learning basics. Here I will take up a few additional topics.

Before getting into Recommendation Engine, lets look at a few concepts
Association Rule mining: At times we try to figure out association or relationship between 2 events. For example, we might say that when someone buys milk he might buy bread as well.

Support: Support is an indication of how frequently the events/ itemset appears together. If Event A is buying of milk and Event B is buying of Bread.
Support = number of times bread and milk are bought together/ total number of transactions

Confidence: Confidence is an indication of how often the rule has been found to be true.
number of times A and B occurs/ A occurrences = Supp(A U B)/Supp(A)

Lift = Supp(A U B)/ Supp(A)*Supp(B)

Apriori Algorithm: This algorithm tries to find out items that can be grouped together. It starts from bottom, ie tries to find subsets which are found together and moves up, based on the concept that it a set has items that share a relationship, all subsets also follow the relationship.

Market Basket Analysis: Market Basket Analysis is a modelling technique based upon the theory that if you buy a certain group of items, you are more (or less) likely to buy another group of items.

Recommendation Engine: When we buy something from an ecommerce store or watch a video on video streaming site, we get various recommendation for our next purchase or view. This is done by recommendation engines running behind the scenes.

There are two common types of recommendations used by these engines

User based/ Collaborative Filtering: If you have watched a video on a site like netflix, the system will look for more users who watched the same video and try to figure out the next most common video most of the users watched and recommend it to you.
Content based Recommendation: Instead of user behavior, the engine will try to segregate the contents based on its properties, for example, movie genre, actors, directors etc. So if you watched an action movie, the engine will try to look for movie with similar content, actors, directors, plot etc.


Text Mining: Not always one will get clean and ready to use data which can be fed to algorithms to start analysis with. A common use case for text mining is Review. Customer provide review about the products or movies in plain english. It is a tricky task to make machine analyze these texts and figure out what is the opinion being shared.

Here are a few common techniques used for text mining.

Bag of Words: This is a simple modeling technique which try to figure out word counts. Data cleanup is done by removing punctuation, stop words (to, a, the etc), white spaces etc. After that algorithm runs and find out count of each word used. This technique is good for tagging documents by understanding common word patterns being used.

TD-IDF: Term frequency- Inverse Document Frequency
Term Frequency = number of times a term occurred in a document/ total terms in document
Inverse document frequency = total number of documents/ number of documents with term ‘T’

Sentiment Analysis: Here we try to figure out the sentiments, for example if a review provided is positive or negative. If there are terms such as- like, loved, enjoyed etc, we might want to consider it as positive review.

Time Series:
There are problems when we need to handled time based data for example stock prices. We will need to store data in time series where each value is associated to a point in time.
When analyzing time series data, there are a few interesting insights one looks for

Trend: one looks for data movement with respect to time in upward trends, downward trends, horizontal trends etc.
Seasonality: Looks for same pattern during the year. For example fruit prices go up during winter every year.
Cyclic patterns: At times the patterns go beyond the year, eg. a particular trend is seen in 3 years or so. The pattern might not have a fixed time period.
Stationarity: Refers to stability of mean value though there is no specific pattern.

Reinforcement Learning: This is based on reward and penalty approach. The agent / engine is intelligent, which is provided constant feedback if the decision taken was correct or not. Agent can improve future decisions based on feedback provided.
Deep Learning: Sometimes referred to as Artificial Neural network(ANN), one can think of it as artificially replicating a Biological Neural Network (BNN).
There are three core areas of a BNN, a Dendrite (receive signals from neurons), Soma(sums up all the signals) and Axon(signals are transmitted through Axon). ANN tries to replicate the BNN by implementing artificial neurons. Read More-