Saturday, September 17, 2016

Socket and Perception of Connection between Client and Server

Sockets: An object created by any networked application which contains 'data and address*' details to be sent to another program running on another machine elsewhere via wireless or wired infrastructure.
Eg: In case of Java, Socket is part of  Java's Networking API(java.net.* package) which knows how to talk to machine's Network Stack(TCP/IP) to send and receive data.

Network Stack: Its a software+hardware infrastructure specific to a computer. The software component is usually implemented by machine's OS.

data and address*:
Data -> Data from source program.
Address -> Host and Port details of the destination program.



Q) When can we say a connection is established between a server and a client?
Ans)       Many imagine or believe that a connection is physical wire or wireless connection. Or some might think it's specific to machine's protocol layer. But this is a pure misconception. Connection is purely abstract and conceptual. Below is how it's supposed to be perceived.

       Similar to how a socket object is created at source program, if a new socket object is created(to receive the data) at the destination program on the destination machine upon a receiving a request from source, then we can say a connection is established. So, in an abstract way connection means creation of client and server specific socket objects. The data transmission between source and destination programs over 'that connection' happens usually but not restricted to first via TCP(But also UDP, SCTP etc - Transport Layer protocols) then to IPv4(but also IPv6, ICMP etc - Internet layer protocols) then to ARN(but also NDP, OSN etc - Link Layer) and so on down through TCP/IP stack protocol layer. Above all the layers is the Application Layer. Hence, 'that connection' is named based on the application layer protocol...
Eg:
1) HTTP Connection if the client and server uses HTTP (Web applications use this)
2) SMTP Connection if the client and server uses SMTP (e-Mail applications use this)
etc,.

Note: Protocols used by Applications - Web Application, Mail Applications, Chat applications etc,. any user application - are called Application Layer protocols. But here is the catch. Sometimes applications may skip the Application Layer and directly communicate starting from Transport layer.

         Now, look at the below diagram showing how the above explained Sockets and Network Stack work exactly in a communication process between a Http Client and Http Server. Clearly indicated who does what - that of Server and Client.
Client - Server communication via TCP/IP with the help of Sockets



Wednesday, September 14, 2016

Frequently Bugging Questions - FBQs - Java

Q1) How many instances of data(variables) and behavior(methods) per objects are created during runtime?

Ans) Well, each instance of a class has its own set of non-static class data. But the behavior or methods(both static and non-static) will be created only once in the class area. After all what is the point of having a same method code multiple times!

Q2) Servlet Container, EJB Container...what is a Container?

Q3) What is Serialization in Java
Ans) Just like .txt, .pdf, .doc etc., Serialization(.ser) is a format which can be understood by a JVM or any java program. There are many ways - eg: text files -  we can save java's objects but .ser is the most efficient way.

Q4) Compare HTTP vs HTTPS vs SOAP in terms of Security?

Security Comparison
Q4) What is ThreadSaftey?
Ans? A Class or its object is said to be thread safe if it has
 i) No State or no instance variables
ii) Immutable state or all its instance variables are immutable
iii) State that can only be modified through it's methods which are synchronized

Q5) What is the difference between MOM and Message Broker?
Ans)
Basically, MOM- Message Oriented Middleware - is an enterprise integration system that does the function of transfer of messages from sender to receiver. It can be imagined as a central system that takes a message(in any format - Text/Soap/Json etc) and simply sends it to the target receiver as it is. MOM does not do any transformation. It just sends as is the message received.

Message Broker: This is nothing but a MOM with a special capability of transforming messages from Senders to accepted formats of the receivers and send/distribute them.

Q6) What is an Inner Class in Java?
When you need some functionality which must be a member of a class but can't be achieved with either a member variable or its method, then Inner Class is used.

Features of Inner Class:
1) Functionality achieved by the inner class is very much specific to the Class
2) It need to use the environment of the Outer class like its members etc to achieve the functionality

Q7) Benefit of DI in Unit Testing?
Dependency Injection and ease of doing Unit Testing:
There are no special advantages other than that are offered by DI itself.
Mock objects which are part of JUnit Tests are also injectable just like other dependencies.
In fact, DI does not prevent the use of Mock Objects -- can be considered as an advantage. Since, unit testing would be difficult if we cant use mocks in place of dependencies in DI environment.

Q8) Unable to Connect to SSL Services due to PKIX Path building failed
When you encounter this issue, the normal solution to add Certificate to cacerts which is part of your java environment using keytool. But sometimes it is necessary for you to add all the certificates in the certificate chain till the root need to be added.

Q9) Which .exe file is picked if two directories with same .exe file are present in Windows's system path?
Ans: Windows executes the .exe file from the first detected/found folder in the path.

Q10) What are keytool, keystore and cacerts in Java?
Ans: keystore, keytool and cacerts are provided by Java SE as part of SSL support. Another term that is required  to understand these concepts is Certificate.
Certificate: A certificate is a digitally signed statement of another entity(server of a person or an organisation), stating that the public key along with data sent from the entity is valid. When data is digitally signed, the signature can be verified at the java client side using a keystore file.

keystore: This is a file that jvm uses to store the digitally signed certificates and keys associated with them. cacerts is one such jvm's system wide available file residing in java.home\lib\security dir which contains CA Certificates. CA Certificate is a certificate awarded to an entity who claim that they are by a recognized Certificate Authority(Verizon, Symantec or GoDaddy) with its signature. During HTTPS communication, if a CA-certificate is received from a server, the signature of the Certificate Authority body can be verified in the store. So that the java client can trust the information received from the server is authorized and secure.

Adding Certificates to trust store: Sometimes, if obtaining a certificate is costly, then the organization may choose to send a self signed certificate. In this case, if the received Self Signed Certificate is verifed in the truststore(cacerts), the signature wont be found. Hence, the java client needs to add the certificate to its store so that the future communication can be established.

keytool: This is the utility to manage keystore and certificate etc.

Note:
iOS  has something called keychain that has the certificates
Android has keystore file that contains the certificates
Windows : has its own certificate store

Q11) How to know which path variable windows is reporting while you issue the command java -version?
Ans: for %I in (java.exe) do @echo %~$PATH:I will tell you the exact path on 'path' variable of Environment Variables on machine. This is useful when multiple versions of jre are installed and you are confused why system uses a version of java that you dont want eventhough you set the environment path properly

Q12) How margins apply in a webpage?
Ans: Every web-element has margin. Margin normally refers to the space around the widget or an element. If there are two web elements adjacent to each other, then if you increase the margin of a n element, it pushes the other away. If a widget is inside a container element, and if you increase the margin of the inner widget, the effect falls on the contents of the inner widget since the inner element cant push the container boundaries away. As a result, the text for example of an inner widget inside a container gets shrink. Suppose, the inner widget is another container and its margins are increased, the elements inside it get closer.

Q13) What is Server/Instance/Box etc?
1. Box/Machine: A physical machine - CPU, RAM and ROM - is called a Box. 
2. Instance: Database software running on a particular port on a physical machine or box is called Database-Service-instance. Similarly, if TomCat is installed on the machine, then it is TomCat instance. Likewise, these are called Server instances or Servers. A group of servers is called Cluster.
3. Proxy Server

4. LoadBalancer - F5

Q14)What is High-availability in webbased applications?
High availability means, customers should not get service interruption frequently. Service interruption means the failure of a request processing at server side(middleware or backend). There are various reasons why a request fails at server side but the relevant one in this context is the unavailability of the server - Application/Web Server or Database server. Unavailability means server is down with StackOverflow or OutofMemory or Physically Server is down or Server has reached the maximum limit to handle requests. In order to make the applications highly-available, ensure there is less number of server down issues. There are many solutions and most obvious one is to have a redundancy. Redundancy means keeping multiple servers - Database or Application Servers or Web Servers - with a Loadbalancer. In rare case of LoadBalancer failure, there should be a backup loadbalancer too.

Q15) How to dynamically provide JAVA_HOME path to MAVAN or mvn command?
Ans. Sometimes, when running the command mvn -version will result in JAVA_HOME is not set properly. Setting JAVA_HOME in the system variables(in case of windows) should fix the issue. But if you have multiple versions of java installed and you want mvn to use one dynamically then do the following.
1. Open the command prompt or shell
2. Temporarily set the JAVA_HOME. set JAVA_HOME="path of jdk which does not contain spaces"
3. Now run the mvn -version command to proceed.

Monday, August 29, 2016

HTTP Communication between Client and Server

Step 1: On the client machine, user who wants a web-resource(eg: html document) from a web server types the URL of the resource in a Browser window and then clicks GO.

Step 2: Browser - a s/w program(Eg C or C++) running on the client machine - takes URL as the input and converts it into HTTP message(also called HTTP request) since Http Clients(Eg Browser) and Http Servers(Eg Apache Web server) use HTTP protocol to communicate. All modern browsers are pre-built with the functionalities of encoding and decoding Http(Application layer protocols or OSI layers 5,6,7) message to/from servers. Servers too have the similar capablities.


   To be more specific, Browser implements** Client Side of the HTTP protocol and Web Server implements Server side of the HTTP protocol.

   The converted HTTP message is then handed over to machine's Operating System's Protocol infrastructure(OSI layers 1,2,3,4) -  Transfer Control Protocol(TCP part of Transport Layer), Internet Protocol(IP part of Internet layer) and Network Protocol( Part of Link Layer). HTTP Message when passed through these three layers will be ultimately become electric/electronic signals which can be transmitted through wired or wireless Internet to the destination.


Step 3: The HTTP message(in the form of electric/electronic/electro magnatic/ light signal) then arrives at the destination machine(Http server in this case). Exact reverse process follows here and converted back to HTTP message. This HTTP message is then be read by Http server(a Software program running on the server machine having the capabilities to read and understand HTTP messages) translates it for later processing by any Java/.NET middle-ware program (which also is running on the server machine). Once the processing is done, a Http Response is created and sent back to client in the exact same fashion(Step 1 through Step 3...shown below)





**What is meant by HTTP implementation by Browser or Web Server?
The explanation could be as simple and plain as a Student asking his or her Teacher a question.

Analogy:

Student who wants to ask his/her English teacher a question says..

What is the tallest structure in the world? ----> [A Message in ENGLISH]


The sentence is constructed based on the Grammar guidelines specified by English language.


Similarly, a browser which wants a html document from a Webserver on a remote machine requests in the following way...


GET /hello.htm HTTP/1.1

User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.google.com
Accept-Language: en-us

The above is [A Message in HTTP]


The message is constructed based on the guidelines specified by W3Consortium on HTTP protocol.


A protocol can be identical to a langugage.

Monday, July 4, 2016

J2EE APIs Placement based on Usage point of view


J2EE Specification has various APIs each having its own functionality to cater for. While developing an Application using these, each API may or may not need others. Following is a usage/interaction level diagram that shows how they can be positioned wrt each other.


Looking from Web Application development based on J2EE compliant server, the EJB container and Web Container APIs are mandatory. Rest of the APIs such as - JMS, JPA, JTA etc are all going to be used based on the services that they offer.

Hence the Container APIs are placed at the center and rest of the APIs are surrounding them.

Note on Terminology:
Container APIs are generally called as Component APIs
Rest of the Service providing APIs - JMS, JAX-WS, JPA, Security - are termed as Resource APIs or Service APIs.

Overview of how Server Runs:
J2EE App Server runs using J2SE Platform APIs and both run in Java Runtime Environment(JRE) on Java Virtual Machine(JVM)

Sunday, July 3, 2016

API level Matching between J2EE compliant Server and Spring Eco System

Having experienced in developing  Java based Web Applications using J2EE compliant app servers and Spring Framework, below is my understanding of how various APIs fit-in if compared at API level in terms of similarity or analogy.

Note: Comparison is not based on performance or any other metrics.




J2EE compliant Application Server: Any implementation of the J2EE specifications. Oracle's WebLogic, IBM's WebSphere are most popular examples. But they are many more that can be found if you search for J2EE compliant Servers.


Tuesday, February 9, 2016

Accessing JSP data inside JavaScript or jQuery

Issue: I came across this situation while trying to add row of select boxes to a table in a JSP page upon clicking an AddRow button. The 'select' boxes should be populated with some model data(jsp data) received from Spring's controller. I am able to add the row of select boxes to the table using jQuery but unable to use the JSP data to the select boxes.

Solution: After searching various solutions on internet, I finalized on 2 methods:

Method 1: Set the JSP data to a html element and read the data inside jQuery and use it.
Method 2: Go for ajax calls in jQuery to fetch data from controller every time you need to populate the select boxes.

Monday, January 25, 2016

Appropirate Usage of JacksonDatatypeHibernate

Jackson, Spring and Hibernate are the three popular frameworks in their respective technologies but there are some issues occuring while using all these 3 together due to serialization of lazy loaded hibernate objects.

I faced a similar issue while converting Hibernate object to JSON using Jackson API in a Spring based web application and following is a sample error description:

No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer  to avoid exception, disable 
SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS)



Approach to solve the above issue:
Having gone through various forums and many different solutions, I have decided to zero in on using JacksonDatatypeHibernate add-on to fix the lazy loading concerns.

Step 1:
Write an ObjectMapper extension-class in one of your packages to inject Hibernate4Module object into ObjectMapper:




Step 2:
Register ObjectMapper extension-class(HibernateAwareObjectMapper) in the Spring-Config.xml with the following configuration:

Important note:
Never configure message converters outside of the annotation-driver tag when mvc:annotation-driven is enabled.  The registered message converter has to be inside the message-converters tag.

This is it.

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