Friday, August 3, 2018

How J2EE components work together in any Container - Spring or Application Server

In a Spring+Jersey+Hibernate RESTful webapplication, we can spot various J2EE components - JTA, JPA, Java Bean Validation, JSON-B API for Binding, JAXB, JAX-RS etc.
As a whole application, we need all the above components work together. Spring is the gluing technology that achieves such purpose with the help of annotation or xml or java based configuration.
Example: 
1. JTA components can be enabled with @Transaction
2. @Entity, @Table, @Column etc enable JPA
3. @Valid enables Bean-validation
4. @Path, @GET, @POST etc assist JAX-RS
5. @JsonProperty part of Jackson - an alternative api such as GSON etc for JSON-B
Note: Jackson, GSON etc are not actual standard implementations of JSON-B.
  • Though, these layers are coupled together, the application may not run into any failure if one of the components does not work properly. Consider the following scenario:
  • RestController receives the JSON request, validates/maps to the entity, forwards it to Service layer. A transaction gets initiated and data gets persisted to database in Service and DAO layers respectively.
  • The above scenario is implemented with the help of annotations - @Valid for validation, @JsonProperty for Mapping to Bean, @Transactional and @Entity etc in service and DAO layers.
  • What happens if we miss @Valid annotation and send invalid data to the application. Well, we may expect the request may get failed since validation semantics are not invoked. But in fact there will not be any such exceptional behaviour but the invalid data gets saved to the database. Though we dont like to persist invalid data in database, the application behaviour is as per the expectation.
  • The way J2EE components are designed to work is so convenient that each layer works independently of others. Any specific layer does its job with the data that it receives from previous layer irrespective of whether the data is valid.

Thursday, June 21, 2018

Upgrade: Jersey 1.x to 2.x


In order to be on the latest stable versions of the middleware technology stack, I upgraded by webapplication from Jersey1.x to Jersey2.x. Here are the details of the migration that might be helpful for those who are facing any issues while performing Jersey upgrade.

Name Old New
Java Java 8 Java 8
Spring 4.2.1 4.2.1
Hibernate 5.3.1 5.3.1
mysql-jdbc-connector 5.1.6 5.1.6
Jersey 1.8 2.27
JSON-B Provider Genson 1.4 Jackson 2.27
Jersey-Spring Jersey-spring 1.8 Jersey-spring4  2.27
Tomcat7.x.x8.0.23

As part of upgrade, it is not sufficient to update maven dependencies from Jersey 1.8 to 2.27 but also modifying web.xml configuration too to complete the task.

Dependency Entries: Following table lists the old and updated entries to be part of pom.xml file of the project


Update to the web.xml: Because of huge code refactoring from Jersey 1 to Jersey 2, the  core class itself it being changed and more. Following is the git sample showing the config changes in web.xml



Note: Dont get mislead by name of the core Jersey2 servelt which is ending with Container. It shoud be treated as a regular dispatcher-servlet and not to be confused with other containers such as SpringIOC or Tomcat 

Friday, June 15, 2018

Timezone best practice

In any webapplication, the timestamps and zones play an important role. Any discrepancies to fetch and save time details normally occur in terms of zones result in deep confusion to the user. This requires us to strategise the way we handle this sort of information. 

It is a good practice to maintain the single timezone at application level to avoid any such issues.

How to configure Uniform Timezone:
There are 3 stages Timezone information might change - Middleware, Frontend and Database. As long as it is controlled at middleware layer, the frontend is free to convert and render the data according to user's locale. Since the database server has its own timezone configuration, we have to force it to ignore those details and save what the middleware sends.

Config at middleware: 
1. Since any java based application or web servers work as per JVM's timezone. Pass timezone information as the jvm arguments.
2. If using Hibernate 5.3 or higher with Spring, following parameter need to be updated in spring-bean configuration file
UTC
3. Forcing database to ignore its own configuration:
Eg: MySQL: Put the following parameters in the connection string

Friday, June 8, 2018

Java Reflections in Spring & J2EE

Java Reflection: This API one of the critical APIs of Java SDK helps in manipulating various components of Class entity at run time.
To explain in detail, everyone knows one way to create an object of a class as shown in below code sample:

**********START*******
public class Sample{
void show(){
System.out.println("Reflections demo...");
}
}

public class SampleDemo{

public static void main(String[] args){
Sample s = new Sample();
s.show();
}
}
************END*******

The above code will be compiled by JVM and get executed at run time.

But there is another way to do the same by using Java Reflection Package. The package offers various constructs - Modifier, Method, Class and Constructor etc - to manipulate classes and execute tasks such as - Creating objects and calling methods on the classes with/without params.

Reflections are used in developing SDKs, IDEs and Frameworks(Spring, Hibernate etc). Here is a sample reflection-example of how a custom annotation works in Java.
----------------------
Spring MVC or J2EE inner workings:
In early days of J2EE web application development, there is a lot of boilerplate-code and object-creations apart from business logic do exist had to be written by developer. Though the boilerplate code and object-creation are necessary but it is inefficient to write in all applications everytime since it eats up developer's time of coding business-logic.

What if there is some intelligent code that handles the above tasks automatically so that developers just write the business?

Consider the following piece of code with the highlighted boilerplate/object-creation code.
************START*********
public class MainServlet{
/*This can be a Dispatcher servlet*/

public init(){

}

public processGET(){

   if(URL.getPath == "/sample"){
     Controller controller = new Controller(); ---->OBJECT CREATION
     controller.sendResponse();
}

}

public processPOST(){
        if(URL.getPath == "/sample"){
      Controller controller = new Controller(); ---->OBJECT CREATION
      controller.sendResponse();
                }

    public destroy(){}
}

public class Controller{
    private Service serviceObj;

    Controller(Service service){
    this.serviceObj = service       ---->OBJECT CREATION
    }

    /*Business logic*/
    public String sendResponse(){

    return seviceObj.getResponse();

    }
}

public class Service{
private DataDAO dataObj;

Service(DataDAO data){
this.dataObj = data;      ---->OBJECT CREATION
}

public String getResponse(){
dataObj.fetchRespFromDB();
}
}


 public class DataDAO{
  SessionFactory sf;

  DataDAO(){
  this.sf = new SessionFactory();  ---->OBJECT CREATION
  }

  /*******CRUD operations**************/

  public create(){

  try{
   
   conn.setAutoCommit(false);      ---->BOILER PLATE
   Statement stmt = conn.createStatement();    ---->OBJECT CREATION
   String SQL = "INSERT INTO Employees  " +
                "VALUES (106, 20, 'Rita', 'Tez')";
   stmt.executeUpdate(SQL);        ---->BOILER PLATE
   String SQL = "INSERTED IN Employees  " +
                "VALUES (107, 22, 'Sita', 'Singh')";
   ResultSet rs = stmt.executeUpdate(SQL);  ---->BOILER PLATE
   
   conn.commit();        ---->BOILER PLATE
   rs.close(); ---->BOILER PLATE
   stmt.close(); ---->BOILER PLATE
   conn.close(); ---->BOILER PLATE
}

catch(SQLException se){   
   conn.rollback(); ---->BOILER PLATE
}

  }

public read(){
  //Database logic
  }

  public update(){
  //Database logic
  }

  public delete(){
  //Database logic
  }


 }
 ************END***********

The combined Boilerplate and Object-Creation code is called Gluing Logic. Gluing is called so because it looks like a thread that knits all the coupled business components together and acts as request-workflow.

 Request-workflow:
 -> Http request received at webserver
 -> Request is handed over to Servlet
 -> Servlet invokes the corrsponding controller based on the URL path
 -> Controller process the request using appropriate method and various business components - Service layer, DAO layter classes.
 -> Finally the respone is built and sent back to client by servlet/webserver.

From the above sample and following description, we can say that the developer's task of coding the gluing-logic need to be handled by, as mentioned before, some intelligent entity.

Intelligent Entity:
Lets strip all the gluing code from the above sample and replace with a human readable text.


************START*********
public class MainServlet{
/*This can be a Dispatcher servlet*/

public init(){

}

public processGET(){

//Create Controller object
//Call appropriate method on controller to handle the request based on url path
}


}

public processPOST(){

//Create Controller object
//Call appropriate method on controller to handle the request based on url path

}

public destroy(){

}
}

public class Controller{

    private Service serviceObj;    //Create Service object and inject here

    /*Business logic*/
    public String sendResponse(){

    return seviceObj.getResponse();

    }
}

public class Service{
     private DataDAO dataObj;    //Create DAO object and inject here

     public String getResponse(){
     dataObj.fetchRespFromDB();
}
}


public class DataDAO{

   SessionFactory sf; //Create SessionFactory object and inject here. 

   /*******CRUD operations**************/

public create(){
 try{

   //Create Connection object, Set autoCommit false, Begin             Transaction   
   
   String SQL = "INSERT INTO Employees  " +
                "VALUES (106, 20, 'Rita', 'Tez')";
   stmt.executeUpdate(SQL);        ---->BOILER PLATE
   String SQL = "INSERTED IN Employees  " +
                "VALUES (107, 22, 'Sita', 'Singh')";

   //Close and destroy Connections or return it back to pool. Commit Transaction
}
catch(SQLException se){   
   //Close and destroy Connections or return it back to pool. Rollback Transaction
}

  }

public read(){
  //Database logic
}

public update(){
  //Database logic
}

public delete(){
  //Database logic
}


 }
 ************END***********

From the above modified code-sample, it will be way efficient if all the human readable text(BoilerPlate/ObjectCreation/injection or Gluing logic) is taken care by the so called Intelligent code.

How to achieve the Intelligence:
Supply the Object-Creation/Injection of various business components(Controllers/ Service layter /DAO Layer objects) part of glueing in a configuration file such as XML or via Annotations.

Let a Java-Reflection read the above information and run the whole request-workflow. 
Note: Reflections are chosen to handle these kind of intelligence dynamically at runtime because they are meant for this.

Who provides this Gluing/Intelligence:
Eg 1: Spring Framework in case SpringMVC based webapps: All the information supplied via spring-beans.xml or @Service, @Repository, @Controller or @Path is processed by a Reflection. Spring heavily uses reflections to (life-cycle)manage its beans and aop proxies.

 Eg 2: J2EE Application-Server in case of standard J2EE applications: Information supplied in web.xml or @Transaction, @EJB, @Stateless, @Bean is processed by a Reflection.
 TomCat or any servlet-cotainer reads web.xml to find the information about defined servlet and cretes a servlet instace then eventually invokes various methods with the help of reflections.

In fact, all component-containers are built using reflection - Servlet container, EJB container, Spring IoC container and Struts. Basically, whenever we encounter a Java object configured in XML (or any external mechanism or annotation) and try to set any properties on it from config itself, reflection is acting behind the scene. Though it is hidden, is implemented in the container itself.

To summarize, Developer writes business components and supply the configuration information(annotations or XML file). Spring or J2EE handles the gluing logic with Reflections internally.

Spring in action:
Consider a spring MVC based webapplication running on Apache Tomcat.

1. Client makes a request to the url
2. request lands up at Apache Http server
3. Apache hands the request to Tomcat
4. Tomcat(a servlet container- contains reflection code) reads web.xml, instantiates servlet and invokes service method on it
5. Servlet's methods invoke Spring IOC container code
6. IOC container(contains reflections) code goes like this:
Note: IOC Container in Spring is an interface - ApplicationContext.java. This is implemented by ClassPathXmlApplicationContext, FileSystemXmlApplicationContext and WebApplicationContext.

  a) scan packages mentioned in spring-dispatcher-beans.xml
  b) find the class annotated with @Controller with matching url pattern
  c) create object of the Controller class with necessary dependencies:- this step creates    not just controller object but also Service and DAO objects
  d) invoke appropriate method on the controller object based on the url pattern
  e) handover response back to dispatcher servlet
7. Dispatcher servlet handsover the reponse back to Tomcat 
8. Tomcat gets the response back to Apache
9. Apache sends response to Client

What processes various annotations in Spring:
All the annotations across Controllers, Service, Repository classes are processed by respective frameworks. Each framework has its own reflection code to process annotations. 

Hibernate: @Entity, @Table, @Id, @Column, @Generated
Spring: @Controller, @Repository, @Service, @Model, @ViewModel, @Autowire, @Qualifier
Jersey: @Path, @GET, @PUT, @POST, @DELETE, @Produces, @Consumes
Spring-Transaction: @Transactional(supports both javax.transaction.transactional and spring's own @Transactional)

Spring does not implement for many of the annotations belonging to various J2EE APIs but only provides integration code to invoke the core classes of respective frameworks and leaves rest of the processing to them to handle.

What about J2EE application servers:
IBM Websphere and Oracle's Weblogic have the fully supported J2EE implementations meaning that the integration logic is inbuilt.

Friday, May 25, 2018

Service failure - End to End connectivity debug basics

1. Identify all nodes in the path - request initiator till the last node of the processing path
2. Test the connectivity between every two successive nodes(virtual or physical machines) separately to spot the chain-breakage
3. Fix the breakages and confirm the response

Ways to test connectivity between successive nodes:
1. Verify the logs for exceptions- Server and Application.
Eg: If the Ticket-Reservation system is running on Tomcat, the Tomcat is the server and Ticket-Reservation is the application.
2. Check if the network related nodes such as Firewalls, Load-balancers etc - are up and running.
3. Check if the database is running.
4. Connectivity test between one machine to another
Eg: If Client is on Node-1 and Server is on Node-2, and the client not receiving the response, then run the following:
ping
telnet
curl
the above will spot if there are any firewall blockers etc.

Saturday, April 14, 2018

MicroServices - Notes

MicroServices architecture:
As per http://microservices.io/, microservices can be defined as an architectural style that structures an application as a collection of loosely coupled services, which implement business capabilities. The microservice architecture enables the continuous delivery/deployment of large, complex applications. It also enables an organization to evolve its technology stack.

Consider a BookStore webapplication with following operations:
1. Orders
2. Customer Registration
3. Browse books

The application's frontend is in - html, css and javascript along with JSPs, backend is in single Oracle's RDBMS and middleware business logic is in Spring/Hibenate with SOAP/RESTful services. All the layers are part of a single monolith application.

DBMS Schema: Orders, Books, Customers

Monolith Style

The problem with above style: Lets say after few months there is an increase in the number of customers that are registering with the website but not all of them are interested in making orders but just to browse the books. In order to scale up to the performance, the whole application has to be scaled horizontally since there is neither an option to individually scale the separate tables(customers and books tables) nor to scale individual middleware services(CustomerRegistration or BrowseBooks) as all the code is in single box.

Solution: Decompose all the services into independently deployable services with database per service.



As per the above design, we can easily scale the services both at AppServers as well as at Database level.

Advantages:
1. Every service can have its own technology stack
2. Teams can independently work with less learning curve
3. Scalability

Disadvantages:
1. Database design and writing queries spanning across multiple databases. The queries become even complex if multiple database systems are of different types - one NoSQL and other is RelationalDB etc
2. Global transactions
3. Increase in remote service calls

REST and MicroServices: Since the services should be simple, we need to design REST services

Saturday, November 11, 2017

Memory Representations of Class & Objects in Java vs Javascript

Java objects and Class based Inheritance in Memory:
In Java, the concept of Templates called Class exists. The main purpose is to tell how to create an object of a class if requested during runtime by using 'new ();'. 

As you know, a class can inherit another class by using 'extends' and on and on..we can have any number of levels of inheritance. Note that each class directly or indirectly extends from root class called 'Object'. That means every object in java has a direct or indirect reference to Object's object instance.

While creating objects for classes, each object, its parent's object and all along till the root(Object's object)...all have their own copies in the memory.

Consider the following inheritance:
ModelSX --> BMW --> Car --> Vehicle --> Object
ModelVClass --> Benz --> Car --> Vehicle --> Object

ModelSX modelSX1 = new ModelSX();
ModelSX modelSX2 = new ModelSX();



As shown above, each single object has its own hierarchical copies of objects. The same applies for ModelVClass and any other class.



JavaScript objects and Prototype based Inheritance in Memory:
Predominantly there are 4 ways to create objects and one of them is via constructor

Here is how:
function Car(model,number,type){
this.model = model;
this.number = number;
this.type = type;
}
var bmwSX1 = new Car("SX1",1234,"SUV");

Executing above lines of code, Javascript creates not just one but 3 objects - Car Function object, Car Function's object, Car's Prototype object. Car Function object & Car Function's object linked via Car's Prototype object. Similarly if you create an Employee object using an Employee function constructor, the 3-object set is created in memory. Like in Class based inheritance, there is a root 3-object set exists - Object Function object, Object Function's object & Object's Prototype. Below figure depicts link between root(Object prototype) and other user defined objects...



As shown above, if user tries to access a property on an object say employee, Jsengine first looksup at employee object, if it doesn't find then it goes to employee's prototype, and if it is still not succeed then it searches in Object's prototype.

How to establish multilevel hierarchy:
Say if we have two objects - Employee and Manager. In order to make employee as manager's parent, link manager's prototype's __proto__ property pointing to employee's prototype. Then the following inheritance will be achieved..
Manager-> Employee -> Object 

Thursday, November 2, 2017

Under the hood - what happens when a program is being run on a computer

A computer system is a bare minimum combination of - Software, Hardware and a bridge
Software: Applications and other programs
Hardware: CPU, Memory(RAM and ROM) and other hardware
Bridge: KERNAL

In present days, computer basically is a binary computer, well we are not yet into quantum-computing era. All the instructions fed to the processor consist of combinations of 1s and 0s. 1 and 0 are decoded to certain voltage levels in real world which will be passed to hardware via circuit.

Hence, at this point we say a processor is a microprocessor(an organized circuit of number of logical gates constructed with Transistors, Diodes etc) which is manufactured to be able to understand a set of instructions called "Instruction Set" specified by manufacturer.

Various processors(from different vendors Intel, AMD, Motorola, Apple etc) have their own instruction sets - x86, AMD64 etc)

Few sample instructions common across main stream sets below:
ADD, COMPARE, IN, JUMP, JUMP IF, LOAD, OUT and STORE etc. They are mnemonics which need to be fed in the form of binary digits.

Sample set of binary instructions or also called Machine Code:
ADD - 101001001001
SUBTRACT - 100000101001
COMPARE - 111100001101

Software: User application programs or System Programs
Any software program to be executed by a CPU need to have its source compiled to those Machine Code instructions which can be understood by the processor where it is supposed to be run. The system crashes if it encounters a foreign instruction. This is called Platform Dependence. 

*Platform - a Processor with its own Instruction Set

KERNAL:
A computing machine with its numerous built-in hardware resources need to be managed efficiently. Example - Memory management, Optimize performance, drive media and other hardware apart from CPU etc. This needs a software program called Kernal-normally written in C and/or Assembly - is the first program that is loaded by BootLoader when you switch-on a computer or a mobile. It has instructions to drive literally each and every hardware packaged in a computing system. As mentioned above, like any software program, Kernal needs to have its Machine code specific to the underlying Processor. Hence, Kernal developers should compile it to corresponding Instruction set of the CPU(platform dependency). Apart from managing system resources, Kenral has yet another important task of being a bridge between other software applications(programs) which need to be run on the machine.

Being a Bridge:
Lets say you have written a piece of Java Program which you want to run it. Assume that the program contains instructions not just to CPU(operations involved with Stack and Heap) but to interact with other hardware(I/O) like display, speakers etc. 

eg: System.out.println("Hello World"); --> This is the operation that should display the message on monitor. This is a H/W operation.

The .java program first compiles to ByteCode represented as .class file. A program called Java Virtual Machine(JVM - java.exe) interprets this ByteCode to Machine Instruction(remember specific to Instruction Set of the underlying Processor) which can be understood by CPU. As part of this process, all H/W operations get compiled to a code that make calls to Kernal's H/W invoking code(Machine Code) corresponding to the H/W you want to interact with. These calls are called 'System Calls' or 'OS Calls'. These system-call invoking operations are called Privileged means User applications don't have authority to directly invoke hardware but can only be done with the help of Kernal.

*java.exe: On a side note, this is too a compiled C/C++ program which can be directly executed by CPU.

When you give a command to run the .java program, the Kernal loads your compiled Machine Code in the memory(RAM) and instructs CPU to start acting on it. All the Stack & Heap related operations are directly executed by CPU but when it encounters any System Call, CPU executes corresponding Kernal's  Machine Code for that hardware. Hence, Kernal acts as a bridge between Hardware and software through System-Call architecture.

Lets understand with following example:
Example: Java program: Ignore the syntax for now.
int i=20;
int j=10;
sytem.out.println("Sum of i,j"+i+j);
System.playMusic("Some song");

Machine code of compiled Java program:
10010101 - CPU1 - Stack &Heap code
11010010 - CPU2 - Stack &Heap code
10100100 - MONITOR1 - System Call for Monitor
11010010 - CPU3 - Stack &Heap code
10010010 - MONITOR2 - System Call for Monitor
11010010 - CPU3 - Stack &Heap code
11010010 - CPU4 - Stack &Heap code
11100110 - SPEAKERS1 - System Call for Speaker
11010010 - CPU5 - Stack &Heap code
10101001 - SPEAKERS2 - System Call for Speaker

Kernal Machine Code for h/w resources:
1010100100101 - MONITOR1
1001001010010 - MONITOR2
1001010010100 - MONITOR3
0010010010010 - SPEAKER1
1001000000100 - SPEAKER2
0010100100100 - SPEAKER3

Finally, the combined code is what is being executed by CPU by switching between User's Java program and Kernal.
10010101 - CPU1
11010010 - CPU2
1010100100101 - MONITOR1
1001001010010 - MONITOR2
1001010010100 - MONITOR3
11010010 - CPU3
1010100100101 - MONITOR1
1001001010010 - MONITOR2
1001010010100 - MONITOR3
11010010 - CPU3
11010010 - CPU4
0010010010010 - SPEAKER1
1001000000100 - SPEAKER2
0010100100100 - SPEAKER3
11010010 - CPU5
0010010010010 - SPEAKER1
1001000000100 - SPEAKER2
0010100100100 - SPEAKER3


P.S.
MOST IMPORTANT: Any software program/application be it OS Program or User specific application - Java, c#, c++, c, JavaScript or python etc - has to be ultimately compiled to Machine Code corresponding to the specific CPU(Microprocessor) on which it needs to be run.

In fact, CPU doesn't different differentiate between OS program or User Application. It executes Binary Instructions of those programs.

CPU's view of Software applications or programs


Programmer's view of Software applications




Thursday, October 19, 2017

Session management:

"In computer science, in particular networking, a session is a semi-permanent interactive information interchange, also known as a dialogue, a conversation or a meeting, between two or more communicating devices, or between a computer and user." ---- Wikipedia

Session: A session in context of Client-Server communication is an exchangeable Token/Key that can be identified by a server to recognize the sender and establish the connection as stateful.

Http is Stateless: HTTP protocol is stateless. Meaning that any information related to a http request-response cycle is lost once the transaction is completed. Hence, a server handles every request in its own isolated context though multiple requests are originated from same client.

Stateful Connection: In this a server preserves specific information related to a client from the first request-response transaction and uses that information to process further requests from the same client until the client or server wants to terminate such connection or conversation. The whole time during(start to terminate) which this communication happens is termed as Session-Time.

Session Mangement a technique to make a Stateless Protocol stateful.

How to establish a stateful connection or in other words how to identify multiple requests are originated from same client?
Answer is a Key/Token called an Identity.
Real world analogy: Imagine you are an employee of a corporate company and you have an Identity Card. Lets say you forgot your ID card one day. What will happen...
-> You will be stopped at the security entrance
-> You will be asked to present your details to identify. The security team make a note of all the details and check with your HR team then will allow you in.

Though its highly unlikely, suppose you forgot ID card for 10 consecutive days. What will happen..
You have to repeat the above 2 steps everyday without another alternative. Doesn't matter you gave your details 1st or 2nd or 3rd day, security team has no concern about the previous visits you paid to the company. It simply asks you to follow the procedure even on the 10th day or any day.

Here, you are client and Security Team is Server. The only saving point is your ID Card which a  Token/Key also called Session Token/Session Key.

To summarise...

 "Once a user has been authenticated to the web server, the user's next HTTP request (GET or POST) should not cause the web server to ask for the user's account and password again" --- Wikipedia.

There are different techniques to implement session management:
1. Cookies
2. URL Rewriting
3. Http Session management

Though every technique has its own merits, I will discuss about Http Session Management.
HttpServer with inbuilt session management feature creates a session and assign some expiration time-out to it whenever a request comes from a client. The session object is saved to the server's in-memory storage until its time-out. Server then generates a cookie called JSESSIONID(in a J2EE server) with a value and links it with the session created. While sending the response back to client, server attaches this JSESSIONID cookie in the response as part of http headers(normally Set-Cookie). The same JSESSIONID cookie should be passed to server in further requests from the client so that they can be identified by the server of who sent those requests. And server uses the session object to store client specific information in the form of Attribute-Value pairs.

A common and very popular case of Session management is Login-Logout: In this business case, a user initiates a request to login. Server creates a session object and forwards a JSESSIONID cookie back to user's client application. The session remains as long as the cookie is exchanged. The session object gets destroyed in other words session is terminated either when user issues a logout request or session timed out by server.

Here, the combination of Cookie along with Server's In-memory Session Object is used to manage session. Cookie can be called as Token which is associated with a Session object

Who provides Cookie handling mechanism to client applications?
Browser based application: 
Now-a-days, all the mainstream browsers have inbuilt mechanism to handle cookies(receiving and sending from/to servers automatically). Developers need not worry about writing code to handle cookies.

Mobile Apps:
Android/iOS developers should explicitly incorporate cookie handling code in their apps to suffice stateful connection with HTTP-servers.

Session management in Server Clusters:   In production environments, there is no single instance but a cluster of servers exist. 

**Servers and Physical Box:
Physical Box: A computer with RAM, Processor and Storage Space
A single box can have one or more instances of Applications running. Application can be Apache-Tomcat Web Server or JBoss Application server etc.

How can a single box can have multiple server instances running simultaneously?
Ans: Different ports. Means, several Tomcats can be installed on the machine with different port configurations.

A load balancer can channel client requests to the servers. All the servers can be accessed via a single DNS name.

In this case an in-memory session object(specific to a single server) wont be of any help if requests from same client are channeled to multiple servers. The created sessions have to be accessible to all server instances to maintain session.

MemCache is a cache-provider: A common storage space accessible to all server instances where the session objects also called Cache objects are created/retrieved/destroyed. This is how session can be maintained.

Session replication: Similar to memcache. Refer to Apache Webserver's Session Replication.

Tuesday, October 3, 2017

Kony FFI Creation

How to Create an FFI:
FFI: Foreign Function Interface
An FFI can be - library(.jar or .aar) or File(.class / .java)
Eg: 
In case of Android: .jar / .aar
In Case of iOS: .zip

Constituents of FFI - Android:
a) FFItoKony Interface file: Java file invoking the FFI code. This is the class that should be mapped to KonyVisualizer's Javascript function. This JS function will be used in the Viz project.
b) FFI code scattered across multiple files: Code invoking Android native functions and classes etc

Constituents of FFI - iOS:


How to Build .JAR file:
1. Kony Visualizer -> Open Perspective -> Java
2. Create a new Java Project
3. Create a class which will be the FFItoKony-Interface. Call/Invoke the other FFI class code in one or more functions
4. Write the business logic inside the other FFI class files. This code can have all the native calls and libraries
5. Build the project. Include the following steps while building
-> Add KonyWidget.jar(found in build folder of the project) as external library
-> Add necessary dependent native(android) libraries while building if required)
6. Export the source(not the dependent libs) as .JAR

How to Integrate and build in KonyViz: Refer to Kony Viz docs for more information
1. Edit-> Integrate Thirdparty Lib->
2. Map the FFItoKony-Interface.Class(Built at step 3 above) file to a JS file
3. Build the project.



Friday, September 29, 2017

CNTLM - Proxy Configuration

Proxy Server and Configuration:
Initially there were only Sever and Client. When client wants a resource from Sever, it sends a request using a protocol. eg: Browser sending a request for google.com home page from GOOGLE server using HTTP protocol.

But in a corporate environment, there exists a proxy server which is a middleman between application-clients and the websites 
1. To impose restrictions on web-browsing
2. To hide identity of the users/client-machine information

How Proxy sever works:
In a proxy environment scenario, 
1. An application such as a browser sends a request to Proxy server. Means, when you type a URL and click send, the HttpRequest for the actual server will be fwded to Proxy server by browser.
2. Proxy server verifies the request then forwards it to the website. It then receives the response and verifies the same. Finally the proxy server sends the response to Application that requested.

A proxy server needs authentication information from the applications that it needs to server. This information is configured in the applications(clients) via Proxy-Settings where the following details are provided..
Proxy Server name, Proxy port, Username and Password

Once the proxy settings are configured, the application sends request to the appropriate proxy server. This is called basic authentication.

Proxy server that needs NTLM:
Many applications now-a-days comes with an inbuilt feature where the proxy information can be provided/configured apart from being able to send a request to actual server. But sometimes, a proxy server needs NTLM authentication besides basic.
And some applications are not equipped to send NTLM authentication (just like they send basic authentication). In such cases we need another software that knows how to send NTLM information to the Proxy.

Cntlm is a software that stands between application-clients and Proxies. CNTLM acts like a local proxy server which is configured with authentication information. All applications now can be configured to send requests to CNTLM server that is running at a configured host and port usually at Localhost+3128.
Cntlm then sends that request to actual proxy server and receives the response from Proxy.

Future directions for applications to have:
1. Able to send http requests
2. Able to setup proxy to fwd http requests to Proxy server
3. Able to send NTLM data to NTLM server


How J2EE components work together in any Container - Spring or Application Server

In a Spring+Jersey+Hibernate RESTful webapplication, we can spot various J2EE components - JTA, JPA, Java Bean Validation, JSON-B API for B...