Thursday, June 13, 2013

JavaScript Closure.

What is a Closure :

Closure is a reference to a function together with the referencing environment.

Two important things to note in the above definition is that closure comprises of two things as follow
  1. A reference to a function.
  2. Binding function's referencing environment (in our case local variables inside the function's scope).
Let us see an example to grasp these two points better.

function HelloWorld(){
    var msg = "Hello World";
    function PrintHelloWorld(){
        alert(msg);
    };   
    return PrintHelloWorld;
};


var referenceToPrintHelloWorld = HelloWorld();
referenceToPrintHelloWorld();


Output of this program : [Hello World]

In the above code snippet, function HelloWorld() returns a reference to PrintHelloWorld(). PrintHelloWorld() closes over the local variable "msg" of HelloWorld(), which is in its execution environment. Here execution environment is the scope in which this function in declared and that is scope of HelloWorld function. Hence this satisfies definition of closure.

Notice though "msg" is defined locally inside HelloWorld's scope but still when we call referenceToPrintHelloWorld() from scope outside of HelloWorld() it alerts the value "msg". This is the magic of closures which closes over any local variable in its scope.

A Use Case : Classic last value problem

Preparation code

<html>
<body>
  <button id="button1" >Button 1</button>
  <button id="button2" >Button 2</button>
  <button id="button3" >Button 3</button>
  <button id="button4" >Button 4</button>
  <button id="button5" >Button 5</button>

</body>
<script>

  for (var i = 1; i <= 5; i++) {
    document.getElementById('button' + i ).onclick = function() {
      alert('You clicked on BUTTON with unique number : ' + i );
    };
  }
</script>
</html>


This is a simple code in which onclick event is attached to the buttons using a loop. When user clicks a button its unique number is supposed to be alerted, e.g When user clicks on the first button it is supposed to alerts "You clicked on BUTTON with unique number : 1". Where this unique number is supposed to be assigned during the loop execution.

Go ahead, run this program and see the output.

Output of this program irrespective of which button you press is always : [You clicked on BUTTON with unique number : 6].
No matter which button you click all the button have the same unique number "6" attached to them.

The root of this confusion is that all the onclick event refer to the same variable i , and at the end of the loop the value of i is 6. So whenever you click on any button it refers to the same variable i which has a value of 6 now. This is exactly the "last value" problem.

So how do you solve this problem ???

You might have guessed it by now and its closures ( though there are other way too). Since closures binds the context (in our case a unique number for every button).

So what we do to solve this problem we assign closures to onclick event rather that simple functions.

Here is the solution.

for (var i = 1; i <= 5; i++) {
  document.getElementById('button' + i).onclick = (function(){
    var uid = i;
    return function(){
        alert('You clicked BUTTON with unique number : ' + uid);
    };
  })();
};


In this solution the value of i is stored in the execution environment which is binded to the function that is returned by the self executing anonymous function. 
 
This is not the best elegant solution. The variable uid is used in this example to just highlight that value of i is stored in the local variable uid which is in the execution environment.

Elegant way of doing this would be passing the value of i as argument to self executing functions scope.

for (var i = 1; i <= 5; i++) {
  document.getElementById('button' + i).onclick = (function(uid){   
    return function(){
        alert('You clicked BUTTON with unique number : ' + uid);
    };
  })(i);
};


P.S.


Closure is a fun thing in JavaScript and can be applied to problems where context of execution has to remembered. Go on and take a dive into closures.    

Wednesday, June 12, 2013

Scoping and Hoisting in Javascript

Scoping


What is the output of following JavaScript code.

  var x = 1;
  {
   var x = 2;
   console.log("Inside: " + x);
  }
  console.log("Outside: " + x);


If your answer is 2,1 then you must read on.

In JavaScript function is the only thing that creates a new scope

Lets see an example to understand what this means.

var x = 1;
function y() {  

     var x = 10;
     console.log("Before Exiting y's scope the value of x is : " + x);
}
console.log("Outside y
's scope the value of x is : " + x);

y();

Output of this program is

    Outside y's scope the value of x is : 1
    Before Exiting y's scope the value of x is : 10

The reason is function y() creates its own local scope and any variable in functions scope is local to its scope. Here var x = 10 declaration inside scope of  function y() overshadows var x = 1 declaration in global scope.

Lets modify the above example a little bit and see what happens.

  • Program 2:

var x = 1;
function y() { 

     console.log("On Entering y's scope the value of x is : " + x);
     console.log("Before Exiting y's scope the value of x is : " + x);
}
console.log("Outside y
's scope the value of x is : " + x);

y();


  • Program 2 (modified):

var x = 1;
function y() { 

     console.log("On Entering y's scope the value of x is : " + x);
     var x = 10;

     console.log("Before Exiting y's scope the value of x is : " + x);
}
console.log("Outside y
's scope the value of x is : " + x);

y();

If you expect the result as 1,1,1 and 1,10,1 then you must watch closely.
  • Output of Program 1 is : 1,1,1 
  • Output of Program 2 is : undefined,10,1
Some of you may find it very amusing that why the value of x on entering y's scope in Program 2 is undefined ?


The answer to this subtle question is scoping and variable declaration hoisting.

 

Hoisting

Variable Declaration Hoisting


Program 2 is internally interpreted as below, declaration of variable x inside will be hoisted to the top of its scope (in our case scope of function y() ). Only declaration is hoisted not the assignment.

On entering function y() scope the program try to access the value of x but by this time only x is declared not assigned, hence JavaScript returns undefined. This is a subtle but important understanding. 

  • Program 2: Variable Declaration hoisting 

var x = 1;
function y() {

     var x;
     console.log("On Entering y's scope the value of x is : " + x);
     x = 10;

     console.log("Before Exiting y's scope the value of x is : " + x);
}
console.log("Outside y
's scope the value of x is : " + x);

y();

Function Declaration Hoisting


Like variables functions are also hoisted. Hoisted in a sense browser first loads the function declaration before anything else is loaded.

Lets see an example of function declaration hoisting.

  • Program 3: Function Declaration hoisting

bar();

function bar() {
    console.log('bar called.');
};
 
 


Output of this program is :  [bar is called]
The reason is as already said function declaration is loaded upfront by the browser before it loads anything else.

Functional Expression hoisting


Lets see another slightly different example.
 
  • Program 4: Functional Expression hoisting

foo();

var foo = function () {
    console.log('foo called.');
};
 

Output of this program is : [TypeError : foo is not a function].

The slight difference between Program 3 and Program 4 is use of  functional expression in the later .

Remember only declaration is hoisted not assignment. Hence internally Program 4 is interpreted as.

 

  • Interpreted Program 4: Functional Expression hoisting

var foo;
foo();
foo = function () {
    console.log('foo called.');
};


Here foo is only declared not assigned any type at the point where call is made and this call is assumed of type function which is an error, hence TypeError .

Conclusion

  1. Function is the only thing that creates a new scope in JavaScript.
  2. Only variable declaration is hoisted to the top of its scope, assignment is not hoisted.
  3. Function declaration (not functional expression) is loaded first by the browser before it loads anything else. 

 

Tuesday, June 11, 2013

JNI - Java Native Interface

Java Native Interface


JNI is a standard programming interface used to solve following problems.
  1. Write Java native methods.
  2. Embedding Java Virtual Machine(JVM) into native application.

Java native Methods:

Java native methods allow programmers to write methods in some other programming languages, such as C , C++ etc. Use case for native methods are as following.
  1. Use certain system functionality that can't be done using pure java.
  2. Get performance mileage by implementing performance sensitive methods in native over pure java.
Follow the link for sample code. Native method Step by Step 

Embedding JVM into native application:

There are certain cases when we require to call existing Java methods in our native code. This is achieved by embedding JVM into our native application.

Follow the link for sample code. Embed JVM in native C code   

Friday, May 10, 2013

Maven Plugin Configuration

Configuring Maven plugins :


Maven plugins are configured broadly in two ways.
  1. Global configuration : This configuration applies to all the goals of a plugin.
  2. Execution specific configuration : Configuration is binded to a specific goals and phases.

Global Configuration :

To apply configuration for all the goals of a plugin follow the syntax shown in following XML. In this example we set compiler version to 1.6 (default is 1.5) which applies to all the goals of compiler plugin (such as compiler:compile, compiler:testCompile etc.)

Execution Specific Configuration :

In advanced build process we may require to execute a plugin with certain configurations for a certain execution. Say for the first execution we need to compile with 1.3 compiler version and for the second execution we need to compile with 1.5 compiler version. This is shown in following XML.

Another use case could be binding the configuration to specific goal and phase as shows below. In this case for antrun plugin configuration is binded to validation phase and run goal .


NOTE: Global Plugin configurations are overriden/merged by more specific execution plugin configuration

P.S. To find all the goals and default configuration of a plugin(say compiler plugin) type mvn help:describe -Dplugin=compiler -Ddetail .

Maven : The Project Management Tool

Apache Maven : 

Maven is a tool that can be used for building and managing any Java-based project. The central concept of Maven is POM, which is a revolution in itself. POM stands for Project Object Model. Maven is used to build project's, generate reports and documentations from a central piece of information.

In this tutorial we will go through a very basic example that covers dependency management using Maven.

Install Maven on Windows:

Follow this link install Maven on windows. 

http://maveninstall.blogspot.in/

Maven Coordinates : 

Most important thing in Maven are Coordinates. Maven Coordinates uniquely define any Project, dependency or plugin. These coordinates are used in a pom.xml. Below is a snippet of pom.xml that shows coordinates of a maven dependency.
 
 Every coordinate is identified by a unique set of groupId / artifactId / version .

Finding Coordinates : 

Not all but almost every library is listed on http://search.maven.org/#browse . This site has a nice search ability.

Build the project

  1. Open CLI (Command Line Interface) and type mvn archetype:generate. This will print many numbers. These numbers correspond to certain archetype. Maven provides a default number to choose. Though you are free to type in any number(in the printed range) we will choose default. For choosing default just press ENTER.
  2. Now choose version of the archetype or just press ENTER to accept default.
  3. Now enter groupID of your project, say com.mypackage, and press ENTER.
  4. Now enter artifactId, say helloMaven, and press ENTER
  5. Accept default version(1.0-SNAPSHOT), press ENTER.
  6. Accept default packge name or change it if you like, we will accept default which is com.mypackage
  7. At this point Maven will show the values of coordinates(groupID, artifactID, version, package name) and ask you to verify them. Verify and Press 'Y' . A Build success message is displayed. 
     
 By this time Maven did a couple of things for you.
  • Firstly Maven created a default project structure (using selected default archetype) for us. This is boiler plate kind of project which will print "Hello World". 
     



  • Secondly Maven created a directory under your HOME with name ".m2". This serves as a local repository of dependent Maven artifacts. By default Maven tries first to resolve the dependencies by looking into this repository, if artifact not found then it may look into maven central repository or your hosted repository as per the settings. Default POM generated in our "helloMaven" project contains dependency on junit. Checkout .m2 for this dependency under <HOME>/.m2/repository/junit/junit/3.8.1.  


Compile the project. 

  • Go to project location, i.e. path../to../helloMaven  . 
  • Type mvn compiler:compile. (use command line)
This command compiles the source code . Compilation can be done using javac also but we used maven since this a maven tutorial. But how does Maven did it. The answer is plugins. You might argue that we did not have compiler plugin in our pom.xml. You are partly right, our pom.xml does not explicitly declared any plugin but inherited the default plugin from Super pom. 

Type mvn help:effective-pom to view effective pom. From this we can confirm that Maven used maven-compiler-plugin (version 2.3.2).



NOTE: Every pom inherits from Super pom and the final pom thus generated is known as effective pom. 

Run the project:

  • Go to project location, i.e. path../to../helloMaven .
  • Type mvn exec:java -Dexec.mainClass="com.mypackage.App" .  Follow the following format <package-name>.<main-class-name>. This will run main class in our case "App". On running our main class it prints "Hello World!" on the console.






Cheers we have now built, compile and ran our first mavenized project.  



Monday, May 6, 2013

Install Apache Maven on Windows.


Installing Apache Maven on Windows.


To install maven you just need to set the environment variables after downloading and extracting maven's zip file as shown here.
  1. You need a Java Development Kit (JDK), the Java Runtime Environment (JRE) is not sufficient. Make sure that JAVA_HOME exists in your user variables or in the system variables and it is set to the location of your JDK, e.g. C:\Program Files\Java\jdk1.6.0 and that %JAVA_HOME%\bin is in your Path environment variable (see Fig. 1). 
  2. Download Maven zip file and extract it, e.g. D:\soffy\maven\apache-maven-3.0.4
  3. Add this Maven extracted location to the environment variables (see Fig. 1).


Fig. 1


Now test if you have configured the env. variables correct by typing mvn -version in the command prompt. If everything is ok you will see output like as in Fig. 2.


 
Fig. 2 


If you are through upto this point then Congrats you have installed Maven successfully and ready to dive into the world of Maven.

Building Android Project with Maven


This Tutorial will take you through a Step by Step approach for building an Android project using Maven. Though an IDE is not necessary but in this tutorial we will use Eclipse-Juno.

Requirements : 

Install the follwing plugins into the Eclipse-IDE.
  1. Install m2eclipse plugin. This plugin provides swift integration of Maven into the Eclipse IDE. Follow this link, which shows how to install m2e plugin into Eclipse http://eclipse.org/m2e/download/
  2. Install ADT (Android Development Toolkit) plugin. Follow this link for installation instructions. http://developer.android.com/sdk/installing/installing-adt.html 
  3. Install m2e-android plugin.  This adds maven support for Android Developer Tools and the Maven Android Plugin. It brings the power of Maven dependency management into the ADT. To install this plugin into Eclipse go to Help -> Eclipse Marketplace and search for "android m2e". 

Start a Maven based android project from scratch. 

In this approach we will start developing a maven based android project from the scratch.

  1. In eclipse start a new Maven Project.
  2. Click Next. Now a Select an Archetype dialog appears.
  3. Click on Add Archetype button. This prompts user with a Add Archetype dialog box. Fill in the Group Id as "de.akquinet.android.archetypes", Artifact Id as "android-quickstart" and Version as "1.0.8" . For now leave Repository URL blank. Click OK.
  4. Now select this Artifact from the list and click Next.
  5. In the dialog box fill in the Group Id (e.g. com.mycompany) and Artifact Id (e.g. myproject) for your project. Click Finish.
  6. Now our boilerplate mavenized android project is ready but it shows an error 'missing required src/test/java'. This is a bug in m2e-android plugin. To fix this issue, manually create folders test/java inside your src folder 
  7. Now run this project. This will show Hello <your project name>!. In our case this displays Hello myproject! 

Cheers .... We have successfully created and ran an Android App integrated with Maven. Now we can also use command line maven tools to resolve dependencies, deploy , run any android project also. 

Following above steps sets up a basic Android project integrated with Maven. Let us now examine generated pom.xml. 
  • First thing to notice is the packaging tag which is set to type apk.
  • Next important thing is to let maven compile your android app, maven must have Android SDK into its repository (local/central). In this example required android.jar (android sdk API level 10) is fetched from mavens central repository, which is set as dependency as following Maven coordinates com.google.android / android / 2.3.3 (Group Id / Artifact Id / version ).   
  • Another important tag is build plugin. Default POM generated already configured "android-maven-plugin" for you. This plugin is the heart of android maven integration. Inside this plugin, notice that platform tag is set to 10. This API level must be same as of used in dependency tag for Android SDK. (set 10 for 2.3.3 jar or set 16 for 4.1)



Friday, April 26, 2013

Enable SSI (Server Side Includes) on Tomcat Apache (Windows).


Enable SSI on Tomcat Apache.   


Disclaimer : This blog and all of its content is for beginners, so geeks and gods please don't feel offended by my posts.

In one of my projects it was required to enable SSI on Tomact Apache running as Window service. It took me a quite a time to figure it out, I seriously don't know if I was dumb that took me so long to get this done but anyways I felt sharing this with you.

Lets get started. Please follow step by step. 

You need to modify two files inside the conf folder. First one is web.xml and other is context.xml.

1. Modifications in web.xml.


  • Uncomment servlet with servlet name as 'ssi'.
  • Uncomment servlet-mapping for this servlet i.e 'ssi'
  • If you want to support SSI for .html file extension also then add one more servlet mapping .  Finally your mapping should look like this 
       <!-- The mapping for the SSI servlet -->
          <servlet-mapping>
              <servlet-name>ssi</servlet-name>
              <url-pattern>*.html</url-pattern>
         </servlet-mapping>
         <servlet-mapping>
              <servlet-name>ssi</servlet-name>
              <url-pattern>*.shtml</url-pattern>
         </servlet-mapping>      
  •  Uncomment mime-mapping with extension "shtml"


2. Modifications in context.xml


  • Add attribute privileged="true" to Context tag. Your context tag should like following
       <Context privileged="true">
Adding privileged="true" enables this context to use container servlets, in our case this is ssi servlet.

Time for a Test.


Open any text editor  and write the following SSI directive in it.

<!--#config timefmt="%A" --> <!--#echo var="DATE_LOCAL" -->

Save this as test.shtml and test.html.
Host this on your Tomcat.
Hit this from browser and it should display current day.
Output of test.html




P.S. Please leave comments or share your thoughts. Suggestions are welcome.