20 October 2013

Preserving The dynamically Added Content When Revisited Using Back Button

The problem with back button is, When user clicks on the back button to revisit the page, the browser displays the cached page. When it displays the cached page all the content that we added dynamically to the html page using javascript on the client side will be lost. For example look at the following html.

HTML with dynamic content added on client side using javascript:-
<html>
   <head>
     <script>
       function insert(){
          var str="<div>Enter The Value :<input type='text' name='magic'></div>";
           document.getElementById("sky").innerHTML=str;
       }
     </script>
   </head>
   <body>
     <form action="xxx" method="post">
       Name : <input type="text"  name="name" >
       <div id="sky" onclick="insert()">Press here for magic</div>
       <input type="submit" value="submit" >
     </form>
   <body>
</html>

In the above html when the user clicks on the magic “div” the insert function gets fired and it inserts a div which contains some elements into the magic div. Now after this the user moved to the next page and he clicked the browsers back button to revisit this page. When he comes to this page again using browsers back button all the content that we added to this html using javascript will be lost as they are added at runtime. So to prevent this we can use few efficient techniques.

I mean if you want to restore the page when user revisited using browsers back button  with all the dynamic content then we can use Ajax or Cookies or Hidden fields to solve this problem. which technique to use will be based on your requirement. To restore the content fire ajax or javascript function on Page load. Even when the browser is loading the html from the cache the loading events gets fired so you can use any method to store the state and restore them using javascript or ajax by calling the functions when onload event gets fired.

Using Ajax to Deal this problem:-
Use the command pattern so that each method which modifies the page's UI by adding controls also invokes an AJAX method to push the method invoked (textual Javascript representation) onto a queue stored in the server's session.

After body onLoad completes, use an AJAX method to query the server's session for a command queue for the page the user is on. If one is retrieved, just eval each member of the queue to rebuild the page's UI in the same order the user did it.

For complete thread on how to solve using Ajax please follow the thread below:-
http://stackoverflow.com/questions/1724739/back-button-handle-a-dynamic-form/1724780#1724780



Preventing Caching of Ajax Requests

Normally when we use Ajax calls using get method the Ajax request will be cached in the browser’s history and the html pages are cached in the browser’s cache. So the problem with this is, when user clicks on the back button of the browser to return to previous page which have some ajax calls then the calls gets fired but the response comes from the cache. It does not hit the server. If we want to prevent the caching we have to make every request unique by adding a request parameter with some unique value.

The following technique shows how to make request unique:- 

var nocache = new Date().getTime(); 
var path = 'http://hostname.domain.tld/api/somejsonapi/?cache=' + nocache;

Now use the path as your url so that the request becomes unique every time and will not return the cached response. 

If using Ajax calls with get is not mandatory then use Ajax with post method so that the ajax requests and responses are not cached. Post method prevents caching in Ajax.

19 October 2013

Command Design Pattern

Command Design Pattern is helpful in some situations. People often talk about this design pattern without having the full understanding of the pattern. If it comes to j2ee frameworks, one of the most popular framework “Struts” uses this design pattern in an efficient manner. So what is Command Design pattern? and why is it named as Command Design Pattern?

Understanding Command Design Pattern and Why Named So:-
In computers command is not a new term. As humans treat themselves as masters and computers as slaves(as computers cannot think by themselves) the word command is suited for executing a set of instruction when some small word is passed to the computer called as command. 

For example in windows OS if you pass a command “dir” in the command prompt it returns the list of files in the current directory.  Here in this case the “dir” in windows is reserved to perform something. In depth the word “dir” is reserved and mapped to “dir.exe” which does the execution part. The dir.exe passes the set of instructions to the computer which is nothing but the receiver of the instruction that are executed when command is issued. The computer (receiver) then responds to the instructions passed and returns the list of files in the current directory. 

so now we understood the command implementor (dir.exe) which is nothing but can be called as command and the receiver (nothing but the computer in this case)   which receives the set or a single instructions from the command execution class. There is still one more important component that we missed which is nothing but invoker. When command is issued the invoker selects the “command implemented class or exe” which is required to execute the said command and executes the appropriate command class or executable. 

So finally there are three important components involved in Command Design Pattern. They are “Invoker” , “Command (command Implementor)” and the “Receiver”

Invoker selects the appropriate command implementor and executes the command. The receiver receives the instructions and will act accordingly. Finally the command issuer gets the desired output.

Now The Most Important Thing Is, What Problem Does It solve?
suppose when some common operations have to be performed around the command execution then this pattern is the answer for such cases. In this pattern the “Invoker” invokes the command. So if the cleanup and initialization operations have to be performed around the command execution the “Invoker” does that. This is the answer for such situations.

Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the class of the method or the method parameters. Using an invoker object allows bookkeeping about command executions to be conveniently performed, as well as implementing different modes for commands, which are managed by the invoker object, without the need for the client to be aware of the existence of bookkeeping or modes.

The following is the example in java for Command Pattern:-

ICommand.java
public interface ICommand{
    public void execute();
}

DirCommand.java
public class DirCommand implements ICommand{
        public void execute(){
               //code for listing the files in the current directory on console.
        }
}

Invoker.java
public class Invoker{

      public void intialize(){
        // perform some comman intialization operations
      }

      public void invoke(String command){
             intialize();
             String finalCommandClassName=command+”Command”;
             // code for instantiating the “finalCommandClass”.
            finalCommandClass.execute();
            cleanup();
       }

       public void cleanup(){
         // perform some cleanup operations here.
       }
}

MainClass:- 
public class MainClass{
      public static void main(String args[]){
        Invoker invoker = new Invoker();
        invoker.invoke(“Dir”);     
     }
}

For more references:-
http://en.wikipedia.org/wiki/Command_pattern

10 October 2013

Tips in designing cross browser html coding

Always add  <!DOCTYPE html> (this is the doc type for html-5) as the first statement in your html file so that browsers do not fall back to primary versions of html. Especially in IE if you dont add the doc type statement “div” alignments will not work as it evaluates and treats your html code as IE5 (quircks) mode which is a very old version.

 When defining “font-family” in your css don’t use generic family types like “serif”, “monospace”. This causes problems and gives different look and feel which is ugly. Especially in IE. Use only specific font families like “Times New Roman” as font families. 

 These two things did a great difference in my design especially when IE is considered.

03 October 2013

Using POJO DataSource in BIRT 4.3



To create a report in BIRT 4.3 we can use POJO dataSource. In 4.3 this DataSource is supported. To use this we need to create a dataset class. We can check this with one example. The following example is done keeping web applications in mind. with little modifications it can be used in the standard-alone applications as well.


To retrieve a student with a specific id we need to have two POJO classes. One is Student.java and the other one is StudentDataSet.java.


Student.java:-


package com.ymd;


public class Student {

private String studentId;
private String name;
private String mobile;
private String email;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}


StudentDataSet.java:-


package com.ymd;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import org.eclipse.birt.report.engine.api.EngineConstants;



import com.ymd.Student;


public class StudentDataSet {
private Iterator<Student> iterator;
public List<Student> getStudents(String studentId){
List<Student> studs=new ArrayList<Student>();
try{
Student stud=getStudent(studentId);
studs.add(stud);
}catch(Exception e){
e.printStackTrace();
}
return studs;
}
private Student getStudent(String studentId){
Student std=new Student();
// your logic to get the details of the student
//goes here. Fetch the student details and populate
// the Student.
return std;
}


//The following method will be called by BIRT engine once when
// the report is invoked. It is also a mandatory method.
@SuppressWarnings(value = { "unchecked" })
public void open(Object appContext, Map<String,Object> map) {
Map<String,Object> mur=(Map<String,Object>) appContext;
HttpServletRequest request=(HttpServletRequest)mur.get(EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST);
String studentId=request.getParameter("studentId");
iterator = getStudents(studentId).iterator();
}
//this method is a mandatory method. It must be implemented. This method
// is used by the BIRT Reporting engine.
public Object next() {
   if (iterator.hasNext())
       return iterator.next();
   return null;
}
//The following method is also a mandatory method. This will be
//called by the BIRT engine once at the end of the report.
public void close() { }
}


In the dataset class the three methods, “public void open(Object obj, Map<String,Object> map)”, “public Object next()” and “public void close()” must be implemented. They will be used by the BIRT Reporting Engine using reflection to generate the report. So in the dataset class we can get the request parameters in the “open” method. so we can pass any number of parameters in the URL and can get the parameters here and use to fetch the data required for the reports. 

The final step is to pack the two classes into a jar file. The name of the jar file can be anything. This jar file will be used by the report designer just to design the report. At run time the classes will be taken from the classpath. I mean in web applications they will be taken from “WEB-INF/classes” folder.


The remaining part of tutorial on how to use POJO Datasource can be read from the following link.

01 October 2013

Creating an Arrow And Circle Just With Html And CSS

Just with CSS we can create arrow marks. The following is the html code.


Code:-

<div style="width:0px;height: 0px;border-left: 15px solid transparent;border-right: 15px solid transparent;display: inline-block;zoom: 1;margin-left: 10px;float: left;border-bottom: 15px solid #999999;"></div>

The following is how it appears in the browser:-







The following is the code for creating a circle:-
<div style="float:left;width:50px;height:50px;">
<a style="background: #8f58a4;border-radius: 50%;cursor: pointer;display: inline-block;height: 100%;margin: 0;width: 100%;"></a>
</div>
Appearance in browser:-