Inheritance – the Ace of the Object Oriented Programming world

The code is just a junkyard if it is not designed for reuse. Re-usability is very simple if you understand inheritance, a very powerful principle of object oriented programming. For this reason I call inheritance the Ace of the object-oriented programming world.

Here, I explain inheritance with a simple illustration. From the figure below can you list the properties that are common to all the balloons?

 

The below properties are common to every balloon:

  1. Color
  2. Size
  3. Price and so on

These properties that are common to all classes of a given type say balloon is stored in a class called the base class or super class or parent class. Inheritance is a powerful object oriented programming feature that allows a class to reuse the properties and methods of an already existing class while adding its own functionality. It’s the process of creating a new class as an extension of an existing class primarily to enhance the code re-usability. The class that extends is called the derived / sub class and the class getting extended is called the super / base class.

Suppose there is a super class called superBalloon. There are different kinds of balloons such as birthday balloons, balloons that represent a theme like sports or Disneyland and so on. For class inheritance java uses the keyword extends. Now let’s write a small java program for the base class “superBalloon”.

 

package balloonInherit;
 
public class superBalloon
{
	/**
	 * The superBalloon class defines methods and variables common to all balloons such as
	 * size, color and price
	 */
	//commonly used fields in all balloons
	public int size;
        public String color;
	public double price;
	public int number_of_balloons_purchased;
	public double total_cost;
 
	public void purchase(double price, int number_of_balloons_purchased)
	{
		total_cost = (price * number_of_balloons_purchased);
	}
}

A derived class is more specific and can have additional functionality of its own apart from that of the base class. Thus a birthday balloon is a specialized version of the balloon class having a new field called decoration cost specific to it’s type to better suit the needs.

We can also override /replace the behavior of the base class in the derived class. Here, in the below example the birthday balloon inherits the superBalloon class and defines a new field called decoration cost specific to it’s kind. We use the super keyword to reuse the already existing properties of the base class.

package balloonInherit;
 
public class subPartyBalloon extends superBalloon
{
	/**
	 * Since this is a partyBalloon, an additional new field called decoration cost is added
	 * which is specific to this kind of balloon
	 */
 
	public static void main(String args[])
	{
		//Create an object for subPartyBalloon class and invoke the purchase method
                subPartyBalloon bDayBalloon = new subPartyBalloon();
		bDayBalloon.purchase();
	}
 
	public void purchase()
	{
		//Additional property specific to the type partyBalloon
		double decoration_cost = 2.00;
 
		//Reuse the existing properties of the base class using super keyword
		super.size = 20;
		super.number_of_balloons_purchased = 3;
		super.color = "red";
 
		//These are the prices of the balloon depending on it's size
		switch (super.size)
		{
			case 10:
				super.price = 5.00;
				break;
			case 20:
				super.price = 10.00;
				break;
			case 30:
				super.price = 15.00;
				break;
			default:
				System.out.println("Invalid size");
		}
 
		//Invoke the the purchase methods of the super class to calculate the base_cost
		super.purchase(price,number_of_balloons_purchased);
 
		//Since it is a birthday party balloon the additional cost for decoration is added
		total_cost = total_cost + decoration_cost;
 
		System.out.format("The total cost of %d %s birthday balloons is %.2f", number_of_balloons_purchased,color,total_cost);
	}
}

The switch-case control structure decides the price of the balloon based on the input size. Once a matching size is found it assigns value to the price variable and breaks the execution of the switch-case block. The total cost of the birthday balloons is calculated and the output is as below.

OUTPUT:

The total cost of 3 red birthday balloons is 32.00

Now let’s create a java program for another derived class called subThemeBalloon. A theme based balloon has theme and design as additional fields specific to it’s kind. For example to represent the theme of Disneyland, a balloon is designed with the theme Disneyland and with the shape Mickey mouse.

The subThemeBalloon class reuses the existing properties of the base class superBalloon using the super keyword. It also has three additional new fields viz. theme, design and decoration cost specific to it’s kind to better suit the needs.

package balloonInherit;
 
public class subThemeBalloon extends superBalloon
{
	/**
	 * A theme based balloon has theme and design as additional fields. For example to represent
	 * the theme of Disneyland a balloon is designed with the theme Disneyland and with
	 * the shape mickey mouse
	 **/
 
	public static void main(String[] args)
	{
                //Create an object of subThemeBalloon class and invoke the purchase method
                subThemeBalloon themeBalloon = new subThemeBalloon();
		themeBalloon.purchase();
	}
 
	public void purchase()
	{
		//Declare three additional properties that are specific to the type themeBalloon
		String theme = "Disneyland";
		String design = "Mickey Mouse";
		int decoration_cost = 5;
 
		//Reuse the existing properties of the base class using super keyword
		super.number_of_balloons_purchased = 20;
		super.price = 15.00;
 
		//Invoke the purchase method of the base balloon class to calculate base cost using super keyword
		super.purchase(price, number_of_balloons_purchased);
 
		//Add the decoration cost for the balloon
		total_cost = total_cost + decoration_cost;
 
		//Print the total cost of the balloon
		System.out.format("The total cost of a %s %s balloon is %.2f", theme, design, total_cost);
	}
}

OUTPUT:

The total cost of a Disneyland Mickey Mouse balloon is 305.00

 

This is all about inheritance. Feel free to post any comments /questions.

Hosting rails application on heroku

Signup for a Heroku account at https://api.heroku.com/signup

Then install heroku gem with the below command:

sudo gem install heroku

Remove ruby 1.9.2, install zlib and openssl package and then re-install ruby as follows:

rvm remove 1.9.2
rvm package install zlib
rvm package install openssl
rvm install 1.9.2 -C --with-zlib-dir=$HOME/.rvm/usr --with-openssl-dir=$HOME/.rvm/usr
rvm --default use 1.9.2@rails3tutorial

Install and compile readline with the below commands:

sudo apt-get install libncurses5-dev
sudo apt-get install libreadline5-dev
cd ~/.rvm/src/ruby-1.9.2-p180/ext/readline/
ruby extconf.rb
make
make install

Associate your Heroku account with the public key.

heroku keys:add

Use create command to create a heroku subdomain for the app:

heroku create

Using git to push the application to the heroku server:

git push heroku master

The open command opens up the url in a new browser window.

heroku open

RVM – Easy installation of ‘ruby on rails’ on ubuntu

Ruby Version Manager (RVM) resolves versions conflicts when multiple versions of ruby is installed on the same system. It also enables quick and easy installation of ruby on rails on ubuntu. This article provides solution to the problems faced during the installation of ruby on rails on ubuntu using RVM.

Installation of RVM:

bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)
source ~/.rvm/scripts/rvm
rvm reload

Install Ruby 1.9.2 with rvm:

rvm package install zlib
rvm install 1.9.2 -C --with-zlib-dir=$rvm_path/usr
rvm install 1.8.7-p174 -C –with-zlib-dir=$rvm_path/usr

To resolve version conflict, create separate gemsets for each of the two different versions:

rvm --create 1.8.7-p174@rails2tutorial
rvm --create use 1.9.2@rails3tutorial

To use Ruby 1.9.2 by default and Rails 3.0 give the below command:

rvm --default use 1.9.2@rails3tutorial

Install Rails:

gem install --no-ri --no-rdoc --version=3.0.1 rails

Confirm installation with the below command. This command will display the version of rails installed on the system.

rails -v

Install RubyGems:
Installation of rvm automatically installs RubyGems
Give the below command to confirm this. This command would display the path in which the gem has been installed.

which gem

Update the system to the latest version with the below command:

gem update –system

Linux shell scripting using GNOME-Shell

Shell Scripting for beginners Part1 covered the execution of a Shell Script on WINDOWS platform with a comprehensive illustration. In this article let us practice shell scripting on LINUX platform. This is done using GNOME-shell for scripting and vim editor for modification and saving of shell scripts.

Open the terminal:  Go to Applications → Accessories → Terminal


Pre-requisite: Installation of GNOME-shell

COMMAND:

sudo apt-get install gnome-shell

OUTPUT: It takes a few seconds

[sudo] password for dell:

Reading package lists… Done

Building dependency tree…………..

After this install the vim editor using the command

sudo apt-get install vim


Creation and execution of a simple Shell Script

Let us start by creating a directory called shellscripts using mkdir command and start working there

Navigate to home directory using cd ~ command

cd ~
mkdir shellscripts
cd shellscripts

Now we are inside the shellscripts directory. Now create a new shell script called test.sh using the command:

vim test.sh

After giving vim command it creates a new file called test.sh. Press “INSERT” key to start scripting. The shell script starts with a “shabang”. In this program we display the username using $USER variable and echo command as below:

#!/bin/sh
clear
echo "Hello, $USER."

The screen should look as below:

Now save the file using ESC+w+q+! command

Grant permissions for execution of test.sh using the chmod command as below:

chmod +x test.sh

Execute the shell script using:

./test.sh

The output is as below:

Shell Scripting for beginners with a simple example Part 1

This article gives a practical exposure to beginners about shell scripting on UNIX platform. Shell script is a script for the shell command-line interpreter. Shell programming is fun and is used to automate highly repetitive time-consuming manual tasks like environment setup, post processing and configuration value changes that involve file manipulation. We can run shell scripts by installing Cygwin and use Emacs as the editor.

We point to the interpreter (i.e) the shell in the very first line of the script. This is called shebang. #! bin/sh is the default shebang if nothing is mentioned.

Writing a simple Shell Script:

Step1:  In the shell command prompt, navigate to your home directory

sh-3.2$ cd $HOME

cd means change directory. $HOME variable refers to a directory on the operating system containing the user’s files. It can be represented in short using ~ symbol.

Step2:  In the home directory create a new file named date.sh

Step3: Modify the access rights on the file so that you can edit/save it using chmod command.

sh-3.2$ chmod 777 date.sh

Everyone has read, write and execute permissions on the file

sh-3.2$ chmod 755 date.sh

Everyone can read and execute this file but I alone should be able to modify it.

Step 4: Now let us create a simple shell script to display the date and hostname.

We store the hostname value in a variable called HOST. We use the date function to display date in the format %m-%d%-%Y. And echo command is used for displaying/printing the output on the command line.

#! /bin/sh

HOST=$(hostname)

echo “——————————————————————-”

echo “Date:$(date +”%m-%d-%Y”)              Hostname:$HOST

echo “——————————————————————-”

Step 5: Run this shell script using the command ./date.sh from the home directory where you saved it.

OUTPUT:

sh-3.2$ ./date.sh

——————————————————————-

Date:12-14-2010              Hostname:dellwin7-PC

——————————————————————-

Key paradigm shift from objects to contracts in the Service-Oriented world

There has been a key paradigm shift from object to contract as the building block for a distributed system in the service-oriented world. Contracts are the new building blocks if we need to develop a long lasting distributed system. How focusing on contracts can improve the business objectives and make partners happier is the least understood aspect of web services which i am going to explain in this article.

There are two common  techniques to develop a web service:

  1. Code-first
  2. Contract-first

Most developers start by writing the service implementation in code and then have a toolkit to produce the WSDL. This approach is called code-first development. Code-first is more common today. This is because working directly with WSDL is extremely difficult. We lack proper tool support to work directly with WSDL and hence code-first is more pleasant. In this technique the developer first codes the logic of how the data is treated within his service. Then he produces the WSDL in an automated way using a toolkit. The WSDL thus produced contains language-specific types. When the business partner wants to interact with the service contract, he realizes that his application doesn’t map nicely to the service contract coded by the developer as it contains language-specific types and he starts looking elsewhere for the service. The key principle of Service Oriented Architecture is to ensure ease-to-consume a contract. The Code-first approach is technology independent and lacks ease-of use.

The fundamental goal of the Contract-first model is to facilitate interoperability. The reach of a web service is unlimited. Embracing this new model of contract-first ensures happier partners. In this approach, the developer first codes the standard contracts that will be shared with the partners. Here the developer focuses on how the data is moved across service boundaries rather than within the service. He invests a lot of time and energy in contract design. He first codes the XML Schema and WSDL definitions. After everyone agrees on WSDL he implements the code. This approach embraces service orientation and is disconnected from how you treat data within a service. It is focused on connecting the dots within a distributed system as a whole. Ease-of use of the service is under the control of contract definition. The Contract definition is a shared language which is the primary focus of this model. This approach ensures that the service designed is interoperable across a wide range of platforms, operating systems and programming languages. It helps partner collaboration and meets the enterprise goals.

Top down vs bottom up SOA

This article compares the two approaches of web services development - top-down and bottom-up - as the battle between the purist versus the pragmatist, the value generator versus the cost saver and the Business Evangelist vs IT implementer.

Web services can be created using two methods: top-down development and bottom-up development. Top-down web services development involves creating a web service from a WSDL file. By creating the WSDL file first you will ultimately have more control over the web service. When creating a web service using a top-down approach, first you design the implementation of the web service by creating a WSDL file.When creating a web service using a bottom-up approach, first you create a Java bean or EJB bean and then use the web services wizard to create the WSDL file and Web service.

appraoch

Should a top-down business-centric approach or a bottom-up approach be employed given that the Business Unit (BU) is more reactive and sensitive to the realities of IT?

The Model-Driven Architecture (MDA) provides an approach aimed at achieving technology independency through full top-down development. In top-down approach the WSDL is designed from a business point of view and is not driven by a service consumer or an existing application. The “WSDL to Java” tool generates java code according to JAX-RPC or JAX-WS. These classes can then adapt the existing business logic.

Although bottom-up Web service development may be faster and easier, especially if you are new to Web services, the top-down approach is the recommended way of creating a Web service. The bottom up approach generates web services for which the design is driven from an application point of view (developer driven) and will not address the need for other consumers.

Three Schema Design Approaches

In a project where multiple schemas are created it is critical to decide which namespace design approach is suitable for the project: (1)should we give each schema a different targetNamespace, (2)should we give all the schemas the same targetNamespace or (3)should some of the schemas have no targetNamespace. To make this critical design decision, let me illustrate the three schema design approaches in this article.

Heterogeneous Namespace Design

1. Give each schema a different targetNamespace
2. If required to re-use another schema in the current schema we need to import it

Benefits
1. Maximise the re-use of the types with separate namespaces
2. Namespace mapped to domain specific service
3. It would be easier to model all the domain-specific types in separate files with individual namespaces
4. Easier to understand
Drawbacks
1. There will be a large number of namespaces to manage
2. There will be a large number of namespaces to import
3. The granularity of the types in import would depend on the types defined and exposed in a particular domain-specific XSD

Homogenous Namespace Design

1. Give all schemas the same targetNamespace
2. As the schemas have the same targetNamespace, the method of accessing components is “include”.

Benefits
1. No need to either import a service or schemas
Drawbacks
1. Need to handle Name collisions
2. Generate code in a single Java package, for a service
3. chances for redundant types
4. does not allow for domain-specific namespaces

Chameleon Namespace Design

Give the main schema a targetNamespace and give no targetNamespace to the supporting schemas. The no-namespace schemas will take-on the targetNamepspace of the main schema.

Benefits
1. In this scheme, schemas are able to blend in with the main schemas that use them
2. Ability to provide application-specific namespace to the schema
Drawbacks
If the schema <include>s multiple no-namespace schemas then there will be a chance of name collisions. In fact, the schema may end up not being able to use some of the no-namespace schemas because their use results in name collisions with other Chameleon components

The most widely used schema design approach is heterogeneous schema design approach. Let me illustrate this with an example.

Step1: Create a schema file named Books.xsd

<!-- to store book information with targetNamespace declared as tns:Books-->
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="tns:Books"
            elementFormDefault="unqualified">
    <xsd:complexType name="Book">
        <xsd:sequence>
           <xsd:element name="Author" type="xsd:string"/>
           <xsd:element name="Title" type="xsd:string"/>
           <xsd:element name="Price" type="xsd:double"/>
           <xsd:element name="Quantity" type="xsd:integer"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

Step2: Create another schema file Sales.xsd

<!-- to store the sales information with targetNamespace declared as tns:Sales-->
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="tns:Sales"
            elementFormDefault="unqualified">
    <xsd:complexType name="Sales">
        <xsd:sequence>
             <xsd:element name="Customer" type="xsd:string"/>
             <xsd:element name="Region" type="xsd:string"/>
             <xsd:element name="TransactionStatus" type="xsd:string"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

Step3: Import the two schema files in Catalog.xsd file

<!--using the Heterogeneous namespace design approach-->
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:b="tns:Books" xmlns:s="tns:Sales" xmlns:ns1="tns:Catalog" targetNamespace="tns:Catalog" elementFormDefault="unqualified">
	<xsd:import namespace="tns:Books" schemaLocation="Books.xsd"/>
	<xsd:import namespace="tns:Sales" schemaLocation="Sales.xsd"/>
	<xsd:element name="Catalog">
		<xsd:complexType>
			<xsd:sequence>
				<xsd:element name="Payment">
					<xsd:complexType>
						<xsd:sequence>
							<xsd:element name="CustomerID" type="xsd:integer"></xsd:element>
							<xsd:element name="PaymentType" type="xsd:string"></xsd:element>
							<xsd:element name="Currency" type="xsd:string"></xsd:element>
							<xsd:element name="ShippingAddress" type="xsd:string"></xsd:element>
						</xsd:sequence>
					</xsd:complexType>
				</xsd:element>
				<xsd:element name="Book" type="b:Book" maxOccurs="unbounded"/>
				<xsd:element name="Sales" type="s:Sales" maxOccurs="unbounded"/>
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>
</xsd:schema>

Introduction to XML Web Services

Web services take web applications to the next level. By using Web services, your application can publish its function or message to the rest of the world. With web services, your accounting department’s Win 2k server’s billing system can connect with your IT supplier’s UNIX server.Web services can offer application-components like: currency conversion, weather reports, or even language translation as services. There are things applications need very often. So why make these over and over again?

Web services are units of programmable application logic located on web servers that can be accessed remotely using standard internet protocols and data formats such as XML, HTTP and SOAP.

Web services are platform-independent and language-independent, since they use standard XML languages. This means that my client program can be programmed in C++ and running under Windows, while the Web Service is programmed in Java and running under Linux.

Web Services are published, found, and used through the Web. The basic Web services platform is XML + HTTP.

WSstandards

Web services platform elements are:

  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)

XML Web Services in 5 Days

XML in 5 Days - A Hands On Approach

Introduction to XML

XML is the universal format for data interchange.  It is supported by all major operating systems, programming languages and development platforms.  It is the standard platform for building interoperable distributed applications. 

The ability to invoke cross platform communications makes the reach of XML Technology unlimited and its use in Web Services compelling.

Web Services are the building blocks for constructing distributed Web-based applications. They are units of programmable application logic located on web servers that can be accessed remotely using standard internet protocols and data formats such as XML, HTTP and SOAP. Web services use XML-based messaging to send and receive data, which enables heterogeneous applications to interoperate with each other.

Basic concepts of XML

 XML represents structured content rather than visual display. A well-formed XML document contains an end tag for every begin tag. Well-formed XML documents can be modeled as trees. The tree has a single root node containing one or more child nodes. A node without a child is called leaf node. XML Document Object Model (XML DOM) is required to work with XML data.

Document Object Model (DOM) 

Document Object Model (DOM) is a representation of the XML document in memory.  It is used to read, write, and manipulate an XML document. DOM loads the entire XML document into memory.

Simple API for XML (SAX) 

Simple API for XML (SAX) is used to read data from XML documents. SAX parser reads the contents sequentially and generates events as it reads the XML document.  It does not load the entire XML document into memory. SAX is good for reading large XML Documents.

Limitations of SAX:  SAX does not maintain any data structures that are required to perform complex searches. They cannot be used to modify the XML document.

Document Type Definition (DTD)

Document Type Definitions (DTD) outlines elements, attributes & relationships allowed in an XML document. DTDs are written in their own syntax rather than XML syntax.

XML Schema Document (XSD)

XML Schema Documents describe and validate the structure of XML documents.  They restrict the value of elements and attributes in an XML document. They are written in XML syntax. An XML document that adheres to XML schema is called Valid XML document. The XML Schema documents have suffix xsd.