How to Launch an EC2 Instance in AWS

Hello Friends,

In this tutorial,we will see how we can spin an EC2 instance in AWS in no time.

Prerequisite :

You should have access to the AWS console.If you don't have AWS account already,you can click here and and create free tier Account on AWS.

How to Launch an EC2 instance in AWS


Step 1 :

Login to Your AWS account with your credentials.

Step 2 :

Click on Services and you will see following screen


Step 3 :

Click on EC2 and you will see following screen :



Step 4 :

Click on Launch Instance and you will see following screen.Here basically you will find all available AMIs.

As per Amazon "An AMI is a template that contains the software configuration (operating system, application server, and applications) required to launch your instance. You can select an AMI provided by AWS, our user community, or the AWS Marketplace; or you can select one of your own AMIs."

If you want to see  "Free tier Only" AMIs,just check the checkbox in front of "Free tier only".

Step 5 : 

We will select "Amazon Linux AMI 2018.03.0 (HVM), SSD Volume Type - ami-08d489468314a58df" AMI by clicking on Select button in front of it.

It has following configuration :

The Amazon Linux AMI is an EBS-backed, AWS-supported image. The default image includes AWS command line tools, Python, Ruby, Perl, and Java. The repositories include Docker, PHP, MySQL, PostgreSQL, and other packages.


On Clicking Select,you will get following screen :



Here you have option to choose Instance Type.

As per Amazon,

 "Amazon EC2 provides a wide selection of instance types optimised to fit different use cases. Instances are virtual servers that can run applications. They have varying combinations of CPU, memory, storage, and networking capacity, and give you the flexibility to choose the appropriate mix of resources for your applications".

For detailed list of various Instance Types available in AWS,please check EC2 Instance Types.It tells you features of various Instance types and use case where they can be used.

Step 6 :

We will choose the default one,which is t2.micro ,which is from General Purpose family and is free tier.Click on "Next: Configure Instance Details" button and you will see following screen.



Some Important properties from above screen,we will discuss below.

Number of Instances : By default it will be populated as 1,which means that only 1 EC2 instance will be created.You can create more than 1 EC2 instance by mentioning number greater than 1 here.Also if you want to launch your EC2 instance in Auto Scaling Group,you can click on "Launch into Auto Scaling Group" and configure it to be launched in Auto scaling group.

Network : By default it is showing here the default VPC created by AWS.If you want to associate this EC2 instance with VPC created by you,you can click on "create New VPC" and then choose that VPC name.Alternatively it is also possible(Which is normally the case) that you first create your VPC and then come to this screen for Launching EC2 instance,in that case you will see your VPC name as well in the drop down and you can choose your VPC.

Note : Once you create an account in AWS,AWS creates
- A default VPC in each region for your account with size /16 IPv4 CIDR block 172.31.0.0/16.This provides 65536 private IP addresses.
- Create a size /20 subnet in each availability zone.This provides around 4096 IP addresses in each subnet.
- Create a internet Gateway and connect it to your default VPC.
- Create a default Security group and associate it with your default VPC.
- Create a default Network access control list(NACL) and associate it with your default VPC.
- Associate the default DHCP options set with default VPC.
- main route table

Subnet : Here you are given option to Launch your EC2 instance in a specific subnet or you have option to choose "No preference",in that case AWS will choose one of the subnet to launch your EC2 instance.

Auto assign Public IP : As default subnets are always public subnet,you will see that Auto assign Public IP option in enabled by default.Having public IP for your EC2 instance means your EC2 instance can communicate with internet.Also with public IP addresses,they are disassociated with instance once instance is stopped or restarted which means every time you restart your EC2 instance,your EC2 instance will get new IP address.

Enable termination Protection : You can protect your EC2 instance from being accidentally terminated via API or console,if you enable this protection.

Step 7 :

Click on Add Storage and you will see following screen.Here you will see the default storage provided by AWS for your t2.micro instance.The storage is named as EBS or Elastic block store.You can think of it as hard disk of your computer.Apart from this default storage you can add more EBS volumes by clicking on "Add New Volume".

Let us see one of the important property to discuss :

Delete on Termination : By default this,this option is turned on,which means that if you will terminate your EC2 instance,your EBS storage will also be deleted,so you will loose all your data on the storage.If you don't want so,you can uncheck this option.

Step 8 :

Click on "Next: Add tags" and you will see following screen :


Tag is basically key value pair which you can use to assign some name to your EC2 instance.For example you might be spinning this EC2 instance to use it as web server, in that case you can use key as "Name" and value as "Web Server".

Let us go ahead and add tag by clicking on Add tag.

Step 9 : 

Click on "Next :Configure Security Group" button and you will see following screen :


Security group basically define what traffic is allowed into your EC2 instance and what traffic is allowed out from your EC2 instance.

By default as you can see there is one entry which means that your EC2 instance can be connected from any where on the internet(0.0.0.0/0) using SSH and TCP protocol on port 22.

Also,you can see there is warning,which says that "Rules with source of 0.0.0.0/0 allow all IP addresses to access your instance. We recommend setting security group rules to allow access from known IP addresses only."

Which in other words is trying to say that this security is not a safe as anyone from internet can connect to your instance.so what you can do is configure more rules in security group which are more constrained.

Step 10 :

Click on "Review and Launch" button and you will see following screen :


Step 11 :

Click on "Launch" button and you will get following pop up.As you can see this pop up is for creating Key pair which you can use then to SSH into your EC2 instance.This is to make sure that only authorised person with valid private key only can access EC2 instance.


Give any name to key pair like "EC2Keypair"  and click on "Download Key Pair" button.It will save key pair on your local machine.

Step 12 :

Click on "Launch Instances" button and you will see following screen :


Step 13 :

Click on "View Instances" and you will see that your EC2 instance is spinning up and is in pending status


Step 14 :

Wait for 1-2 minutes and you will see that your EC2 instance is in running state


Step 15 :

Make sure that you stop your EC2 instance,if you don't want to use it and have created for learning purpose only,because there is cost involved if your EC2 instance keeps on running.Actually you should terminate it,to avoid the cost(of course if you don't want to use it any more).

For stopping ,go to Action -> Instance State -> Stop
For terminating,go to Action -> Instance State -> Terminate

Summary :

In this tutorial,we saw that how we can spin an EC2 instance quickly by going through following configurations :

Choosing Amazon Machine Image (AMI)
Choosing Instance Type
Configuring Instance details
Adding Storage
Adding Tag
Adding Security Group
Creating KeyPair and saving it

Please feel free for any comments,Questions or to share it with someone you feel it might be helpful.


How to Use Lombok to remove boilerplate setters getters in Java

Hello Friends,


One of the points which is said time and again against Java is that ,we have to write a lot of boilerplate
code in the form of setters and getters for our simple POJO classes which unnecessarily increases the
length of our code.


To tackle this problem,there is an open source project called Project Lombok which solves this problem
by allowing you to just write few annotations and it will generate getters and setters in the .class which
are generated from Java files.


Dockerizing a Spring Boot Application

Hello Friends,

In this tutorial,we will see how we can dockerize our Spring Boot Application.By dockerizing ,we mean that we are going to run our application as docker container.





Following are the steps involved :

1. Create a Spring Boot Application
2. Install Docker on your machine
3. Create a Docker file in your project
4. Docker build using docker file
5. Docker run

Let us see these steps one by one.

Step 1. Create a Spring Boot Application

Please follow my tutorial How to Create Spring Boot Project With Spring Initializer for steps needed to create a Spring Boot project using Spring Boot Initiailizer.

So once you complete this,you should be ready with springBootApp project in your workspace.

Step 2. Install Docker on your machine(Example here is for Windows10)

 2.1 Go to Docker Hub 



     
 2.2 Sign in to the Docker Hub.If you don't have account,create a new account by clicking on Create Account.

   

 2.3 Click on Download Docker Desktop on the below screen


2.4 Click on the "Download Docker Desktop for Windows" to download Installer for Windows.

     For downloading installer for Mac,click on "Docker Desktop for Mac".






















2.5 Follow the steps mentioned here to install Docker from Installer and your Docker should be up and running.

From Docker Docs

- What the Docker Desktop for Windows install includes: The installation provides Docker Engine, Docker CLI client, Docker Compose, Docker Machine, and Kitematic.

- Containers and images created with Docker Desktop for Windows are shared between all user accounts on machines where it is installed. This is because all Windows accounts use the same VM to build and run containers.

- Nested virtualization scenarios, such as running Docker Desktop for Windows on a VMWare or Parallels instance might work, but there are no guarantees.

3. Create a Docker file in your project

    Before we create a docker file,let us understand what is docker file and why it is required.

3.1 What is Docker File ?

Docker file is text file which has set of instructions or commands which will be executed by      Docker demon to create a docker image.

Example of Docker file :

FROM openjdk:8u212-b04-jdk-stretch
COPY target/springBootApp-0.0.1-SNAPSHOT.jar springBootApp-0.0.1-SNAPSHOT.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "springBootApp-0.0.1-SNAPSHOT.jar"]


3.2 Why Docker File is required

By executing the docker file basically we are creating a docker image.This image has all the details required to run the application viz. application code,system libraries,tools.Now we can run this image on any machine which has docker installed and it will get same execution environment.Say I have multiple environments to which my application code will go through before moving to production like ST,ET.Now if I execute this docker image on any of these(ST,ET,Prod) machine,it will make sure that application has same execution environment.

Also it is worth mentioning that once we run our docker image ,it becomes container and we can see container by executing following command:

docker container ls

4. Docker build using docker file

To execute commands or instructions in docker file,we need to execute docker build command on the command prompt as below :

docker build -t <tag name> .

docker build command builds the docker images from a dockerfile and  a "context".A build's context is a set of files  located in the specified PATH or URL.The build process can refer to any of the file in the context.For example,our build can use a COPY instruction to reference a file in the context.

4.1 PATH

In the below example,PATH is current directory(dot),so the context will be built by using files and folders in the project folder(from  where we are executing this command)

docker build -t <tag name> .

In the below example,

docker build -t "springbootapp" .

docker build command needs to be executed from the root of your project where you have placed your docker file and name of the file has to be dockerfile(case insensitive).When we execute docker build,all the instructions in the docker file are executed one by one and a docker Image is created with name given in "tag name".

We can check the newly created docker image by executing following command:

docker image ls


4.2 URL


With the URL parameter,we can mention the url of the Github or bitbucket repository.Docker build will then recursively pull the directories ,subdirectories,files from that repository and will use it as build context and send it to the Docker daemon.

docker build -t <tag name>  <Repository Url>

In this case,docker will clone the remote repository and will use cloned repository as build context.

5. Docker run


Docker run command runs the docker image. Runtime instance of docker image is called docker container.

docker run -p 8080:8080 <image name>
   

By default container does not publish any port.Here we are mapping port 8080 of the container to the port 8080 of the host machine.

So basically,after docker run,your application will be up and running as container.

Summary

By dockerizing our Java application,we make sure that our application gets same kind of execution environment across DEV,ST,ET,PR to make sure that application behaviour does not change due to change in application environment(DEV,ST etc.).

References :

https://docs.docker.com/

Feel free to post any questions in comments section or to share this post with anyone.

Also,if you like JavaSolutionsGuide and want to contribute,go ahead and

- Write an article
- Share with me at javasolutionsguide@gmail.com and
- See Your Article Getting Published on main Page of JavaSolutionsGuide with your name.


How to integrate and use EclEmma plugin for having good Junit Coverage


Hello Friends,

If writing good code is important,then it is equally important to write good Junit test cases which covers all the business logic.By writing Junit test cases which covers business logic thoroughly ,we actually make sure that individually each method of our code is working fine as per expectation and hence reduce the chances of getting bugs in the later phases of software development.

In this tutorial,we will see how we can use EclEmma plugin to check code coverage of our java code and hence can make sure that we have good coverage through Junit test cases.


Step 1 :

Go to following link :
Step 2 :

Click  on Installation -> Download option on left menu.

Step 3 :

Right click on top most(latest) link(At the time of writing this article, it is “eclemma-3.1.2.zip”) and save Zip on your machine.



Step 4 :

Extract the zip at the same location or location of your choice.

Step 5 :

Copy the extracted folder and go to eclipse folder(Where your eclipse is installed) and paste this extracted folder to the dropins folder within eclipse folder.

Step 6 :

Restart Eclipse.

Step 7 :

Right click on your project folder and select Coverage As-> JUnit Test and click Coverage button.It will run all your test cases and check for coverage.

Now because at this stage,we don't have any test case in our code for Service layer,we are getting 0.0% coverage and all code lines are shown red which means these lines are not covered under Junit test.




In general :

If you see Green colour, it means all those lines are covered under Junit testing.

If you see Red colour, it means all those lines are not covered under Junit testing.


If you see Yellow colour, it means your tests have run through those lines but not all test cases have been covered.

Example 

What we are going to do next is,we will create a Spring boot project,add some code in it and then gradually write test cases and see how EclEmma plugin gives as code coverage.

Step 8 : 

Let us look at it how it works by creating a simple Spring boot project with name "eclemma".Please  follow my tutorial How to create spring boot project with Spring Initializer to create spring boot project.

Step 9:

In  newly created project,create packages  and classes with names as per following screenshot


Step 10 :

Here is the source code for CalculatorService 

package com.blogspot.javasolutionsguide.eclmma.service;

/**
 * @author JavaSolutionsGuide
 *
 */
public interface CalculatorService {

 int add(int a , int b);
 
 int subtract(int a,int b);
}



Here is the source code for  CalcualtorServiceImpl 

package com.blogspot.javasolutionsguide.eclemma.service.impl;

/**
 * @author javaSolutionsGuide
 *
 */
public class CalculatorServiceImpl {
 
 public int add(int a , int b) {
  int c = a + b;
  return c;
 }

 public int subtract(int a,int b) {
  int c = a - b;
  return c;
 }
}

Step 11 :

So ,first we will write test cases only for add() method and then run Eclemma coverage

Here is the code for JUnit test cases for add() method :

package com.blogspot.javasolutionsguide.eclEmma.service.impl;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.blogspot.javasolutionsguide.eclemma.service.impl.CalculatorServiceImpl;


/**
 * @author JavaSolutionsGuide
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {CalculatorServiceImpl.class})
public class CalculatorServiceImplTest {
 
 @Autowired
 private CalculatorServiceImpl calculatorService;
  
 @Test
 public void add_for_givenTwoInteger_shouldReturn_sumOfTwo() {
  Assert.assertEquals("Test case to check if add returns sum of two give positive numbers", 3, calculatorService.add(1, 2));
    }
 
}



Step 12 :

Now let us run the EclEmma Coverage again and see the results :



As we can see,the coverage percentage has increased from 0.0% to 60% for CalculatorServiceImpl class and also the lines of code for add() method has now green colour after running coverage,which means that these lines are covered by Junit tests.

Step 13 :

Similarly ,we will write all test cases for subtract method and see coverage.

Add following test case in  CalculatorServiceImplTest.java :

@Test
public void subtract_for_givenTwoInteger_shouldReturn_differenceOfTwo() {
  Assert.assertEquals("Test case to check if subtract returns sum of two give positive numbers", 1, calculatorService.subtract(2, 1));
}


As we can see now,coverage is 100% for CalculatorServiceImpl class.

Summary 

So in this tutorial,we learnt how we can use EclEmma plugin to see the Junit test coverage of your code.On the basis of the Junit Code coverage report,we can find out which part of our code is covered by Junit and which is still left and then we can accordingly write more test cases for the uncovered lines of code,which will make sure that we have covered all required lines of code through Junit and hence result in better code quality. 

If you like reading this article,share it with your friends,colleagues for whom you think it might be helpful.

Also,if you like JavaSolutionsGuide and want to contribute,go ahead and

- Write an article
- Share with me at javasolutionsguide@gmail.com and
- See Your Article Getting Published on main Page of JavaSolutionsGuide with your name.

How to use profiles in Spring Boot Application

Hello Friends,

In this tutorial,we will learn,how we can use profiles in a Spring Boot Application.


How to Setup Multifactor Authentication (MFA) for your AWS account

Hello Friends,

In this tutorial,we will understand

- What is Multi factor Authentication for your AWS account and Why it is required
- Steps to setup Multi factor Authentication for your account


What is Multi factor Authentication for AWS account and Why it is required


From official AWS Documentation, AWS Multi-Factor Authentication (MFA) is a simple best practice that adds
an extra layer of protection on top of your user name and password. With MFA enabled, when a user signs in
to an AWS website, they will be prompted for their user name and password (the first factor—what they know),
as well as for an authentication response from their AWS MFA device (the second factor—what they have).
Taken together, these multiple factors provide increased security for your AWS account settings and resources.


You can enable MFA for your AWS account and for individual IAM users you have created under your account.
MFA can be also be used to control access to AWS service APIs.

Steps to setup Multi factor Authentication for your account


Step 1 :

Go to AWS console and login with your username ,password.


Spring Boot Actuator Tutorial


Hello Friends,

In this tutorial, we will learn about Spring actuator and what all it helps us with.

1. What is Spring Actuator?
2. How to add Spring actuator to Maven Project or Gradle Project?
3. Create a Spring Boot project with Spring Actuator dependency.
4. Monitoring the Application with Spring Actuator Endpoints.

How to check which Process is using port 8080 or any other port and vice versa on Windows

Hello Friends,

In this tutorial, you will learn the following :

- How to check which process/application is using a particular port on Windows
- How to check which port is being used by a particular process/application on Windows

Restful API using Spring Rest + Spring Data JPA + H2 with Spring Boot Example

Hello Friends,

In this tutorial, you will learn the following :

1. Configuring Spring Rest, Spring Data JPA and H2 in Spring Boot
2. Example of Spring Rest, Spring Data JPA, and H2 to create restful services endpoints with Spring Boot
3. Using Swagger to test the Restful endpoints

How to Integrate H2 database in Spring Boot App

Hello Friends,

In this tutorial, we will try to explore that how we can integrate with the H2 database in a Spring Boot application.