Thursday, August 31, 2017

Encapsulation vs Abstraction

Encapsulation:-- Information(Data) hiding.
Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation. As the name suggests, Encapsulation is "hide/enclose something".


Abstraction:-- Implementation hiding.
Abstraction refers to showing only the necessary details to the intended user. As the name suggests, abstraction is the "abstract form of anything".

class Foo{
    private int a, b;
    public Foo(){ }
    int add(){   
         return a+b;  
    }
}

Internal representation of any object of Foo class is hidden outside the class. --> Encapsulation.
Any accessible member (data/method) of an object of Foo is restricted and can only be accessed by that object only.

Implementation of method add() is hidden. --> Abstraction.

Implementation Difference Between Encapsulation and Abstraction

Abstraction is implemented using interface and abstract class while Encapsulation is implemented using private and protected access modifier.

 Real world example:-
Complex logic is in the circuit board which is encapsulated in a touchpad and a nice interface(buttons) is provided to abstract it out to the user.

So Abstraction is generalized term. i.e. Encapsulation is subset of Abstraction.

Wednesday, August 30, 2017

Polymorphism | Binding - OverLoading vs OverRidding

Polymorphism is the ability for data to be processed in more than one form. It allows the performance of the same task in various ways. It consists of method overloading and method overriding, i.e., writing the method once and performing a number of tasks using the same method name.

Connecting a method call to the method body is known as binding.

Static binding/Early binding/Compile time binding :-
When type of the object is determined at compiled time(by the compiler), it is known as static binding.

class Dog{ 
 private void eat(){System.out.println("dog is eating...");}
 public static void main(String args[]){ 
  Dog d=new Dog(); 
  d.eat(); 
 } 
}

OR

The binding which can be resolved at compile time by compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time .

Static binding is better performance wise (no extra overhead is required). Compiler knows that all such methods cannot be overridden and will always be accessed by object of local class. Hence compiler doesn’t have any difficulty to determine object of class (local class for sure). That’s the reason binding for such methods is static.

public class NewClass
{
    public static class superclass
    {
        static void print()
        {
            System.out.println("print in superclass.");
        }
    }
    public static class subclass extends superclass
    {
        static void print()
        {
            System.out.println("print in subclass.");
        }
    }

    public static void main(String[] args)
    {
        superclass A = new superclass();
        superclass B = new subclass();
        A.print();
        B.print();
    }
}

Output:-
print in superclass.
print in superclass.

Since the print method of superclass is static, compiler knows that it will not be overridden in subclasses and hence compiler knows during compile time which print method to call and hence no ambiguity.







Dynamic binding/Late binding/Run time binding :-When type of the object is determined at run-time, it is known as dynamic binding. 

class Animal{ 
 void eat(){System.out.println("animal is eating...");} 

 
class Dog extends Animal{ 
 void eat(){System.out.println("dog is eating...");} 
 
 public static void main(String args[]){ 
  Animal a=new Dog(); 
  a.eat(); 
 } 
}

In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have same method . Let’s see by an example

public class NewClass
{
    public static class superclass
    {
        void print()
        {
            System.out.println("print in superclass.");
        }
    }

    public static class subclass extends superclass
    {
        @Override
        void print()
        {
            System.out.println("print in subclass.");
        }
    }

    public static void main(String[] args)
    {
        superclass A = new superclass();
        superclass B = new subclass();
        A.print();
        B.print();
    }
}

Output:-
print in superclass.
print in subclass.

- Methods are not static in this code.
- During compilation, the compiler has no idea as to which print has to be called since compiler goes only by referencing variable not by type of object and therefore the binding would be delayed to runtime and therefore the corresponding version of print will be called based on type on object.


OverLoading vs OverRidding - Both are concepts of polymorphism.
- Method overloading is a form of static binding. Method overriding is a form dynamic binding.
- Overloading is applied in single class, but overriding is applicable for inherited class.
- Method overloading is always specific to method signature. It defines number of parameter, type of parameter and sequence of parameter.

Thursday, August 24, 2017

SQL

DDL - Data Definition Language: statements used to define the database structure or schema. Some examples:

    CREATE - to create objects in the database
    ALTER - alters the structure of the database
    DROP - delete objects from the database
    TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
    COMMENT - add comments to the data dictionary
    RENAME - rename an object

DML - Data Manipulation Language: statements used for managing data within schema objects. Some examples:

    SELECT - retrieve data from the a database
    INSERT - insert data into a table
    UPDATE - updates existing data within a table
    DELETE - deletes all records from a table, the space for the records remain
    MERGE - UPSERT operation (insert or update)
    CALL - call a PL/SQL or Java subprogram
    EXPLAIN PLAN - explain access path to the data
    LOCK TABLE - controls concurrency

DCL - Data Control Language.
Some examples:

    GRANT - gives user's access privileges to database
    REVOKE - withdraw access privileges given with the GRANT command

TCL - Transaction Control:
statements used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

    COMMIT - save work done
    SAVEPOINT - identify a point in a transaction to which you can later roll back
    ROLLBACK - undo the modification I made since the last COMMIT
    SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use
    SET ROLE - set the current active roles

DML are not auto-commit. i.e. you can roll-back the operations, but DDL are auto-commit.

 

ActiveMQ

ActiveMQ is an implementation of JMS. It is message broker designed for the purpose of sending messages between two applications, or two components inside one application.

Features:-
Enterprise integration : Allowing applications built with different languages and on different operating systems to integrate with each other.
Location transparency : Client applications don’t need to know where the service applications are located.
Reliable communication : the producers/consumers of messages don’t have to be available at the same time
Scaling : can scale horizontally by adding more services that can handle the messages if too many messages are arriving.
Asynchronous communication : a client can fire a message and continue other processing instead of blocking until the service has sent a response;
Reduced coupling : the assumptions made by the clients and services are greatly reduced as a result of the previous 5 benefits. A service can change details about itself, including its location, protocol, and availability, without affecting or disrupting the client.

This MOM(message-oriented middleware) has two models which are the point-to-point/queue model and publish-subscriber/topic model.

Difference between the two is the number of recipients.

In queue, you only have one receiver or consumer.
In topic you can have your message be disseminated/spread to a number of subscribers.

In queue you do not have to worry about timing because the sender will have the luxury to send messages whenever he or she wants to. And the same goes for the receiver; he or she also has the liberty of reading it whenever he or she wants.
And, In topic, the publisher has to be continuously active for a subscriber to receive the messages. Otherwise the message will be reallocated.

 

Hibernate

Hibernate is a ORM tool which offer lots of advantages over plain JDBC.

Database independent
You can work with any database you want like oracle,mysql,db2,sql server ,etc. Using hibernate you won't worry about writing database specific queries and syntax. It's provides HQL (Hibernate Query Language), which is compatible with any database server. You just need to write queries in HQL, at the end hibernate converts HQL to underlying database and executes it.

OOP concepts
In ORM, you will map a database table with java object called "Entity". So once you map these,you will get advantages of OOP concepts like inheritance, encapsulation,associations etc that are not available in the JDBC API.

Caching mechanism - which improves performance
1st level & 2nd level cache provided hibernate means you don't need to hit database for similar queries, you can cache it and use it from buffered memory to improve performance.

- First-level is a mandatory Session cache.
- Second-level is an optional cache. Hibernate has a lot of cache providers for this level, the most popular are: EHCache, OSCache, warmCache, JBoss Cache, etc.
- Query-level is an optional cache for query result sets.

Lazy loading
Supports Lazy loading (also called n+1 problem in Hibernate). Take an example-parent class has n number of child class. So When you want information from only 1 child class,there is no meaning of loading n child classes.This is called lazy loading (Load only thing which you want).

- Supports JPA annotations, means the code is portable to other ORM frameworks.
- Connection pooling
- Bulk updates
- Built-in support for explicit locking and optimistic concurrency control.
- Allows you to transform the ResultSet into Entities or DTO (Data Transfer Object).
- You do not need to handle exceptions.Hibernate allows database management (for example creating tables), JDBC can only work with existing DB tables.
- Hibernate has capability to generate primary keys automatically while we are storing the records into database.
- Getting pagination in hibernate is quite simple.
- Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One

In terms of disadvantages of using other persistent layer:-
Boilerplate code issue
For Dao layer, need to write same code in several files in the same application, but spring data jpa has eliminated this. -  providing JPARepository

Hibernate Inheritance Mapping
Compared to JDBC we have one main advantage in hibernate, which is hibernate inheritance.  Suppose if we have base and derived classes, now if we save derived(sub) class object, base class object will also be stored into the database.

Hibernate supports 3 types of Inheritance Mappings:

    Table per class hierarchy(Single Table Strategy)
    Table per sub-class hierarchy(Join Strategy)
    Table per concrete class hierarchy




- In the above case, we can map the whole hierarchy into single table, here we use one more discriminator column i.e. TYPE.
- Performance wise better than all strategies because no joins or sub-selects need to be performed.
- Tables are not normalized.

@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
  name="TYPE",
  discriminatorType=DiscriminatorType.STRING
  )



 - In the above case, we have a single table for each class in the hierarchy but subclass mapped tables are related to parent class mapped table by primary key and foreign key relationship.
- It’s highly normalized but performance is not good.

@Inheritance(strategy=InheritanceType.JOINED)

- In the above case, we have one table for each concrete class in the hierarchy. But duplicate column is added in subclass tables.
- slightly more normalized than table per class strategy
- To support polymorphism either container has to do multiple trips to database or use SQL UNION kind of feature.

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)



Association Mappings between Hibernate Entities

one-to-one association

1. Using foreign key association:-
a foreign key column is created in owner entity.

if we make Employee owner, then a extra column “ACCOUNT_ID” will be created in Employee table. This column will store the foreign key for Account table.

 

To make such association, refer the AccountEntity class in EmployeeEntity owner class as follow:
//EmployeeEntity
@OneToOne
@JoinColumn(name="ACCOUNT_ID", referencedColumnName=”ID”)
private AccountEntity account;
    
In a bidirectional relationship, one of the sides (and only one) has to be the owner: the owner is responsible for the association column(s) update. To declare a side as not responsible for the relationship, the attribute mappedBy is used. mappedBy refers to the property name of the association on the owner side.
//AccountEntity
@OneToOne(mappedBy="account")
private EmployeeEntity employee;

Above “mappedBy” attribute declares that it is dependent on owner entity for mapping.
 
one-to-many association
Eg:- In any company an employee can register multiple bank accounts but one bank account will be associated with one and only one employee.

 


many-to-many association


What is the difference between FetchType.LAZY and FetchType.EAGER in Java persistence?
EAGER = fetch the data immediately : fetched fully at the time their parent is fetched. So if you have Course and it has List<Student>, all the students are fetched from the database at the time the Course is fetched.
LAZY = fetch the data when needed OR on demand: LAZY on the other hand means that the contents of the List are fetched only when you try to access them. For example, by calling course.getStudents().iterator(). Calling any access method on the List will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List (or Set). So for your lazy collections, the concrete types are not ArrayList and HashSet, but PersistentSet and PersistentList (or PersistentBag)
One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why?
In case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after session.close() statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.
 
 
 
 

Wednesday, August 23, 2017

Apache Solr

Apache Solr is an open source search engine built upon a Java search library called Lucene. It supports REST like API for performing various operations like update, query etc.

Creating fields for Indexing Document-
This can be achieved in 2 ways-
    Using Solr UI.(which modifies the managed-schema.xml by adding fields to it)
    Adding a new schema.xml

Indexing Document-
Now that the fields have been added by using either of the two methods mentioned above, we will index the document. We will create a new test.xml file which contains the person data to be indexed.

Querying the Indexed Document-
Now the data has been indexed.

Apache Solr vs Elasticsearch
Both Solr and Elasticsearch are popular open source search engines built on top of Lucene. Both have vibrant communities and are well documented.

The difference is in the way each builds a wrapper and implements features on top of Lucene.

Logging Framework


Monday, August 21, 2017

Polymorphism

Polymorphism
- is a concept where one object can have many forms. The most common use of polymorphism in Oops occurs when a parent class reference is used to refer to a child class object.
- static
- dynamic

Inheritance
- is a mechanism in which one object acquires all the properties and behaviors of a parent object. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes and same properties needed in multiple class you need not need to write multiple times.

Saturday, August 12, 2017

Microservice - independently deployable applications

In monolithic software, we mainly use a three-tier architecture:

    Presentation layer
    Business layer
    Data access layer

Say a traditional web application client (a browser) posts a request. The business tier executes the business logic, the database collects/stores application specific persistence data, and the UI shows the data to the user.

However, there are several problems with this type of system. All code (presentation, business layer, and data access layer) is maintained within the same code base. Although logically we divide the services like JMS Service and Data-Access Service, they are on the same code base and runs under single process context.



Microservice architecture / Microservices tells us to break a product or project into independent services so that it can be deployed and managed solely at that level and doesn't depend on other services.

On what basis do I break down my project into independent services?

So If the project has Inventory, Order, Billing, Shipping, and UI shopping cart modules, we can break each service down as an independently deployable module. Each has its own maintenance, monitoring, application servers, and database. So with microservices, there is no centralized database — each module has its own database.


Benefits:-
Each module is independent so you can choose programming lang. which best fits for module.
Each module has it's own database so you free to choose Nosql or relational. So application is polygot in nature.

So, "The microservice architectural style is an approach to developing a single large application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery."

Challenges:-
- hard to debug and trace the issues
- greater need for end to end testing

https://www.dineshonjava.com/microservices-with-spring-boot/
 

Spring boot


Spring boot - simplifies spring application development

It is not a framework but it is approach to develop spring based application with very less configuration.

Features:-
Auto-Configuration:-
- works by analyzing the classpath. Can automatically configure common configuration scenarios. If you forget a dependency, Spring Boot can’t configure it.

=> Spring Boot automatically configures required classes depending on the libraries on its classpath.
– Sets up a JPA Entity Manager Factory if a JPA implementation is on the classpath.
– Creates a default Spring MVC setup(configures  DispatcherServlet & ContextLoaderListener), if Spring MVC is on the classpath.


Starter Dependencies:-
- It offers help with project dependency management. The starter brings you required dependencies as well as some predefined configuration bits.

=> In simple words, if you are developing a project that uses Spring Batch for batch processing, you just have to include spring-boot-starter-batch that will import all the required dependencies for the Spring Batch application. This reduces the burden of searching and configuring all the dependencies required for a framework.

CLI:- 
- Lets you write complete applications with just application code, but no need for a traditional project build.

Actuator:-
- Gives you insight into what’s going on inside of a running Spring Boot application OR expose different types of information about the running application – health, metrics, info, dump, env etc.

So, Spring Boot can take the burden of configuration off your hands.


Q:- Suppose your application want to interact with DB?
 - Spring Data libraries on class path
 - define properties in the application.properties file exists in classpath of application
database.host=localhost
database.user=admin
then it automatically sets up connection to DB along with the Data Source class.

Q:- How to reload changes on Spring Boot without having to restart server?
Include following maven dependency in the application.
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>springloaded</artifactId>
 <version>1.2.6.RELEASE</version>
</dependency>


- Spring Boot includes support for embedded Tomcat, Jetty, and Undertow servers. By default the embedded server will listen for HTTP requests on port 8080.

- By adding logback.xml file to the application we can override the default logging configuration providing by the Spring Boot. This file place in the classpath (src/main/resources) of the application for Spring Boot to pick the custom configuration.

- Automatic restart
Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

This can be achieved using DEV Tools. With this dependency any changes you save, the embedded tomcat will restart. Spring Boot has a Developer tools (DevTools) module which helps to improve the productivity of developers. One of the key challenge for the Java developers is to auto deploy the file changes to server and auto restart the server. Developers can reload changes on Spring Boot without having to restart my server. This will eliminates the need for manually deploying the changes every time. Spring Boot doesn’t have this feature when it has released it’s first version. This was a most requested features for the developers. The module DevTools does exactly what is needed for the developers. This module will be disabled in the production environment.

- Configuration file 
application.properties file is very important where we would over write all the default configurations. Normally we have to keep this file under the resources folder of the project.

- what if I want to use Jetty server instead of tomcat?
spring-boot-starter-web which pull spring-webmvc, jackson-json, validation-api and spring-boot-starter-tomcat automatically and when we run the main() method it started tomcat as an embedded container so that we don’t have to deploy our application on any externally installed tomcat server.

Simple, exclude spring-bootstarter-tomcat from spring-boot-starter-web and include spring-boot-starter-jetty.


Magic behind the SpringBoot’s AutoConfiguration:-

SpringBoot provides various AutoConfiguration classes in spring-boot-autoconfigure-{version}.jar which are responsible for registering various components/beans.

@EnableAutoConfiguration annotation enables the auto-configuration of Spring ApplicationContext by scanning the classpath components and registers the beans that are matching various Conditions using @Conditional feature.
 
For example consider org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration class.




Thursday, August 10, 2017

Caching

You go to the bank to deposit 2 checks, and withdraw a small sum.
So you stand in line until a teller opens.
You make your first deposit. Then your second. Then you make your withdrawal.
Now you're done, you leave the teller line.
Getting to the teller is like creating your session, now you're in the bank, ready to work.
Each deposit and withdrawal are their own contained set of work, these are your transactions.
When you're done with your work and leave, you're closing or abandoning your session.
So in essence a session contains your transactions, after all you can't make a bank deposit if you never go to the bank right.

Monday, August 7, 2017

Java Executor framework

- The Executor framework is an abstraction layer over the actual implementation of java multithreading so that the programmer only concentrates on the business logic implementation.
- It is the first concurrent utility framework in java and used for standardizing invocation, scheduling, execution and control of asynchronous tasks in parallel threads.
- Executor implementation in java uses thread pools which consists of worker threads. The entire management of worker threads is handled by the framework. So the overhead in memory management is much reduced compared to earlier multithreading approaches.
- all parallel works are considered as tasks instead of simple threads.
- The Java Executor framework creates tasks by using instances of Runnable or Callable.
- In case of Runnable, the run () method does not return a value or throw any checked exception. But Callable is a more functional version in that area. It defines a call () method that allows the return of some computed value which can be used in future processing and it also throws an exception if necessary.


In the java.util.concurrent package there are three interfaces:

Executor — Used to submit a new task. execute()
ExecutorService — A subinterface of Executor that adds methods to manage lifecycle of threads used to run the submitted tasks and methods to produce a Future to get a result from an asynchronous computation.
ScheduledExecutorService — A subinterface of ExecutorService, to execute commands periodically or after a given delay.

Executor Interface
- Using an Executor it is possible to remove the manual creation of threads to execute a command.

public class MyRunnable implements Runnable {

  public void run() {

    // code to be executed

  }

}



Thread t = new Thread(new MyRunnable());

t.start();


can be replaced with

Executor executor = ... // Executor creation

executor.execute(new MyRunnable());


ExecutorService Interface

ExecutorService adds a more useful and advanced version method to execute commands, submit().

Passing a Callable to the submit method is possible to get a Future object and use it to retrieve the result of the asynchronous computation.

Additionally it is possible to shutdown an ExecutorService rejecting submissions of new commands. Using the shutdown() method all submitted commands will be executed before stopping the ExecutorService, but no new command is accepted. A call to shutdownNow() prevents waiting tasks to be executed and try to stop all currently executing commands.
 
Runnable myCommand1 = ...

Callable<String> myCommand2 = ...

ExecutorService executorService = ... // Build an executorService

executorService.submit(myCommand1);

// submit Accepts also a Callable

Future<String> resultFromMyCommand2 = executorService.submit(myCommand2);  

// Will wait for myCommand1 and myCommand2 termination

executorService.shutdown(); 

Runnable myCommand3 = ...;

// Will throw a RejectedExecutionException because no new task can be submitted

executorService.submit(myCommand3); 


ScheduledExecutorService Interface

The ScheduledExecutorService is used to schedule command executions after a given delay or periodically, it must be used as a replacement for Timer and TimerTask.

It uses the method schedule to run the command after a given delay of time, scheduleAtFixedRate() and scheduleWithFixedDelay() are used to execute a task periodically.



How to Create an Executor

To create an Executor it is possible to use the factory Executors class.

Most common methods are used to create:
 

- an ExecutorService with a single thread to execute commands with method newSingleThreadExecutor().
- an ExecutorService that use a fixed length pool of threads to execute commands with the method newFixedThreadPool().
- an ExecutorService with a pool of threads that creates a new thread if no thread is available and reuse an existing thread if they are available with newCachedThreadPool().

- a ScheduledExecutorService with a single thread to execute commands with the method newSingleThreadScheduledExecutor().
- a ScheduledExecutorService with a fixed length pool of threads to execute scheduled commands with the method newScheduledThreadPool().



public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    } 


==> we are creating fixed size thread pool of 5 worker threads. Then we are submitting 10 jobs to this pool, since the pool size is 5, it will start working on 5 jobs and other jobs will be in wait state, as soon as one of the job is finished, another job from the wait queue will be picked up by worker thread and get's executed.

 

Sunday, August 6, 2017

Desgin Patterns - GOF and J2EE

Design Patterns:-
- provide solutions to common software design problems.
 - or the best practices one software developer should follow in developing software.
- important to apply appropriate pattern for a situation. Otherwise, can over complicate code or may lead to maintainability issues.

GOF
1. Creational Pattern:-
- provide ways to create single or group of related objects.

Singelton:-
- ensures that only one object of a particular class is ever created.
- all further references to objects of this particular class refer to same underlying instance.

Prototype:-
- used to create a new object by copying all of the properties of an existing object.
- this practice is particularly useful when the construction of a new object is inefficient.

Factory:-
- create an object without exposing the creation logic to the client and refer to the newly-created object using a common interface. It is one of the most widely used creational patterns.

Main Class -> asks -> Factory -> creates -> Interface/Abstract Class -> Concrete Class 
                                                                                                              -> Concrete Class 

Real Example:- You have some row materiel (Input) , you provided it to one factory (factory class) and the factory gives you a product (object) so based on your raw material and factory implementation you get a product.



Abstract Factory:-
- creating a factory of related or dependent objects without explicitly specifying their concrete classes. Each generated factory can give objects as per factory pattern. So there is a super-factory which creates other factories.

Real Example:-  Its like you have raw material , you provided it to one factory as input but instead of processing your input this factory delegates the task to create product to its sub factories . Simply abstract factory means multiple factories.



The main difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

Builder:-
- construct a complex object from simple objects using step by step approach.


2. Structural Pattern:-
- provide a manner to define relationships between classes or objects.

Facade:-
- used to simplify access to functionality in complex designed subsystem(complicated to use or difficult to understand).
- facade class is a "wrapper" that contains a set of members that are easily understood and simple to use. These members access the subsystem on behalf of the facade user, hiding the implementation details of the underlying code.
- One example use of the facade pattern is for integrating a web site with a business application. The existing software may include large amounts of business logic that must be accessed in a particular manner. The web site may require only limited access to this business logic. For example, the web site may need to show whether an item for sale has reached a limited level of stock. The isLowStock method of the facade class could return a boolean value to indicate this. Behind the scenes, this method could be hiding the complexities of processing the current physical stock, incoming stock, allocated items and the low stock level for each item.



Proxy:-
- a class represents functionality of another class.
- a proxy is a wrapper or agent object that is being called by the client which references to real serving object behind the scenes.
- use of the proxy can simply be forwarding to the real object, or can provide additional logic.
- In the proxy, extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked. For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.



Remote Proxy. A remote proxy provides a local object that references a subject object in another location, generally via a network connection. The proxy performs the required actions to encode the requests for network transfer and accept the results from the remote resource before returning them to the client.

Adapter:-
- used to allow two incompatible types to communicate.
- involves a single class which is responsible to join functionalities of independent or incompatible interfaces. This is called the adapter which acts as a translator between the two types.

A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plug-in the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.







Decorator:-
- creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact. Its like acting as a wrapper to existing class.


Composite:- 
- creates a tree structure of group of objects that is treated the same way as a single instance of the same type of object.
- compose objects into tree structures to represent part as well as whole hierarchies.
- lets clients treat individual objects and compositions uniformly.



Flyweight:-
- If an application requires a large number of fine-grained objects of a class, share them instead of repeated instantiation.
The object you share is referred as a flyweight.
To apply flyweight pattern, the object properties can be divided into intrinsic and extrinsic properties.

Intrinsic properties make the object unique whereas extrinsic properties are set by client code and used to perform different operations.
For applying flyweight pattern, we need to create a Flyweight factory that returns the shared objects. For our example, lets say we need to create a drawing with lines and Ovals. So we will have an interface Shape and its concrete implementations as Line and Oval. Oval class will have intrinsic property to determine whether to fill the Oval with given color or not whereas Line will not have any intrinsic property.

3. Behavioral Patterns:-
- define manners of communication between classes and objects

Strategy:-
defines a set of related algorithm and encapsulate them in separated classes, and allows client to choose any algorithm at run time.
- It allows to add new algorithm without modifying existing algorithms or context class, which uses algorithm or strategies.

- Combination of Collections.sort() and Comparator interface is an solid example of Strategy pattern.

There are three participants in the strategy pattern.

Strategy declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a concrete strategy.

Concrete strategy implements the algorithm using the StrategyInterface.

Context is configured with a ConcreteStrategy Object; maintains a reference to a strategy object; may define an interface that lets strategy access its data.

Strategy Pattern Class Diagram

Command:-
- used to implement loose coupling in a request-response model.


1. Client create receiver object and then attach it to command object.
2. A request is wrapped under an object as command and send to invoker object.
3. Invoker object pass it to encapsulated command object.
4. Command Object pass it to appropriate method of receiver object to perform specific action.



Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation. The Receiver has the knowledge of what to do to carry out the request.  The Invoker holds a command and can get the Command to execute a request by calling the execute method. The Client creates ConcreteCommands and sets a Receiver for the command. The ConcreteCommand defines a binding between the action and the receiver. When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver

Observer:-
- defines a link between objects so that when one object's state changes, all dependent objects are updated automatically. This pattern allows communication between objects in a loosely coupled manner.

J2EE
Front controller:-
- all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request. The front controller may use other helpers to achieve the dispatching mechanism.

DAO:-
 

Friday, August 4, 2017

Java Web Services - SOAP vs REST

SOAP vs REST

1.
SOAP is good for applications that require formal contracts between the API Server and Client since it can enforce the use of formal contracts by using WSDL (Web Services Description Language).

REST is always better than SOAP in situations where lower bandwidth[ie. connectivity is expensive] between API Server and Client is required. An API consumed mostly by mobile applications is one of the use-cases where you should avoid SOAP at all costs. Simply calls services via URL end points.

2.
Performance is not great as SOAP is heavyweight as its uses XML and have extra overhead due to their headers.

Performance is much better than SOAP as REST is lightweight as it uses JSON and no extra overhead as no header provided. just key-value pair data. But it can use other data type also like XML,text etc. 

3.
SOAP defines its own security BUT REST doesn't have its own security.

4.
Learning curve is high in case of SOAP.

XML - XML stands for eXtensible Markup Language. It is a markup language much like HTML which was designed to store and transport data.
It is often used for distributing data over the Internet. It's what we had before JSON became the big thing.

JSON - It's a human readable object serialisation format, less verbose than XML. Very popular nowadays.

JAXB - "Java Architecture for XML Binding" is the primary mechanism for turning XML data into objects which you can then interact with, and vice versa. It's important to realize that it's an specification and not an implementation, so it mostly defines a set of annotations and simple classes / interfaces in the javax.xml.bind package.

Jackson - a library for data binding. It supports both XML and JSON as document formats, and implements the JAXB API.

Java DOM and SAX Parser are lower-level APIs to parse XML documents, while JAXB is a higher-level API for converting XML Documents (elements and attributes) to a Java object (and vice versa). Implementations of JAXB will most likely use a DOM or SAX parser behind the scenes to do the actual parsing of the XML input data.

JAXB is used to Marshalling(Java objects to XML representations) and Unmarshalling (XML contents to Java object).

Web Services - let applications exchange information over web

Web Services work on client-server model where they communicate over the network. Web services accept incoming requests from client and send response to client in either plain text, JSON or XML format. Server side component provides the endpoint URL where service is located and client application can invoke different methods.

The beautiful thing about web services is they are language independent. So a web service written in Python can be requested from a client written in Java, C#, Ruby etc.

Web services are classified into two categories:-

    SOAP – In SOAP-based web services both client and service transfer SOAP messages to communicate.
    REST – While in REST-style services both client and service transfer raw XML OR JSON to communicate.

Java provides APIs for creating both SOAP and REST-style web services and these are:-

JAX-WS (Java API for XML Web Services)
is a set of APIs for creating web services in XML format particularly SOAP and can also develop RESTful Web services. Plus, creating corresponding clients that communicate using XML OR use remote procedure calls(JAVA-RPC) to exchange data between client and service provider. It’s part of standard Java API, so we don’t need to include anything else which working with it.


Developers use this API to define methods, then code one or more classes to implement those methods and leave the communication details to the underlying JAX-WS API. Clients create a local proxy to represent a service, then invoke methods on the proxy. The JAX-WS runtime system converts API calls and matching replies to and from SOAP messages.

JAX-WS provides many annotation to simplify the development and deployment for both web service consumers (clients) and web service providers (endpoints).

client <----------------------------------SOAP Message------------------------------------------->server
<--------------------------------------------SOAP Protocol------------------------------------------------------>
<------------------------------------------- HTTP Protocol ------------------------------------------------------>
(proxy.methods)

JAX-WS + Spring integration

JAX-WS + Spring + cxf integration

JAX-RS (Java API for RESTful Web Services)
is a set of APIs and specification that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern.

JAX-RS is a standard defined in Java Specification Request 311 (JSR-311) and Jersey / RESTEasy are implementations of it.

Being implementations mean that the spec says "if you put @GET("/foo") on a method (bar()), you may access data X" - now in an app server, someone needs to go in and actually read your deployed code, parse the byte code with the @GET annotation and then if the user actually browses to e.g. http://localhost/foo get this web request to reach bar() and translate the return value of bar() into a http answer (e.g in XML or JSON representation).

So the spec with the name "JAX-RS" only provides the syntax and semantics of e.g. @GET, but the work of parsing requests, calling the right methods, marshalling the result values etc. need to be done by a package that implements the spec.


Some guidelines for a good way to structure REST API URLs
- Most rest APIs tend to only have resource names and resource IDs in the path. Such as:
/depatments/{dept}/employees/{id}

- Some REST APIs use query strings for filtering, pagination and sorting.

Recommended:- putting any required parameters in the path, and any optional parameters should certainly be query string parameters.

If there is a scenario to retrieve a record based on id, for example you need to get the details of the employee whose id is 15, then you can have resource with @PathParam.

GET /employee/{id}

If there is a scenario where you need to get the details of all employees but only 10 at a time, you may use query param

GET /employee?start=1&size=10

This says that starting employee id 1 get ten records.

Parameters
http://localhost:8080/user
@RequestMapping{
value="/user"
method
consumes
produces
}

http://localhost:8080/user?marketplace=1&merchant=2 => queryparameters
@RequestParam(name="marketplace") int marketplace, @RequestParam(name="merchant") int merchant

@RequestBody Object object

http://localhost:8080/user/{marketplace}
@PathVariable("marketplace")
@PathVariable is to obtain some placeholder from the uri (Spring call it an URI Template)

@PathParam/PathVariable :- for retrieval based on resource id

@QueryParam/RequestParam :- for filter or if you have any fixed list of options that user can pass


Web services are part of the SOA Services Oriented Architecture. So, when to use SOAP or REST web services to expose your API to third party clients?

Both approaches work, both have advantages and disadvantages to interfacing to web services, but it is up to the web developer to make the decision of which approach may be best for each particular case.

1. By now, most developers have at least been exposed to the REST approach, which uses a standard URI (Uniform Resource Identifier) that makes a call to a web service like http/https://www.mycompany.com/program/method?Parameters=xx. The approach is very simple to understand and can be executed on really any client or server that has HTTP/HTTPS support.

Using SOAP 1.2 has some additional overhead that is not found in the REST approach, but that overhead also has advantages.

So developers use REST approach for ease of development with little learning overhead as key advantages to the style.

2. Now, if your application needs a guaranteed level of reliability and security then SOAP 1.2 offers additional standards to ensure this type of operation. Comparatively, the REST approach would make the developers build this custom plumbing.

3. RESTFul Web Services serves JSON that is faster to parse than XML.

4. While REST today uses HTTP/HTTPS, SOAP can use almost any transport to send the request between clients and servers.

REST is very easy to understand and is extremely approachable, but does lack standards and is considered an architectural approach. In comparison, SOAP is an industry standard with a well-defined protocol and a set of well-established rules to be implemented, and it has been used in systems both big and small.

Web Development

Design Phase:- Below all these represent different stages of the UX/UI design flow:- Wireframes represent a very basic & visual repr...