21 June 2013

How do we determine the end of page in browser?

In facebook application the page is not completely loaded at once. It is loaded partially and when we drag the scroll bar to the bottom then some more part of the page gets loaded but how this is detected?


A simple java script can be solve this problem

window.onscroll = function(ev) 
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) 
        alert("Bottom of page is reached");

Difference between JVM and JRE

The basic difference between the JRE (Java Runtime Environment) and JVM (Java Virtual Machine) is, JVM is a specification and JRE provides the implementation.

In simple
JRE = JVM+ java and native API's.

Look at the following diagram for an idea of what JRE is.

The above is the overview of JRE. 

JVM is the real machine (piece of software) which is part of the JRE that executes the byte code.

In java first the source file (*.java) is compiled into the byte code by using a compiler that is "javac" which is provided as part of the jdk. Then to run this byte code (*.class files) the class file should be supplied to JVM. This is done by invoking "java" tool which is provided as part of the jdk. 

The following diagram is the architecture of the JVM:-

So once the byte code is supplied to JVM, it does the following steps
  •    The class loader loads the class file and it makes it available to the JIT (Just Intime Compiler) or the Interpreter which is part of the JVM.
  • JIT or Interpreter then converts the byte code to the machine code (Executable code) and stores it in class area. That means JIT executes the byte code.
  • while execution JVM uses other classes that are part of the program from the API's provides by the JRE , the method variables are stored on the stack and objects are stored on heap.
  • JVM uses the PC registers to maintain current and next executable instructions.
This is how the JVM works in brief.

One important thing to know is the difference between java compiler and JIT. Java compiler is a tool (piece of software) provided as part of jdk and is used to convert the source code to byte code but the JIT is part of the JVM that converts the byte code to executable code (direct instructions to CPU).

Best ways to build dynamic components in browser.

Long back in my projects we have done some terrible mistakes when creating dynamic HTML components on the current page that is being viewed. So thought to document the best ways to do this after discussion with some experts.

Problem :-

on the currently viewing page there is a checkbox. If user checks the checkbox then a combobox with the values coming from database should be displayed next to the checkbox.
A combobox should be displayed with some specific values on the currently being viewed page when user selects an option in the combox that is already there on the page. I mean the dynamic combobox values depend on the option selected in the combox present on the page.

so how to achieve this?


well for these cases when a checkbox is checked or an option is selected on the cobbox, when these events occur an Ajax call should be triggered, it sends request to the servlet for data and then the servlet should return the values as JSON or XML, when the browser receives the response as JSON or XML then using javascript we have to parse the response and build the javascript string containing combobox code and then insert that into the DIV which displays it on HTML.  

The following snippet shows how to build combobox using javascript and insert into HTML:-

var selectHtml = '<select name="dibujoshechos" id="dibujoshechos">';
for (..){
    selectHtml += '<option>' + valueToBeDisplayed + '</option>';
selectHtml += '</select>';

On the server side to convert objects into JSON there are redymade libs available.

How to get the auto generated primary key of the inserted row

Hi there is one common problem in the development I saw was how to retrieve the auto generated key for the row that we insert into the database.

Normally what developers does is first they will insert the data into the database and then immediately they try to fetch the primary key by querying the database asking for max number of the primary key column as it is auto sequenced and always the max number will be the just inserted row's primary key.

This does not work all the time because in a multi threaded environment it is possible that two clients insert the rows into the same table at same time. So this fails at that point of time.

Solution in java:-

Instead just executing the query using Statement object in jdbc use the following methods that are there since 1.4. The following are the methods present in Statement class part of the sql package.

Methods in Statement Class:-

 intexecuteUpdate(String sql, int autoGeneratedKeys)
          Executes the given SQL statement and signals the driver with the given flag about whether the auto-generated keys produced by this Statement object should be made available for retrieval.
 intexecuteUpdate(String sql, int[] columnIndexes)
          Executes the given SQL statement and signals the driver that the auto-generated keys indicated in the given array should be made available for retrieval.
 intexecuteUpdate(String sql, String[] columnNames) 

For using with prepared statement the following are the methods in Connection class.

For Using With PreparedStatement Method in Connection Class:-

 PreparedStatementprepareStatement(String sql, int autoGeneratedKeys)
          Creates a default PreparedStatement object that has the capability to retrieve auto-generated keys.

when using the above methods they make available of the any auto generated keys available for the insert made by that Statement object.

To retrieve the auto generated keys from the Statement object use the following method of the Statement class.

Method in Statement Class To Retrieve Keys:-

          Retrieves any auto-generated keys created as a result of executing this Statement object.

Common problem that developers face with Ajax

On so many web sites when ajax is being used to update part of the page sometimes we see 404 server response page which is the ugly part. This is due to lack of proper knowledge of developers on Ajax.


The ideal solution would be to do nothing if the response from the server is not ok. To do this we should check the Ajax request status. if the Ajax request status is 200 that mean the server response is proper, if not then there is a problem. So do nothing when there is a problem.

The following is the code for complete Ajax call:-

function getHTTPObject() {
             if (typeof XMLHttpRequest != 'undefined') {
                        return new XMLHttpRequest();
             try {
                          return new ActiveXObject("Msxml2.XMLHTTP");
              } catch (e) {
                        try {
                                        return new ActiveXObject("Microsoft.XMLHTTP");
                          } catch (e) {}
                return false;

 <script type="text/javascript">      
   function getSearchStudents(){
                document.getElementById("noStudent").style.visibility = "hidden";
                var userString=document.getElementById("userString").value;
                var http=getHTTPObject();
                 http.open("GET", "searchStudent.do?userString="+userString, true);    
                 http.onreadystatechange = function() {
                              if (http.readyState == 4 && http.status == 200) {
                                                      document.getElementById("noStudent").style.visibility = "visible";
                                                      document.getElementById("noStudent").style.visibility = "visible";

One good thing that developer needs to know is the states of the Ajax request. There are four states. The "readyState" property can hold four values that is 0,1,2,3,4.

0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready

20 June 2013

How to break the Firewalls reliably

We have been listening about firewalls from long time. All the organizations are almost using firewalls to control the traffic of their employees. So when you are working in an organization mostly you will be behind a firewall. All the traffic that goes from your computer will be monitored and controlled. So how do we break this firewalls to have a free access to internet? Is there a way to do it?

The answer is yes. There is a reliable way to break the firewalls. The technique is called "HTTP Tunneling".

What is HTTP Tunneling?

It is wrapping other protocols in HTTP protocol. Any protocol can be wrapped inside the HTTP Protocol. So wrapping other protocols inside HTTP Protocol and sending them to bypass the firewalls is called HTTP Tunneling.

How This Can Be Done?

The client (It could be anything) sends a HTTP request(wrapping another protocol inside it) to the HTTP Tunneling server. When client makes a request to the HTTP Tunneling server client first establishes connection to the firewall (assuming it as proxy server), then proxy server establishes connection on behalf of the client to the HTTP Tunneling server, then HTTP Tunneling server takes the request rips off the HTTP headers and sends the original protocol to the remote host (The host that we finally want to reach) by establishing a connection, then remote host responds and sends response to the HTTP Tunneling server and it wraps the response inside HTTP Protocol and sends HTTP response to the client. Then the HTTP response reaches the firewall and it sends the response to the client. The client extracts the data from the HTTP response and uses it.

The following picture shows how it works:-

No organization blocks HTTP protocol and its ports. They cannot block all and allow few sites. They block few sites and allow the rest so we can reliably break the firewall but if you are caught in the organizations doing this they will consider it a serious offence. No firewall can stop this.

The only thing we need to know is HTTP Protocol and the protocol that we wrap inside. If you know the specs of this that is good enough to do it on your own. If you don't know anything about protocols then use ready made software available on net.

You can get HTTP Tunneling clients and servers for free of cost on the net or if you are a programmer you can build one very easily. 


 HUB: - 

This is the least intelligent device on the network. It copies the packet arrived on one port to all of its other ports except the port that it came from. So there is no difference in broadcasting and a normal packet.

If computers are connected in bus topography and if that line is connected to hub, all the computers on that bus reads the packet which is placed by hub at the same time which mean the packet travels to the end of the bus replicating a copy to each node on the bus.


A switch does essentially what a hub does but more efficiently. By paying attention to the traffic that comes across it, it can "learn" where particular addresses are. For example, if it sees traffic from machine A coming in on port 2, it now knows that machine A is connected to that port and that traffic to machine A needs to only be sent to that port and not any of the others. The switch now records the IP or MAC in its table.

If any multicast packet or a packet (MAC or IP) which is not known to it arrives on the port it replicates that packet to all its ports except the port that the packet arrived from.

 The net result of using a switch over a hub is that most of the network traffic only goes where it needs to rather than to every port. On busy networks this can make the network significantly faster.


These are the most intelligent and complex devices on the network. It routes the packet according to the routing table recorded in it. It also may add additional headers to the packet for efficient routing.

When ever it routes the multicast packet to another network it reduces the packets TTL by one. When the TTL becomes 0 the packet will no more be forwarded by the router. It drops the packet. 

How SSL (Secure Socket Layer) works

In our day to day activities on web we use "https" protocol for secure authentication. Most people do this unknowingly. Most of the developers does not know how this protocol works and how it makes authentication or browsing safe. For the people who are curious to know how this works, here it is.

HTTPS uses SSL. SSL mean Secure Socket Layer. SSL is combination of symmetric and asymmetric cryptography.

 Secret Key Cryptography (Symmetric cryptography):-

In this both the parties who are willing to share the data uses the same secret key and cryptography algorithm to encrypt and decrypt the messages. In this both parties should have a prior understanding on the secret key and the algorithm that they use in cryptography. The same key and algorithm is used for both encryption and decryption.

 Public Key Cryptography(Asymmetric cryptography):-

In this if "A" wants to send a secret message to "B" then "B" will have his own Private key and will share his Public key over the network to "A". Using Public key the messages can be encrypted but they cannot be decrypted. They can be decrypted only by the corresponding Private key. So now "A" will take the Public key of "B" and will encrypt the messages that he wants to send to "B". Once "B" receives the messages from "A" he will decrypt them using his Private key. The public and the private keys are cryptographic inverses of each other; what one key encrypts, the other key will decrypt. So this is called Asymmetric Cryptography.

 Public key cryptography requires extensive computations, making it very slow. It is therefore typically used only for encrypting small pieces of data, such as secret keys, rather than for the bulk of encrypted data communications.

 How SSL Works In Brief:-

 client sends a request to the server by providing information such as highest SSL version it supports, cypher suites (A set of cryptographic algorithms) available with it.
Server chooses the SSL version and best cypher suite which are available on both client and server and sends this information to the client.
server also sends its public key certificate to the client.
client encrypts the "secret key" and cypher algorithm that they should use on further negotiations using servers public key and will send it to the server.
client and server have an agreement on cypher algorithm and secret key that they should use.
Now client and server changes to the encryption mode.
Now both exchange the information using symmetric cryptography.
At the end of the connection, each side will send a close notify message to inform the peer that the connection is closed.

                   **********************Hope You Enjoy This*****************