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


Friday, September 1, 2017

How Client server communication works

The contents(files) that get exchanged between client(browser) and a sever(webserver) are html, css, javascript, images, pdf files etc. When a browser sends a request for a URL, the response can be html or html+css or html+css+javascript. Server wont send all the files in a single response if altogether makes it a large response. Rather it(here 'it' means server which in turn is nothing but the code(Java or c#.NET) written by developer...the way he intends to send) includes links to css,js files, images and other htmls in the response and sends it at the first time. Then server waits for another request to serve the rest of the content. After browser receives the first html response, it sends requests for other resources which are included as links while parsing the first html.
Server then responds with rest of the content.

So far so good. As long as server needs to send only static content, we can have all the html, css and Javascript readily developed to serve them immediately upon request. But, it is not always the case. In fact it never be one. The requests need to be processed based on the business logic and html content has to be rendered with some data retrieved from the database. 
In such case, we need to build html embedding data along with frontend event-handling code and Styling information dynamically.

Below are the techniques to dynamically render html+css+javascript+data:
1) Servlets: These are Java classes which create dynamic webpages by Println statements
2) JSP: A special kind of servlets which embed javacode inside html tags.
3) JSF: Yet another J2EE standard mechanism to handle requests

Ultimately, all such techniques create html response with backend data embedded. And necessary CSS and Javascript is obviously part of it.

Thursday, August 31, 2017

Javascript Modules - Overview

There are basically two runtimes for Javascript:
1. Client-side: Browser
2. Server-side: NodeJs

Client-Side:
Basically a webpage contains tags which will be parsed by a webbrowser with the help of its various components - HTML Parser, CSS parser and JS Engine etc. How Browser executes Javascript is our area of focus while discussing about Javascript modules.

Consider the following html:



The console of the browser when this page is loades shows the following output:
1
2
3
4
5
...

Means..the browser executes the script tags in a sequential fashion.

Consider another sample showing only the script tags:

Lets see how Browser loads the above html:
Browser, executes script tags in a sequential fashion as explained earlier. And if there are any tags that contain downloadable libraries from CDNs or scripts from Server, it downloads them asynchronously but the execution of the same will be sequential(in the order of encountered).
Meaning...once all the CDN libraries(jquery, bootstrap, backbone etc) are downloaded, the js code in 1.js, 2.js, 3.js will be executed respectively. But, sometimes, to speed up the execution, browser executes the scripts asynchronously.

The disadvantages of the approach:
1. Polluting global namespace:
If boht 1.js, 2.js contain a variable named 'a', a scope-conflict occurs. This is called polluting namespace.
2. Dependency: What if a browser executes scripts asynchronously(parallelly). Imagine executing 2.js while 1.js is still downloading or any other CDNs are downloading. And the problem arises if 2.js contain a jquery or backbone js function which is still loading.


To overcome those issues two approaches are defined:
a) CommonJS: ServerSide..NodeJS..Synchronous
b) Asynchronous Module Definition - AMD - Client side - Require.js - Asynchronous
c) ECMA's standard module spec

RequireJS:
This contains 3 basic building blocks:
1. require : Using this we can tell execution-environment(browser) of all the dependencies(js files) that it needs to load before execuing a piece of code.
2. define : Using this we can instruct browser of all the dependencies that the piece of code needs and register the current file(in which the define statement present) with RequireJS so that it can be used in require statement.
3. configure:  Configure shortnames for accessing various js files in different folders.

Essential Software Programmer Toolkit and Terminology

List of most frequently used tools by programmers:

Online code formatters for SQL, JSON, Java
Online Validators
Postman, POSTman Interceptor
SoapUI
Keyboard Shortcuts
Shell/Bash commands
Hostfile for network issues
WinSCP - For server logs and various other tasks
Notepad++ and its styler
JUnit
wkhtmltopdf
Eclipse
Netbeans
IntelliJ
Fiddler
Cntlm
TinyMCE - RichText editor

Terms:
Mobile:
ios: AppStore
TestFlight

Android:
SDKManager
FeatureFlag concept

Domain - Financial

Personetics lib

Native
SPA

APIs:
Service Configuration
Service orchestration
Integration




Friday, August 25, 2017

Comparing Android and WebBrowser

Comparing Android and WebBrowser:
Normally, users or developers compare Android with iOS or any other mobile based operating system. But here, I am not making a feature comparison. As part of my job, I do develop both mobile and web applications. Based on my past experience with it, I tried to create an analogy of both the systems to help myself quickly visualize where exactly the bare minimum components present in both the models fit along in the specific view of front-end application. And below what I could come up with.
Please mind that, though there are number of ways both are different, I made this comparison to ease my development activity.


Project Structure: Android vs Web Browser


From the above Figure...

Systems or the RunTimes: A(ny) WebBrowser has components like - CSS Parser, HTML parser, JavaScript engine and many more - to render web pages to user on desktop or a mobile screen. Android,though an Operating system that does numerous activities compared to a WebBrowser, also internally uses few components to display the content on the Mobile or Tablet screen. These internal components specific to each system.

View or User Interface:
In case of Android, layouts and the corresponding styling are defined in .xml files which are parsed by Android's internal components(described above) to build UI for the user. Similarly, webpages are written in HTML files(a markup language comparable to XML) and their styling is defined in .xml files. A WebBrowser reads these html and xml code, parses them, builds the DOM tree and finally renders it to user.

JavaScript vs Java:
The webpages or mobile layouts(Ref Mobile Screens in Fig) are static in nature. They don't have any knowledge on how to respond to events, perform network related operations such as sending request to server and process the response. JavaScript in case of WebBrowser and Java in Android are for the rescue. Developer specifies the code to handle all the User events, system events and network actions. They basically provide the dynamic capabilities to otherwise static pages.
WebBrowser has JavaScript engines to read and process the javascript and Android has DVM(Dalvik Virtual Machine) to compile and run Java code.

Static Content:
Any software project should contain static content such as images etc to be rendered to the user. Android and WebBrowser are no different. They too contain resources folder with all sorts of resources required by project.

Manifest file:
The only difference between Android and WebBrowser is this. The manifest file present in Android app but not in WebApplications. Main reason is that After an android app is developed, it has to be installed in the client machine(mobile or tablet or IOT)that runs on Android OS. In order to let Android OS know which class that it needs to start on the startup and which folders contain which data etc..all these details are specified in a Manifest.xml file. This is more of a configuration file. Where as in case of WebApplication...this is deployed on the server and client machine which uses browser does not need to have the frontend htmls to be installed. Rather browser sends a request to the server that and server responds with the html+css+javascript code back to the browser and it then processes. Hence, a manifest file is not required in case of webbrowser.

Friday, August 18, 2017

EHS Practices

Emerging Health System(EHS):
URL Mapping:
A completely different implementation that I came across. The system uses various front controllers(Dispatcher servlets) such as
Ajax Servlet
Upload Servlet
Image Servlet
Web Servlet: Main servlet for dispatching requests to other EJB objects.

All other servlets except WebServlet have the similar and self-explanatory task of dispatching requests.
Web Servlet(DADA Servlet): This instead of mapping requests through a config file(eg: xml), approach uses a combination of Java's Reflections and Database Table to dynamically execute methods on classes based on request parameters.

The solution is designed in such a way that the requests from front-end contain a static path eg: http://Host:port/ehs/ehsdadaservlet along with parameters.
The URL: /ehs/ehsdadaservlet is mapped to Web Servlet(Dispatcher).
WebServlet then invokes a ProcessHandler by passing it the HttpRequest for further processing.
The request-parameters contain information of which EJB and its method need to be invoked.
The ProcessHandler takes in the request, extracts the parameters, validates the values against database table to fetch appropriate class and its method. And then it invokes the classes and method dynamically with the help of Reflections.

Here the process handlers cannot be called as Controller as in MVC since they don't dispatch back the response.

Front End:
The development of frontend webpages is done via a software called ToolKit. It has a GUI that contains all UI elements which can be dragged and dropped to design webpages and can hook JavaScript methods to events of UI elements.
Once designed, the whole logic is stored in database tables. There are UI Process-handler classes which dynamically construct HTML pages(View) extracting from db, attach the XML data(Model) received from EJBs and render them back to client.

DAO and Service layers:
As part of persistence, no Hibernate or ORM tool is used rather they directly invoke Stored procedures from Service layer bypassing DAO layer.
A tool called Query builder(Similar to HQL) is used to avoid directly coding SQL queries. The objects compatible to be written in QueryBuilder queries need to be generated automatically by another in-house tool.

MasterData Managment:
Any application(Web based or desktop) that interracts with Users, should have the master data configured in the database and corresponding UI to pull and save data back-and-forth.
The practice followed in this project is somewhat less niche. In the previous projects, we used to maintain the config data in seperate tables here they maintain all the data in a single table calling it ControlCodes.

Eg:
Visa Meta data: will be in a table with Country, Visa Name, Class, Sub class etc
Address related meta data: Country, City, State, PostalCodes, etc
Seperate UI is designed to maintain this data.

But here in EHS, they configure all the data in a single table and maintain a single UI to manipulate the data. Though the adavantage of having single UI for whole management, lot of wastage will be there in terms many table columns being NULLs.

Imagine maintaining Visa metadata, Address meta data, any other configuration data in a single table. Though the data might be less, lot of columns will be NULLs resulting wastage of storage space.

These practices are highly unmaintainable in the long run.


Request Mapping Techniques in Web Applications - J2EE

URL mapping techniques:
Request mapping or the URL mapping is the most important part of any web application development.
Following are the types of techniques used in projects that I am aware of.

Finnacle:
All sorts of URL mapping is done at the Filter level. Filters are normally pre-processing constructs stand before Dispatcher Servlets in the request path.
But, Finnacle(a financial product) provided filters with an additional capability of url mapping to servlets.

Emerging Health System(EHS):
A completely different implementation that I came across. The system uses various front controllers(Dispatcher servlets) such as
Ajax Servlet
Upload Servlet
Image Servlet
Web Servlet: Main servlet for dispatching requests to other EJB objects.

All other servlets except WebServlet have the similar and self-explanatory task of dispatching requests.
Web Servlet(DADA Servlet): This instead of mapping requests through a config file(eg: xml), approach uses a combination of Java's Reflections and Database Table to dynamically execute methods on classes based on request parameters.

The solution is designed in such a way that the requests from front-end contain a static path eg: http://Host:port/ehs/ehsdadaservlet along with parameters.
The URL: /ehs/ehsdadaservlet is mapped to Web Servlet(Dispatcher).
WebServlet then invokes a ProcessHandler by passing it the HttpRequest for further processing.
The request-parameters contain information of which EJB and its method need to be invoked.
The ProcessHandler takes in the request, extracts the parameters, validates the values against database table to fetch appropriate class and its method. And then it invokes the classes and method dynamically with the help of Reflections.

Here the process handlers cannot be called as Controllers as in MVC pattern, since they don't process response and pick view to dispatch back the response.

SpringMVC:
Any springMVC web-application takes advantage of spring-container's @RequestMapping annotations or XML config files to map the request to corresponding controller methods. Dispatcher servlet only dispatches the requests to these controllers.

Friday, August 11, 2017

Theory behind wait(), notify() and notifyAll()

Multithreading in java is implemented with concept of Object and its Monitor.

Imagine monitor as a flag(or) register. JVM manages this.


If multiple threads need to access or share the object, first a thread has to acquire lock on the monitor of the object. Once a thread acquires a lock, no other thread can access that object. This can be done by using "synchronized" keyword in Java.

So far, a thread acquires a lock but how it notifies other threads to acquire a lock on the object?

wait(), notify() and notifyAll()
How it works?

Eg: Produced and Consumer Problem

A Queue object with size field is being shared by Producer and Consumer threads.

class Producer{
run()
{
synchronized(msg){
  if(msg.size =  max)
      wait();
  msg.push();
  notifyAll();
}
}
}

class Consumer{
run()
{
synchronized(msg){
  if(msg.size ==  min)
      wait();
  msg.pop();
  notifyAll();
}
}
}

class ProducerConsumerDemo(){
    public static void main(String arg){
       Queue msg = new Queue();
             msg.size = 10;

Producer p = new Producer();
Consumer c = new Consumer();

p.start();
c.start();
       

   }
}



How it works:
Lets say P acquires lock on msg first. P starts and C starts. Since, P acquired, C cant enter its synchronized block. P starts in its synchronized block. Since msg is empty at first, P push() happens. msg has one element. P calls notifyAll(). Means it exits the synchronized block and releases lock on msg. C starts and enters synchronized block. C consumer one element of msg. Now msg has zero elements. C calls notifyAll()--> Means C releases lock. C exits the synchronized block. Now, lets say C got the lock. C enters synchronized block but just waits and releases the lock. Now P enters the synchronized block. P produces. P notifies. P releases the lock. P exits the synchronized block...the story repeats.

Important derivations:
wait(): When a thread calls wait() in a synchronized block,
1) It does not leave the synchronized block
2) It releases the lock
3) It will be in wait/blocked state

When another thread notifies, it continues execution from where it started waiting. Means, line of code after wait() statement.

Notify: When a thread calls notify() in a synchronized block
1) It does not leave the synchronized block if notify() is not the last statement in synchronized block. It continues execution of statements after this. During this also, no other object acquires Lock. Another thread acquires lock, if the current thread exits synchronized block.

2) It leaves synchronized block if notify() is last statement in the synchronized block
3) It releases the lcok[ONly after exiting the synchronized block]

This thread needs to acquire lock again if it needs to execute.

sleep(): Does not release lock. It pauses main() thread.


wait
    synchronized(obj){
                     ---------
                     ---------
                     ---------
                     wait();  // At this point, thread goes to wait state.
                     ---------  // Form this point will be continued execution after notified by other threads
                     ---------
                     ---------
                     ---------

}   // Synchronized end




notifyAll
        synchronized(obj){
                     ---------
                     ---------
                     ---------
                     notifyAll(); // At this point, thread might release or might not release lock based on next 
                     [---------         lines of code exist or not.
                     ---------          If next line exist, it does not release the lock
                     ---------]         If next line does not exist, it releases the lock

} //End of synchronized block


Note: In a syncrhonized block, both wait() and notify() should exist. Or at least notify() has to exist.

Multi Threading Notes - Java

1)Thread States: Running, New, Runnable, Blocked/Waiting, Dead

2)Context Switching: Process of storing and restoring CPU states while switching between threads

3)Join: Using this method, we can ensure serialization of thread execution.

Eg: T1, T2, T3

{
T3.start();
T3.join();
T2.Start();
T2.join();
T1.start();

}

IN the above program, JVM first encounters T3.start(). It then starts thread T3. Then parallelly it tries to execute next statement, but it encountes T3.join(), indicating JVM should continue with T3 and go to next statement until T3 is completed. Then, it starts T2...

O/P:
T3 Starts

T3 Ends
T2 Starts
T2 Ends
T1 Starts
T1 Ends


4) Difference between synchronized block and synchronized method?
Using synchronized block { } -> we can partially block some lines of a method but not the whole method. Whereas in synchronized method, the whole method will be blocked.

5) Volatile, Transient, Temporal, Atomic

6) Thread Dump: GIves info about active threads. Used to analyse the deadlock situation

7) How to prevent deadlock?
Lock ordering
Lock timeout
Dead lock detection

9) Concurrency control methods?
  synchronized block - wait(), notify()
  Lock api
  Concurrent data structure/ collection
  Volatile, Atomic
  Immutable Objects

Java Memory Model



When Threads share objects in Heap, each thread has to acquire lock(a flag that will be set by the JVM upon request from thread) of the object that it wants to use. In case of method area, threads have to acquire lock of *Class to use its static data.

*Class: In Java, there is a class called Class that represents the actual Class template(not the object)

SOAP vs REST

SOAP RESTful
Heavy Weight Light Weight
Highly standardized with a dedicated team looking after the specifications Its just an archtectural style. No specific guidelines or spec
Slow because of High Payload and processing. Both payload and processing are related to guidelines. SOAP message(Payload) should contain all the information adhering to all the standandards(Eg: Secruity, Distirbuted nodes, Addressing etc) Hence the Message generator(client) and and its processing server need to accommadate all the code to process the guidelines. Thats the overhead while scaling. No rules. No overhead. Note: And to be fair cant even be compared with SOAP. Since REST does not follow any guidelines.
Tool need to test SOAP-WS since the WSDL cannot read by any browser so far. Browser will be sufficent but for complex requests POSTMAN is required
Built in error handling guidelines are to be mentioned in the message No built in error handling is specified in the message
Highly secure. Independent of Transport Protocol's security No message layer security can be achieved. Need to depend on Transport layer and Applicaiton security

Sunday, August 6, 2017

GIt Tutorial - Important commands

1. Open Git bash

Download existing source from Sever(Github/Gitlab):
1. cd path_of_the_workspace
2. git clone url_of_repo_on_github/gitlab name_of_the_local_folder
Eg: git clone https://github.com/naveenanem22/pmt-phase1.git demo
Note: Name of the localfolder is optional. If not provided, it will create a same name as per the repo on server
The above command will create a folder with the name of the root folder of the project on server inside the workspace directory
a remote called 'origin' gets created with the url of the remote-project-on-the-server
The local project folder gets initialised with git init command
3. cd name_of_project_folder
eg: cd pmt-phase1
4. Clone a branch of a repo..not the master
git clone --single-branch
as in:
git clone --branch --single-branch []
git clone https://NKumar@www.servername.com./scm/reponame/someapp.git --branch v3-update --single-branch

Following commands are valid from the project folder on the local machine:
cd name_of_prj_flder
1)git branch: Shows the details of all the branches the local project has
2) git remote: show the details of the remotes the project connected to
What is remote?
Remote is the alias of the url from where branch is created
A project can have as many remotes as possible
A branch can update its source from any of the remote
3) git init: This is the first command to bring a project(folder) under the radar of Git.
Execute this command from project-root-folder.
4a) git add . : commits all the files from working-dir to staging-area
4b) git add "name_of_the_file.ext" : adds specific file from working-dir to staging-area
eg: git add tobeaddedfile.txt 
5) git commit: commits all the changes from staging-area to repo
eg: To commit all files => git commit -m "This is the commit comment"
To commit specific file => git commit "name_of_the_file.ext" -m "comment"
eg: git commit system.js -m "Committing system.js"
6) git push: pushes local dir to server
7) git status: shows the details of the git local project
8) Rename a remote:
git remote rename old_name new_name
eg: git remote rename old_name new_name
9) Rename the current branch to a new name
Eg: git branch -m new_branch_name
9) Switch to another branch
10) To discard changes done to a file
eg: git checkout -- name_of_thefile.java
11. How to remove a project-root folder from Git Version system if it is initiated by 'git init' command
Navigate to project-root folder in windows explorer-> Show Hidden files -> Delete .git folder. This should remove the project-root from Git system. Use git init command to add it again.
12. git branch -a
Lists all the branches local and remote
13. git commit history with timestamp
git log --pretty=format:"%ad %h by %an, %s" --date=iso | sort -r | less
14.To reset to a previous commit
git reset --hard
15. To delete a branch
git branch -d
16. To revert a particular commit
git revert <#commit-hash>
eg: git revert 00eer6549
17. To rebase a branch1 from branch2
Step 1: Switch to the branch1
git checkout branch1
Step 2: git rebase origin/branch2
Step 3: git status --> This will show you to pull the changes..but don't do that..rather issue the following command..
git push -f -> this is to force push the changes




Following are useful linux(unix) commands:
1. ls --> lists all the subfiles and folder under a specific directory
2. ls -la --> lists all sub files and fodlers including hidden and meta files


Create a branch from master branch in local
Note: Before creating a new branch, always uptodate the current branch
1. cd name_of_prj_flder
2. git checkout -b new_branch_name
eg: git checkout -b pmtnaveen
Once work changes committed to local repo, push the branch to server.
3. add all files to staging area
git add .
4. commit files from staging to final-repo
git commit -m "This is the commit comment"
5. git push remote_name branch_name or git push --set-upstream remote_name branch_name 
a new branch gets created on the server(github)

How to add a local project to git version control and eventually create a repo on server
1. from Git bash: cd to Project_root folder
2. git init
Desc: this adds the whole project folder into git version control
3. git add .
Desc: to add all files and folders under the project to staging area
4. git commit -m "comment"
Desc: to commit the files from staging to commit
4.a git commit
Desc: To commit the files and write the comments on the editor. ':wq' to exit
5. Create a 'repo' on github and copy the url
6. create remote pointing to the step-5's url
git remote add 'name_of_the_remote'  'url_of_the_remote_git_repo.git'
eg: git remote add origin https://github.com/naveenanem22/meandemo.git
7. git push 'name_of_the_remote' 'name_of_the_branch'
git push origin master


Update localbranch to track remote branch:
cd name_of_prj_folder
1. git branch -u remote_name/branch_name
2. git pull

Git editor shortcut keys:
1. press "i"
2. write your merge message
3. press "esc"
4. write ":wq"
then press enter

Gitignore:
How to tell git to ignore some files/folders from tracking
Ans: 
1. Add a file called '.gitignore' in project root dir.
2. Specify the names of the files or folders or with pattern in .gitignore file. Save the file.
3. Add the file to git system by git add command
4. Then commit .gitignore file
5. Run git status command to check if the ignored files shown under untracked are not visible anymore

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...