Shortlink

Gradle your Java app

Working with ANT has always been a slightly boring experience for me because of it’s rigid XML syntax. Setting up classpath, tasks like clean, compile, run tests etc., every time is a tedious process.
Ever since I started working with Groovy I started looking at a build tool known as Gradle. Gradle is a Groovy script that can be used to automate the build activities of your project. Let’s see how to build a simple Java project using Gradle.

You can download Gradle and add the bin folder to the path. I have a simple project ‘GradleEx1″ with the following project structure.

The src folder will have a class Hello with the following code.

package com.durasoft;
public class Hello{
	public String sayHello(String name){
		return "Hello " + name;	
	}
}

The tests folder will have a test case HelloTest with the following code.

package com.durasoft;

import org.junit.* ;
import static org.junit.Assert.* ;

public class HelloTest{

	private Hello helloObj = new Hello();
	
	@Test
	public void testSayHello(){
		assertEquals(helloObj.sayHello("Sam"),"Hello Sam");
	}
}

Let’s create a build script build.gradle in the GradleEx1 folder. This gradle file will have a groovy script where you will specify the tasks compile, run tests and package them in a jar file. While doing that you will also add reference to JUnit library.

The build.gradle file is shown below.

apply plugin:'java'

version = "1.0"

repositories {
  mavenCentral()
}
 
dependencies {
  testCompile group: 'junit', name: 'junit', version: '4.8+'
}

sourceSets {
	main {
		java {
			srcDir "src"
		}
	}
	test {
		java {
			srcDir "tests"
		}
	}
}

Is that all??? Yes. All I have done is specify the source folders and the dependencies from maven repository. So what about the compile, run tests, jar etc? The single line apply plugin:’java’ does the trick. It gives you built-in tasks like compileJava, test, jar etc., associated with any ANT build. Here’s where the ‘convention over configuration’ paradigm of Groovy/Grails comes into picture.

So how do we run this? Go to command prompt and run gradle test from GradleEx1 folder.

You can also run gradle jar to create GradleEx1-1.0.jar file. Have a look at the build folder generated in GradleEx1 folder.
Gradle is pretty simple and straightforward and makes use of the DSL capability of Groovy. It’s definitely a welcome change in configuring builds.

Shortlink

Classes in JavaScript

JavaScript is a functional Object-Oriented language. The language’s first class citizens are functions. Functions can be assigned as literals to variables as shown below.

var workOut = function(calories){
    document.write("Burning " + calories + " calories);
}
workOut(100);

Functions can also be invoked with a new keyword. This feature in JavaScript paves way for writing some traditional Object-Oriented code.
Say you want to create a class with variables and methods in JavaScript, instantiate it just like you do in C#/Java. Let’s create a class Person with name and age attributes and eat method.

  function Person(theName,theAge){
     this.name = theName; //public variable
     this.age = theAge;
     this.eat = function(){
        document.write(this.name + " is eating");
     }
  }

If you want to now create an object of Person and invoke it’s eat method you can use the new keyword similar to other OO languages.

   var p1 = new Person("Sam",23);
   p1.eat();

So what’s going on behind the screens?. We will discuss more about them later.

Shortlink

Dive into Android development – V

Let’s try to connect to a server resource from an Android application and display the data. I have created a very simple JSP page ‘server.jsp’ that returns the server date and time. This date and time will be displayed in our Android application in a simple TextView component.
The server.jsp has the following code
                <%@page import=“java.util.Date”%>
                <%= new Date()%>

In the onCreate method of the Activity, you will use the normal Java approach to connect to a server and fetch data, i.e, using the java.net and java.io package. The code for connecting to the server.jsp is given below.
        TextView dateText = (TextView)findViewById(R.id.dataText);
        String address = http://YourAddress/server.jsp;
        try {
                     URL url = new URL(address);
                     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                     if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                         InputStream inputStream = urlConnection.getInputStream();
                         BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
                         String line = null;
                         while ((line = br.readLine()) != null) {
                               dateText.setText(line);
                         }
                        br.close();
                       }
           } catch (Exception e) {
                    Log.e(“Error fetching data “, e.getMessage());
            }

When you run this code, you will get an error logged into to your LogCat as shown below.
You have to add a permission attribute in the Android Manifest file for your application to be able to connect to the internet. Add the following line in AndroidManifest.xml file. 
               <uses-permission android:name=“android.permission.INTERNET”/>

You can play with the manifest file using the design wizard instead of manually editing it.
So all set and done, your app connects to the server resource, loads the data from the server and displays it in the TextView component.

Shortlink

arguments in JavaScript

Ext JS 4 involves calling this.callParent(arguments) from the initComponent method of a view component. For quite some time I was thinking that arguments is a pre-defined variable in Ext JS 4 before I started reading  the book  JavaScript: The Good Parts”.   Very interesting book for those who want to start taking JavaScript as a serious programming language. 
arguments is  a built-in parameter available in a function in JavaScript. It’s an array that is used to access the parameter list of the function, which basically says you don’t really have to formally declare arguments for a function, but still access the values passed, using the ‘arguments’.
Say you have a method to concatenate all the values passed to a method in JavaScript. You can write it like below: 

function concat(){
   var result = “”; 
   for(var i=0;i<arguments.length;i++){
        result += arguments[i] + ” “;
   }
   return result;
}
document.write(concat(“This”,”is”,”cool”)); //Output is This is cool

You can see that arguments is a built-in array parameter that can be used to access the parameters passed when the function is invoked. In case you want to avoid concatenating anything other than a string, reflection can be tossed in.

  if(typeof arguments[i] == ‘string’)
       result += arguments[i] + ” “;
But what is strange is that the ‘arguments’ is really not an Array instance in the true sense. It doesn’t have methods like slice, push, pop associated with the Array class. So need to be a bit careful while using ‘arguments’.

Shortlink

extraParams in Ext JS 4

A Store instance in Ext JS4 uses a Proxy object to connect to the server. If you want to pass parameters to the proxy dynamically you can make use of the extraParams property. Let’s discuss a simple example to see the use of extraParams property.
Let’s say you have two list boxes ‘country’ and ‘city’. Based on the value selected from the country list box, the city list box has to be populated. The city list will be loaded from the server, through a cityStore that we have configured. When the country value changes you will pass the country as a parameter to the cityStore and load the cities in the listbox.
The code for the cityStore is given below.

var cityStore = Ext.create(“Ext.data.Store”,{
fields : [“name”],
autoLoad : false,
proxy : {
type : “ajax”,
url : “citiesServlet”,
reader : {  type : “json”}
}
}});
The cityStore is populated by sending a request to a ‘citiesServlet’. The city combo box can be mapped to the cityStore. The country and city combo boxes are declared as shown below.

                                           {
           xtype : “combo”,
        displayField : “name”,
        fieldLabel : “Country”,
        store : {
        fields : [“name”],
        data : [
                {name:”India”},{name:”UK”},{name:”USA”}
              ]
        },
          listeners : {
        change : function(source,newValue,oldValue){
        cityStore.proxy.extraParams = {“country” : newValue};
        cityStore.load();
        },
        }
        },
        {
        xtype : “combo”,
        store : cityStore,
        displayField : “name”,
        fieldLabel : “City”
        }

 You can notice that in the change event listener of the country combo box , the selected value  is passed as a parameter to the cityStore’s proxy object using the extraParams property and load method is invoked. Since the cityStore is mapped to the city combo box, the combo box gets automatically populated with the data fetched from the server.