Saturday, 13 September 2014

Method overloading in Javascript

Background on method overloading

If you are from java or C# background then you must be familiar with the concept of method overloading. You can refer to following post on method overloading in java


Just to summarize (as far as java is considered) two methods are said to be overloaded if they have same method name but different method signatures. Also note method signature is the name of the method plus the number and types of arguments. Signature has nothing to do with return type. Also two methods cannot have same signature.

So for example

public void foo(String arg1);
public void foo(String arg1, String arg2);

are overloaded methods. Also note method overloading is a compile time phenomenon. Which method is to be used for execution is decided at compile time depending on the method signature.

Okay enough of Java overloading background. Lets head to javascript.



Method overloading in Javascript

Method overloading is not possible in Javascript in strict sense!

yeah that's right. You should not do something like

function foo(x)
{
  //some logic 
}

function foo(x,y)
{
  //some logic 
}

Why have i written "should not" rather than "cannot" is because no body can stop you from writing the methods above. It's just that it will not serve it's intended purpose. Why not ?-

The issue is that JavaScript does NOT natively support method overloading. So, if it sees/parses two or more functions with a same names it’ll just consider the last defined function and overwrite the previous ones.

So  foo(x,y) wold override foo(x) in above case.  So if I call method as foo(1) and as per what I have written above foo(x,y) will overwrite foo(x) why is there no some kind of error or Exception ? 

Well because when you specify arguments in the round brackets - they are just like synthetic sugar coating on the real arguments. This is where there is another JavaScript feature, which a lot beginners miss out on. In any JavaScript method, the arguments passed into the method are accessible via an Object array with the name arguments.

So lets say you now have a method

function func1(a,b,c)
{

   //some logic 
} 

and you call func1(1,2,3,4) then a=1(arguments[0]), b=2(arguments[1]),c=3(arguments[2]) and you c(arguments[3]). So as I said arguments inside round brackets are just to improve the functionality.


In fact for above method you can also call it like func1(1,2) and in this case arguments c and d will be undefined. Following the same argument above you can have a function defined with no argument and call it with any number of arguments.

You can check any variable if it is undefined in the following way (using typeof ) -


function func1(a,b,c,d)
{
   if(typeof a == 'undefined')
   {
      alert("a is undefined"); 
    }
     // and so on... 
}


So how do we resolve this issue ?

One of the way I think is suitable for most of the case is follows -

Lets say you have method

function foo(x)
{

} 


Instead of overloading method which is not possible in javascript you can define a new method

fooNew(x,y,z)
{
}


and then modify the 1st function as follows -

function foo(x)
{
  if(arguments.length==2)
  {
     return fooNew(arguments[0],  arguments[1]);
  }
} 

If you have many such overloaded method consider using switch than just if-else statements.

Related Links


Monday, 8 September 2014

Lifecycle of SimpleFormController of Spring MVC

Background

Yes SimpleFormController has been deprecated since Spring 3.0 but is still widely used. So  in this post I am going to discuss the lifecycle or workflow of this controller.

Steps

Workflow is as follows and it is controlled by AbstractFormController class - 

  1. The controller receives a request for a new form (typically a GET).
  2. Call to formBackingObject() which by default, returns an instance of the commandClass that has been configured (see the properties the superclass exposes), but can also be overridden to e.g. retrieve an object from the database (that needs to be modified using the form).
  3. Call to initBinder() which allows you to register custom editors for certain fields (often properties of non-primitive or non-String types) of the command class. This will render appropriate Strings for those property values, e.g. locale-specific date strings.
  4. Only if bindOnNewForm is set to true, then ServletRequestDataBinder gets applied to populate the new form object with initial request parameters and the onBindOnNewForm(HttpServletRequest, Object, BindException) callback method is called. Note: any defined Validators are not applied at this point, to allow partial binding. However be aware that any Binder customizations applied via initBinder() (such as DataBinder.setRequiredFields(String[]) will still apply. As such, if using bindOnNewForm=true and initBinder() customizations are used to validate fields instead of using Validators, in the case that only some fields will be populated for the new form, there will potentially be some bind errors for missing fields in the errors object. Any view (JSP, etc.) that displays binder errors needs to be intelligent and for this case take into account whether it is displaying the initial form view or subsequent post results, skipping error display for the former.
  5. Call to showForm() to return a View that should be rendered (typically the view that renders the form). This method has to be implemented in subclasses.
  6. The showForm() implementation will call referenceData(), which you can implement to provide any relevant reference data you might need when editing a form (e.g. a List of Locale objects you're going to let the user select one from).
  7. Model gets exposed and view gets rendered, to let the user fill in the form.
  8. The controller receives a form submission (typically a POST). To use a different way of detecting a form submission, override the isFormSubmission method.
  9. If sessionForm is not set, formBackingObject() is called to retrieve a form object. Otherwise, the controller tries to find the command object which is already bound in the session. If it cannot find the object, it does a call to handleInvalidSubmit which - by default - tries to create a new form object and resubmit the form.
  10. The ServletRequestDataBinder gets applied to populate the form object with current request parameters.
  11. Call to onBind(HttpServletRequest, Object, Errors) which allows you to do custom processing after binding but before validation (e.g. to manually bind request parameters to bean properties, to be seen by the Validator).
  12. If validateOnBinding is set, a registered Validator will be invoked. The Validator will check the form object properties, and register corresponding errors via the given Errors object.
  13. Call to onBindAndValidate() which allows you to do custom processing after binding and validation (e.g. to manually bind request parameters, and to validate them outside a Validator).
  14. Call processFormSubmission() to process the submission, with or without binding errors. This method has to be implemented in subclasses.


Above was the workflow  as specified in the Spring documentation of AbstractFormController. 

If it's confusing refer to following diagrammatic representations and try to co-relate

Diagrammatic Representation



Note :  If there are any errors in command object fields binding form will be reloaded (as shown in Request 2 of above diagram and after processFormSubmission(), showForm() and referenceData() are again called). onSubmit() is never called if this happens.

Typically a Spring bean lifecycle of a SimpleFormController would look something like below - 



Understanding some basic methods

  • isFormSubmission() : This method determines whether form is submitted (a POST request) or is for initial viewing (a GET request). This method is the base on which the two workflows of SimpleFormController are split.
  • formBackingObject() : This method returns an instance of command object which is the form Object. You can specify the class of this Object by setCommandClass( ) method. Or you can directly specify it in your bean configuration file -

    <property name="commandClass">
    <value>org.opensourceForgeeks.FormBackingObject</value>
    </property>

  • initBinder() : This method is called after the form command object is created and data binder is created by the controller. Developers can override this method to register custom PropertyEditor.
  • isValidateOnBinding(): If this method returns true then the binding validations are performed. By default it is set to true and final. Only way to change it is through setValidateOnBinding() method.
  • referenceData(): This method is used to provide reference data if any. Do not confuse it with formBackingObject() method where form Object is created. This method is used to provide any extra reference data that model may need to render UI page other that the command object. Whole model is then sent  to the View set by formView property of the bean in dispacher-servlet.xml file. Form View will then be rendered (See above diagrams for reference).

Related Links

Tuesday, 2 September 2014

Calling JavaScript function in href vs. onclick

Background

There are multiple ways to call a Javscript function in an anchor tag. You can put the method in href attribute or you can use onclick event or jquery events. This post is about good practices while calling a javascript function in such a scenario.


Usage in order of  increasing good practice


<a id="myLink" href="javascript:MyFunction();">link text</a>
 
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
 
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
 
<a id="myLink" title="Click to do something" href="#" onclick="MyFunction();return false;">link text</a>
 
<a id="myLink" title="Click to do something" href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>

But the best practice as of now is to use jquery and attach an even handler to the elements id. Something like -

$('#myLink').click(function()

  {

     MyFunction();

     return false;

  }); 

 Notes

  • The onclick won't fire if someone middle-clicks on your link to open a new tab or if they have JavaScript disabled.
  • In case javascript is enabled adding return false in  onclick will will prevent browser from following the link.
  •  If you don't have a link in href attribute you should do javascript:void(0) rather than # in the href attribute.  '#' will take the user back to the top of the page if it is present in the href attribute and onclick is not returning false.

 

Related Links


Saturday, 30 August 2014

JAXB Tutorial for Java XML binding with annotations

JAXB

JAXB stands for JAVA Architecture for XML bindings. We will come to it in some time. Before that we need to understand a even basic concept - Serialization. Simply speaking Serialization is the process of turning an object in memory into a stream of bytes so that it can be transferred over a network or stored in a persistent storage.


There are various ways to serialize an object. For eg.

  1.  Serialization via XML. Convert the Object to XML transfer it and then convert it back to XML. 
  2. You can do the save via JSON (Javascript object notation).
  3. Or you can use the Serialization provided by Java i.e by making your class implement Serilizable interface.
In this post we will see how can we serialize/de-serialize Objects to and from xml.

Note : The verbs Marshal and Unmarshal are synonymous with Serialize and Deserialize. Specially in XML serialization you will hear the words   Marshal and Unmarshal very frequently.


Dependencies ??

If you are using JDK 6 or higher version you don't have to worry about any dependencies as JAXB comes bundled with it. If you are using a lower version that Java 6 then you can download the jars from here. Download and add “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

 To the code....

First Create a model class file in package opensourceforgeeks.model. Lets call it Employee.java . Add the following code to it.
package opensourceforgeeks.model;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * 
 * @author athakur
 *
 */

@XmlRootElement
public class Employee {

    private String name;
    private int age;
    private int id;
    
    public String getName() {
        return name;
    }
    
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    
    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }
    public int getId() {
        return id;
    }
    
    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }
    
    @Override
    public String toString() {
        return "Employee [name=" + name + ", age=" + age + ", id=" + id + "]";
    }

}
 


Next lets create a class to test this out.  Create class JAXBTest.java under package opensourceforgeeks.test. Add the following code to it and run - 

package opensourceforgeeks.test;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import opensourceforgeeks.model.Employee; 
/**
 * 
 * @author athakur
 *
 */ 
 public class JAXBTest {

    public static void main(String args[]) {

        Employee employee = new Employee();
        employee.setName("Aniket");
        employee.setAge(23);
        employee.setId(101);

        try {

            File file = new File("C:\\Users\\athakur\\Desktop\\data.txt");
            JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            
            System.out.println("Serializing Data");
            //Serilization
            //put the xml in the file
            jaxbMarshaller.marshal(employee, file);
            //also print it on standard ouput
            jaxbMarshaller.marshal(employee, System.out);
            
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            
            System.out.println("Deserializing Data");
            //Deserialization
            //read the xml to get the Object
            Employee newEmployee = (Employee) jaxbUnmarshaller.unmarshal(file);
            System.out.println(newEmployee);

        } catch (JAXBException e) {
            e.printStackTrace();
        }


    }

}
Your project structure should look like below - as per above conventions of-course. You are free to put the code anywhere you like :)


Output : 

On the standard output console you can see - 

Serializing Data
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="101">
    <age>23</age>
    <name>Aniket</name>
</employee>
Deserializing Data
Employee [name=Aniket, age=23, id=101]

You can also verify the data in the file whose path you have provided. XML should be generated in that file. It will have same XML as shown on standard output. For more details you can refer to the tutorial provided on the JAXB official site.

NOTE1 : In the model classes that you annotate you need to have default constructor (If you do not have any constructors Java compiler will put one default no arg constructor for you). If you do not provide default constructor you will get following exception -

JAXBException occurred : 1 counts of IllegalAnnotationExceptions.

NOTE2 :  If you get following exception - 
No message body writer has been found for response class
Make sure you are annotating root element with @XmlRootElement

Summary

Its quite self explanatory - the bindings and the conversion. Got the following diagram from the web that explains it in simplest way -



Related Links

Sunday, 24 August 2014

Enabling telnet client on Windows 7

Background

A terminal emulation or telnet is a program for TCP/IP networks such as the Internet. The Telnet program runs on your computer and connects your PC to a server on the network. You can then enter commands through the Telnet program and they will be executed as if you were entering them directly on the server console. (More on Wiki)

If you type telnet in your windows console you will see command not found


That's because telnet client is not enabled by default on Windows. Lets see how can we enable it.

To enable Telnet command line utilities:

  1. Click Start > Control Panel.
  2. Click Programs and Features.
  3. Click Turn Windows features on or off.
  4. In the Windows Features dialog box, check the Telnet Client check box.
  5. Click OK. The system installs the appropriate files. This will take a few seconds to a minute.

Screenshots





And telnet client should be enable in your windows. You can just type telnet and check. It should open Microsoft telnet client. Or you can try directly connection to a host.

Eg. telnet alt4.gmail-smtp-in.l.google.com 25



Related Links

t> UA-39527780-1 back to top