Wednesday 29 August 2018

Lombok Plugin

Lombok Plugin implementation (To Avoid Setters and Getters in Pojo's and Entitties)

Step 1: Add lombok latest dependency in pom.xml.

<dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
          <version>1.18.2</version> 
         <scope>provided</scope> 
</dependency>

Step 2: Add or copy lombok jar in sts or eclipse(Where the location of Eclipse or STS installation).

Step 3: Open command prompt and move to eclipse location and type below command.
java -jar lombok-1.18.2.jar

Step 4: After above step it will open a small UI like below 

Step 5: Click on install and specify the installation location of sts or eclipse.

Step 6: Remove all setters and getters in Entity and Pojo's and add @Data annotation in that.

Step 7: Update the Maven update once.



Tuesday 20 February 2018

Internal Collection working

HashMap Internal Working

HashMap always works based on Hashing. Because which helps to faster search.
HashMap having put(Object k, Value v) and get(Object k) methods.
Will see How HashMap works Internally by using these 2 methods.

Bucket : Bucket is one element in HashMap Array. Nodes can store into the bucket. 2 or more nodes are same in each bucket then it will store by using linked list as like below.

Key k = "king"
Value v = "100"
put(Key k, Value v) 
{
       hash(k) ->1021467
       index = hash & (n-1) -> 3
}

Based on key will find the HashValue
Based on HashValue will find the IndexValue.
HashValue & key & value will sit. @ indexValue,
If it same Index it will store in next node of Linked List.(Because in linked list always last node is null).


get(Object key)
{
hash(key) -> 1021467
index = hash & (n - 1) ->3
}

Based on Key value it will find the HashValue.
Based on Hashvalue it will find the Index.
Based on Index value it will return the value of that key.

If Index  value is same for different key then it will take the Hash Code and compares and return the value.

Ex : Key = "King" then Hashvalue = 1021467 so it return index = 3. Based on index and hashvalue it return the value = 100.
If Key = "Queen" then HashValue = 1024241 so it return index = 3. Both index are same so now it take the Hash value and compare in another node of the linked list. If both Hash values are same then it will return the value= 90.

ArrayList Internal Working



LinkedList Internal Working


Monday 12 February 2018

MicroServices


What is a Microservice?

MicroServices is an Services oriented architecture which reduces the time and development criticality.

What are the benefits of Microservices architecture?

  • Better fault isolation; if one microservice fails, the others will continue to work. 
  • Code for different services can be written in different languages. 
  • Easy integration and automatic deployment; using open-source continuous integration tools such as Jenkins, etc. 
  • The microservice architecture enables continuous delivery. 
What is the role of architect in Microservices architecture?
  1. Planner : 
  2. Technologies : 
  3. Tools : 
  4. Customization : 
What is the advantage of Microservices architecture over Service Oriented Architecture (SOA)?
Service Oriented Architecture is a software architecture where distinct components of the application provide services to other components via a communications protocol over a network.

1. Microservices, in a way, are the next step in the evolution of Service Oriented Architectures.

2. Building multiple services that are part of the same Service-Oriented Architecture

3. SOA development can be slow due to use of things like communication protocols SOAP, middleware and lack of principles but

On the other hand, Microservices are agnostic to most of these things. You can use any technology stack, any hardware/middleware, any protocol etc. as long as you follow the principles of Microservices.

Is it a good idea to provide a Tailored Service Template for Microservices development in an organization?
There are many organizations that provide tailored templates for Microservices. Eg. Dropwizard, Karyon etc. You can use these templates to make faster development of services in your organization.

Also remember that template code should not promote shared code. This can lead to tight coupling between Microservices.

What are the disadvantages of using Shared libraries approach to decompose a monolith application? 


What are the characteristics of a Good Microservice?

  1. Single Responsibility
  2. Private Data
  3. Monitored 
  4. Clustering 
What is Bounded Context?

Bounded Context is a central pattern in Domain-Driven Design. It is the focus of DDD's strategic design section which is all about dealing with large models and teams. DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their interrelationships.

What are the points to remember during integration of Microservices?

I. Technology Agnostic APIs:
II. Breaking Changes:
III. Implementation Hiding:
IV. Simple to use:

Is it a good idea for Microservices to share a common database?

What is the preferred type of communication between Microservices? Synchronous or Asynchronous? 


In synchronous communication, a Microservice can provide instant response about success or failure. In real-time systems, synchronous service is very useful. In Asynchronous communication, a service has to react based on the response received in future.

Synchronous systems are also known as request/response based. Asynchronous systems are event-based.

Synchronous Microservices are not loosely coupled.

What is the difference between Orchestration and Choreography in Microservices architecture?
Service orchestration represents a single centralized executable business process
Service choreography is a global description of the participating services, which is defined by exchange of messages, rules of interaction and agreements between two or more endpoints.

What are the issues in using REST over HTTP for Microservices?

Due to JSON or plain text in response, performance of REST over HTTP is better than SOAP. But it is not as good as plain binary communication.

There is an overhead of HTTP in each request for communication.

HTTP is not well suited for low-latency communications.

Can we create Microservices as State Machines?

What is Reactive Extensions?

Reactive Extensions is a design approach in which we collect results by calling multiple services and then compile a combined response. It is also known as Rx.

What is DRY?

What is Semantic Versioning?

Is it a good idea to build a Microservice or buy a commercial off the shelf software?


Why do we break the Monolith software into Microservices?


What is Continuous Integration?


What is Continuous Delivery?


What is Ubiquitous language?


What is the benefit of Single Service per Host model in Microservices?


What are different types of Tests for Microservices?


What is Mike Cohn’s Test Pyramid?


What is the difference between Mock or Stub for Microservice tests?


How can we eradicate non-determinism in tests?


What is a Consumer Driven Contract (CDC)?


What is PACT?


How can we separate Deployment from Release of Microservices?


What is Canary Releasing?


What is the difference between Mean Time to Repair (MTTR) and Mean Time between failures (MTBF)?


How can we do cross-functional testing?


What is a good tool for monitoring multiple services at a time?


What is Semantic Monitoring?


Why do we use Correlation IDs in Microservices architecture?


What is the difference between Authentication and Authorization?


How does HTTPS authentication works in Microservices?


What are Client certificates?


Why some big companies use API keys for providing access to public APIs?


What is Confused Deputy Problem in security context?


How can we secure Data at Rest in an organization?


What are the different points to consider for security in Microservices architecture?


What is Conway’s law?


What are the important Cross-Functional Requirements to consider during the design of a Microservice?


What is a Circuit Breaker pattern in the context of Microservice?


What is Bulkhead design pattern?


What is Idempotency of a Microservice operation?


How can you scale a Database?


What is Command Query Responsibility Segregation (CQRS) design pattern?


How will you implement Caching in Microservice?


What is CAP theorem?


How will you implement Service Discovery in Microservices architecture?


What is a good tool for documenting the Microservices?


In which scenarios, implementing Microservices architecture is not a good idea?


What are the major principles of Microservices?

Tuesday 6 February 2018

VersionTools


Gradle

Maven

Gradle checks Incremental builds means whether input or output of task changed since last build invocation.
Maven doesn’t have this option.
Source code or class path changes happens in project gradle checks the affected files and recompile those.
Maven doesn’t have this option.
If a dependent project has changed in an AB compatible way then java compilation tasks will be upto date. Means A depends on Project B and a class changed in B Project then Gradle wont Re-compile A.
Maven doesn’t have this option.
Parallelly sub projects will build  
Maven also having same option.


Spring Boot

Spring Boot is a framework which have Auto Configuration, Auto Dependency Resolution and Embedded HTTP Server like Tomcat and Jetty.

Spring Boot main aim is "To simplify the Spring Based Application Development".

To Start the Spring Boot Application below Jars are required.
  • SpringBootStarterWeb
  • SpringBootStarterParent
  • Java8Version
  • SpringBoot Maven Plugin.
Pros : 
  • No need to write XML Configurations, all configurations we can write in java code.
  • Reduces the Boilerplate code.
  • Testing is very easy.
  • Quick starts of application.
  • Provides all non functional features like Embedded Server, Security, Matrix and healthchecks.
  • Provides lot of plugin to work with Embedded Systems.
  • Provides Command Line Interface (CLI) Tool for development and testing.
Cons : 
  • Very tough to convert the legacy projects into new Projects.
Spring Boot Jars & uses : 
  • Spring-Boot-Starter-Web-Service : We can work with SOAP Web Services.
  • Spring-Boot-Starter-test : For Junit and MOCITO etc.
  • Spring-Boot-Starter-jdbc : For Spring JDBC
  • Spring-Boot-Starter-Security : Spring Security
  • Spring-Boot-Starter-data-JPA : JPA
  • Spring-Boot-Starter-data-rest : Restful WebServices.
  • Spring-Boot-Actuator : To load the Matrices and Project Health checkups.
More Points About Spring Boot : 

  • Spring Boot Starter Web Jar : It includes Tomcat, Hibernate, Restful Service, Logging and Web jars.
  • Spring Boot Auto Configuration : It will have Auto mated Error pages. Automatically Error page will come if we hit wrong URL. 
  • @ Spring Boot Application : Will include @EnableAutoConfiguration, @Configuration, @ComponentScan.
@SpringBootApplication :

@Configuration : Denotes the bean definitions for application context.
@EnableAutoConfiguration : It enables the bean presents in class path settings and various property settings.
@ComponentScan : It tells to spring scan all the components like configurations and services and other components in the application.

Spring-boot-starter-cache
Enabling spring framework Caching support.
@EnableCache :
Load Changes without Restart the Server
  • By using Spring-boot-devtools Dependency we can load the changes and it will reflect without restarting the server.
Spring-Boot-Actuator
  • It uses to load the Matrics and Health Checkups for application.
  • Basically it will uses in Production environment only.
  • By using " Spring-Boot-Actuator" Jar we can use this service.
Run with Custom Port : 
  • Add the following port in application.properties file
server.port = 8091

Spring Boot Remote Application :
  • By using below configuration, we can run the Spring Boot Application Remotely.
spring.devtools.remote.sercret = mysecret
Validations in Spring Boot :
  • By using below annotations we can validate 
@ConfigurationProperties , @Value 
Spring-Boot-Starter-Quartz
  • We can schedule the cron jobs by using Spring-Boot-Starter-Quartz.
HIKARI Connection Pool in Spring Boot :
Step 1 : Add a "hikaricp 2.6.1 jar" or "latest hikari jar" as dependency in pom.xml.
Step 2 : Add a below property in application. properties file.
spring.datasource.type = com.zaxxer.hikari.HikariDataSource
Step 3 : Set all Hikari properties in properties file like timeout etc.
Step 4 : Use HikariDataSource.
Step 5 : Set all the properties in util class or configuration class.
             private static HikariDataSource ds = new HikariDataSource();
             ds.setDriverName("");
             ds.setJdbcUrl("");
             ds.setUserName("");
             ds.setPassword("");

Proc of HikarCP
  • Its very faster and zero overhead production quality connection pool.
Override the Embedded server in Spring-boot :
Step 1 : Exclude the tomcat dependency in Spring-boot-starter-web by using below exclusion.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>



Step 2 : Change the default server port number.
Step 3 : Change the Server-specific properties.(SSL, ContextPath, ContextParameter etc.)

How to provide security in Spring Boot :
Use Spring-Boot-Starter-Security in pom.xml and in configuration file extends the WebSecurityConfigurerProperty class and override the methods.

How to provide the security for REST URL or URI or API :
In Different ways we can provide the Security for Rest API's : 
  1. Basic authentication (SSL Certificate) : Client will provide the SSL Certificate and install it in Web Server.
  2. OAUTH 1.0a : OAUTH is signature based protocol.  This protocol uses Cryptography signature. This can be used without SSL.
  3. OAUTH 2 : This protocol completely eliminates the signature. It requires Transport layer security which handles the encryption. This is very simple to configure so this will use for less sensitive data.
Because of above adv and disadvantages it is safer and simpler to choose basic Auth with SSL Cert for Most REST Services

ActiveMQ in SpringBoot :
By using "Spring-boot-starter-activemq" jar in pom.xml.

In Spring Boot How it will take Hibernate as default implementation of JPA :
First Need to add Spring-Boot-Starter-Data-JPA dependency in pom.xml file.

Once Spring Boot application starts it will check the class-path. If Hibernate dependency in the class path then Spring boot will take as default implementation of JPA. If it is H2 database related Jars in class-path then we can write the H2 implementation for JPA. 

How do we connect the external database in Spring Boot :
Remove H2 database jar or Hibernate jar in pom.xml or make it SCOPE as test. Add the Other external Database jar (MySql or Oracle) into pom.xml and configure the properties in Configuration class file and add the properties in property file.

Profile In Spring Boot
Enterprise applications will have multiple environments like DEV, STAGE, PROD.
So Profile will help to have different application configuration for different environments.
Profile Configuration :
We are having 2 profiles : Dev and Prod
Step 1 : Override the property file name like below
Dev : application-dev.properties
Prod : application-prod.properties

Step 2: Once we have a specific profile configuration we have to set the Active profile.
2 way we can do this. 
1. By changing the property in applicaiton.properties file.
spring.profile.active = prod
2. By changing the arguments in environment.
-Dspring.profile.active = prod


More Points will be add soon...

Hibernate


Hibernate is a ORM Tool, which transfers the java objects into Relation Database in the form of Objects.
Hibernate is a Open Source and Light weight.



ORM Tool : Converting the data between RDBMS and OOP Language is know as ORM.
  • Hibernate 
  • iBATIS 
  • Java Data Objects (JDO) 
  • Java Object Oriented Querying (jOOQ) 
  • Java Persistence API (JPA) 
  • MyBatis
Advantages:
  • Simple API provides for storing and retrieving the data from database. 
  • Supports Association, Inheritance, collections & Cache Mechanism.
  • If Table is not exist in the DB it will automatically create wont throw any error.
  • Connection Pool Mechanism is very simple to implement. 
  • Not specific to any database, we can use any type of RDBMS queries to access the db.
  • Automatically generates the Primary Key.         
Dis-Advantages :             

  • Lot of API need to learn.
  • Debugging and performance tuning is difficult.
  • Slower than Pure JDBC because Hibernate will generate lot of SQL Queries @ Runtime.

Difference between JDBC & Hibernate : 

Hibernate :

  • Hibernate provides cache mechanism.
  • Implementing Connection Pool mechanism is very easy. 
  • Not Specific to any database Queries are DBMS Specific.
JDBC :

  • Not supported for Cache Mechanism
  • Need to write different code for Connection pool.

Composite Primary Key : 
If Table having more than one primary key we can call it as Composite Primary key.

Criteria :

Projections :

Types of Hibernate :

  1. IDENTITY 
  2. SEQUENCE
  3. CUSTOM GENERATOR
  4. AUTO
Optimistic locking :
Frequently accessing the data on a table, that time lock will happen on table. To optimize that we can use "Versioning" or "Time stamp" on a table. Which acts as a cache, when ever values changes it will fetch the latest data. 

Cache :

When Cache will apply on api's?
Where ever frequent changes wont happen then we can implement cache on that api.
Ex : Search the particular data in Case Module.

2 Types of Cache in Hibernate :
1st Level Cache : Session Level Cache. Default cache in hibernate.
2nd Level Cache : Session Factory Level Cache. Need to configure and customize.

How Cache works ?
@Cacheable annotation will take care about cached  data.
@Cacheable(Value = "temp") : Value will take about the data changes in cache.
EhCache.xml : Need to specify the cache details by using Cache value. Name and value should be same in both. Here we will mention the cache timing based on this time cache will update the data.

Difference between Load() and Get()?

Load () : It wont hit the database and retrieve the value. Because it will create one proxy object with the given identifier. If Object is not found then it will through "Object Not Found Exception "

Get () : It will always hit the database to retrieve the values.If Row is not found it will throws "Object Not Found Exception".

Difference between Eager and Lazy Load :

Eager Loading : 
  • Load all the relationships data from the database.
  • Bit Slow.
  • By Default it will fetch eager.

Lazy Loading : 
  • Doesn't Load the relationship unless explicitly asked via getters.
  • More Faster.

Difference between Merge and Update : 
Update() : 
update returns serializable object.
When ever data is there then update will happen based on id or some other attribute.

Merge():
Merge return type is void.
Its acts as a persist() means, If we want to save any modification at anytime without knowing the state of an object then we can go for persist().


Aggregations: 

1. One To One Mapping: 
Ex : One Student will have One Laptop
@Entity
public class Student
{
@Id
Private int sid;
private String sname;
@OneToOne
private Laptop laptop;
------
------
}

2. One To Many Mapping & Many To One Mapping 
Ex : One Student will have Many Laptops 
@Entity
public class Student
{
@Id

Private int sid;
private String sname;
@OneToMany(mapped By = "sid")
private List<Laptop> laptop;
-----
-----
}
Note : If we didnt specify the mapped By = "sid", it will create a new table like Laptop_Student.

3. Many To Many Mapping
Ex : One Student will have Many Laptops.
        Multiple Laptops belong to One Student.

@Entity
public class Student
{
@Id

Private int sid;
private String sname;
@ManyToMany(mapped By = "students")
private List<Laptop> laptops;
-----
-----
}




@Entity
public class Laptop
{
@Id

Private int lid;
private String lname;
@ManyToMany(mapped By = "laptops")
private List<Student> students;
-----
-----
}


Note : If we didnt specify the Mapped By ="names" then it will create 4 extra tables.

Swagger


Swagger is widely used for visualizing APIs, and with Swagger UI it provides online sandbox for frontend developers. 

Swagger is a tool, a specification and a complete framework implementation for producing the visual representation of RESTful Web Services. 

It enables documentation to be updated at the same pace as the server. 

Pros : 

  1. No need to maintain any separate document for API's.
  2. Once we update the API's in services it will reflect in Swagger UI.
Cons : 

Swagger Implementation :

Step 1 : Add the below swagger dependencies (Latest versions) in pom.xml.

Step 2 : Write a swagger configuration class to configure the swagger UI.


  • To enable the swagger UI we will use @EnableSwagger2 Annotation.
  • Docket is used to get ApiInfoBuilder which provides the way to control the endpoints in swagger.
Step 3 : Write a controller with a Method GET.

Step 4 : Write a Spring boot main method to run the application.

Step 5 : Run the Swagger UI with below url






Tuesday 30 January 2018

Security with Spring Boot

Web Services Security can be provided in many ways: 

  1. SSL Configuration
  2. HTTP Basic Authentication 
  3. OAUTH Configuration
  4. HTTP Digest Authentication.



SSL Configuration

Step 1 : Create a Spring boot application by using http://start.spring.io

Step 2 : Generate a SSL Certificate by using keystore commands like below

keytool -genkey -alias selfsigned_localhost_sslserver -keyalg RSA -keysize 2048 - validity 700  - keypass changeit -storepass changeit -keystore ssl-server.jks.

It will generate the ssl.server.jks file which will have self signed certificate.

Step 3 : Create Controller class and write one get method.

Step 4 : Copy the keystore file (ssl-server.jks) into the resource folder.

Step 5 : Copy the below properties into the application.properties file.

server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN

server.ssl.key-store-type=JKS

Step 6 : Do maven build and call the get method through web browser. You will get warning like not trusted certificate authorities. Just give continue it will redirect to HTTPS.

HTTP Basic Authentication : 

Step 1 : Create a spring boot project by using spring boot security jar.

Step 2 : Write one simple Controller with @GetMapping method which will returns some message.

Step 3 : Run the spring boot main application.

Step 4 : Hit the service (http://localhost:8080/security/hellosecurity/)in browser, then pop up will ask username and pwd to access the API.

Step 5 : Default username : user, Password : it will generate in Console.

Custom Configuration:

Step 6 : Write a @Configuration Class which extends WebSecurityConfigurerAdaptor
Override the configure methods in the class and give the custom roles and credentials like below

Step 7 : Hit the service will ask the username and password. Use the above custom credentials to access the API's. From custom class we can hit the Database and validate the roles and credentials also.

OAUTH Configuration in Spring Boot:

Will be add soon

SpringBoot

SpringBoot SpringBoot Application :  Pros & Cons :  SpringBoot Application creation using spring.io :  SpringBoot Application Annotation...