EGIT – GIT in action within your Eclipse IDE

This article presents two simple steps to place your eclipse workspace under GIT. EGIT is a plugin that allows you to use GIT directly within the Eclipse IDE.

Step1: Installation of EGIT

Navigate to Help  –> Install New Software

Step1help

 

Type the URL from which the EGIT could be downloaded. Then, click select all and next.

http://download.eclipse.org/releases/indigo/

step3selectallnext

 

Then Deselect All and select only “Eclipse Egit” and click on next.

step3bselecteclipseegit

After installation of EGIT, we need to configure GIT on Eclipse

 

Step2:  Configure your Eclipse project to use GIT

Right click on your project in Eclipse. In the context menu, Choose Team –> Share Project

Step4LocalRepository

 

Then, select GIT in the Share Project menu

Step5SeletGIT

Then enter the name of your project and create a new GIT repository for the project

Step6CreateNewGITrepository

To view your project as a GIT repository within the Eclipse IDE, navigate to Windows –> Show View –> GIT –> GIT Repositories

Step7ShowViewGITReo

Now you can see your project placed under GIT version control and apply all the GIT commands from your Eclipse IDE!

GIT merge conflict – commit your changes or stash them before you can merge

Here are the frequent GIT merge conflict horror stories one might encounter when one pulls the latest code changes or when the project code is rebased. If you are using GIT bash, its quite easy to configure the GIT environment with a visual GUI tool called DiffMerge that helps you clearly see the lines of code causing the conflict and resolve the merge conflict with a “single click”.

Problem:

Merge conflicts while doing git pull
Output 1:

git pull
Enter passphrase for key '/c/Users/arvenkataraman/.ssh/id_rsa':
Auto-merging testSuite/sample.xml
CONFLICT (content): Merge conflict in testSuite/sample.xml
Automatic merge failed; fix conflicts and then commit the result.

Output 2:

git pull --rebase
U       testSuite/sample1.xml
U       testSuite/sample2.xml
U       testSuite/sample3.xml
M       testSuite/sample4.xml
U       testSuite/sample5.xml
U       testSuite/sample6.xml
U       testSuite/sample7.xml
M       testSuite/sample8.xml
M       testSuite/sample9.xml
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm '
as appropriate to mark resolution, or use 'git commit -a'.


Output 3:

git pull
Falling back to patching base and 3-way merge...
Auto-merging testSuite/sample.xml
CONFLICT (content): Merge conflict in testSuite/ sample.xml 
Auto-merging testSuite/sample2.xml
CONFLICT (content): Merge conflict in testSuite/ sample2.xml 
Auto-merging testSuite/sample3.xml
CONFLICT (content): Merge conflict in testSuite/ sample3.xml
Failed to merge in the changes.
Patch failed at 0001 test changes

Solution


Step 1: Download DiffMerge tool

The SourceGear DiffMerge tool could be downloaded from the below location:
http://www.sourcegear.com/diffmerge/downloads.php


Step 2: Configure GIT to use DiffMerge tool

Open GIT Bash and navigate to the GIT repository. Then give the below commands to configure GIT with the downloaded DiffMerge tool

git config --global merge.tool diffmerge
git config --global mergetool.diffmerge.cmd "C:/\"Program Files\"/\"SourceGear\"/Common/DiffMerge/sgdm.exe --merge --result=\$MERGED \$LOCAL \$BASE \$REMOTE"
git config --global mergetool.diffmerge.trustExitCode true


Step 3: Invoke DiffMerge from GIT bash

 


If the git pull command doesn’t succeed due to merge conflict, please give the below command:

git difftool

The DiffMerge opens up as below with automatically selected merge conflict files for comparison
Step1mid2selectfiles

Step 4: Shift the highlighted piece of code to resolve the merge conflict

On the top of the DiffMerge tool there is an arrow to apply changes from the right to left:
step2 DiffMerge for merge conflict
The files are displayed side-by-side for comparision and the differential piece of code to be merged is highlighted in violet color:
step3 Merge changes
Select the piece of code highlighted and click on the “apply changes from the right” arrow at the top. After merge the code will look like below:
step4 After merge

Similarly we could resolve all the merge conflicts with a single click. It is a lot more easier since this is a visual tool for merge.

Code debugging with watch variables/expression using Eclipse IDE

Here are the steps to do extensive debugging of java code using Eclipse IDE with watch variables, expression and Inspect.

Step1: Enable breakpoint

Set the breakpoint at the line of code or point of method entry from where you would like to start debugging the code. Right click on the left margin of the editor next to the line of code and a context menu pops up. Select toggle breakpoint in the context menu as shown below:

Figure1: Toggle Breakpoint

Step1-enableBreakpoint

 

Step2: Configure the breakpoint to stop execution

To start debugging, the execution should stop at the breakpoint specified. For this click on breakpoint properties (refer Figure1)  and do the following:

  1. Check Hit count
  2. Specify value as 1
  3. Select “Suspend thread” option

This will stop the execution when the program hits the breakpoint.

Step3setBreakpint

 

Step3: Switch to debug perspective

In Eclipse, select Window –>Open Perspective –> Debug as shown below:

Step4 switch to debug perspective

 

Step4: Run in debug mode

Now run the program in debug mode. Select Run –> Debug

Step5 Run in debug mode

Now the program starts running in debug mode and you would see the state of the thread as “running”

Step6 running thread

When the program hits the breakpoint the state of the thread changes from “running” to “suspended

Step7 suspend thread

 

Step5: Debugging the code with Expressions \Watch variables \ Inspect

Now the code stops at the breakpoint. You could use the watch variables / expression to monitor the current value of the debug variable.

Suppose you set the breakpoint at the variable named “counter” and the program stopped at counter variable as shown below:

step8 stops at code\

Add the expression with the variable name “counter” which allows you to monitor the value of the variable as you execute the program:

Step11 watch variableexpressions

You could also right click on the counter variable and select “Inspect” from the context menu

Step12 right click to inspectstepinto

If it is a method then, select the method name and click on “Step Into Selection“. This will allow you to monitor or debug the method execution line by line.

 

Step6: Use F6 key to step into the method

To “step into” the next executable line of code in the current method, press the “F6 Key”. This will pass the program control from the current line to the next executable line of code.

Step9 Press F6 key

 

Git – Permission denied (publickey)

This is a very common issue that most users face after installation of GIT.

Extensive troubleshooting of this GIT issue “Git – Permission denied (publickey)” can be done with the below command:

ssh -vT git@github.com

Output:

OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug1: Connecting to github.com [204.232.175.90] port 22.
debug1: Connection established.
debug1: identity file /c/Users/arvenkataraman/.ssh/identity type -1
debug1: identity file /c/Users/arvenkataraman/.ssh/id_rsa type -1
debug1: identity file /c/Users/arvenkataraman/.ssh/id_dsa type 2
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.5p1 Debia
n-6+squeeze1+github9
debug1: match: OpenSSH_5.5p1 Debian-6+squeeze1+github9 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.6
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
The authenticity of host 'github.com (204.232.175.90)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,204.232.175.90' (RSA) to the list of know
n hosts.
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Users/arvenkataraman/.ssh/identity
debug1: Trying private key: /c/Users/arvenkataraman/.ssh/id_rsa
debug1: Offering public key: /c/Users/arvenkataraman/.ssh/id_dsa
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).

 

Solution:

Step 1: Navigate to .ssh directory inside your home directory

         cd ~/.ssh

Step 2: Generate the public/private rsa key pair

         ssh-keygen

Step 3: Copy the SSH key to the clipboard using the below command

         cat id_rsa.pub | clip

Step 4: Navigate to your GIT repository in https://github.com/

Step 5: Go to Account Settings

accountsetting

Step 6: Under Account Setting select SSH keys

ssh

Step 7:  Click on Add SSH key, paste the key copied to the clipboard (in Step 3) and store the key

saveSSH

 

 

Getting started with Ruby on Rails

Video demonstration of ruby on rails application creation:

One of the many advantages of rails is that it immediately gets you from zero to a functional application. To get started lets create a directory for the rails project called “railsproject”.

mkdir railsproject

Now open the ruby command prompt and navigate to the directory that we just created. Run the rails new command to make your first rails application. Let us call our first rails application as “first”. The rails new command is a program that creates a skeleton rails application. It creates a standard file and directory structure that makes it easier than ever to organize and deploy files. All the rails application have a common file and directory structure making it easy to understand someone else’s code.

rails new first

After the file creation is done rails automatically runs the bundle install command which we will discuss later in this article. Upon successful execution of the rails new command, it will display the message “Your bundle is complete!”

Output:

Bundle install command

 

Now lets have a quick look into the files and directories that have just been created. I use Aptana studio, an IDE for windows users of Rails.

Rails application directory structure

 

Let’s learn more about the files that have been created.

  • app – This contains the Core application code including the models, views, controllers and helpers. The model, view and controller are very important parts of a rails architecture which we would learn in-depth in the later articles
  • script/rails -A script to generate code and start the local server
  • vendor – This contains third party code such as plugins and gems
  • Gemfile – This file contains the gem requirements of the application

The bundle install or the bundler command which we had seen in the beginning of this article installs the gems from the Gemfile. The bundler looks for the gems that needs to be installed from this file. Thus the Gemfil should contain the gems needed by your application.

Gemfile:

source 'https://rubygems.org'
 
gem 'rails', '3.2.8'
 
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
 
gem 'sqlite3'
 
# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
 
  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platforms => :ruby
 
  gem 'uglifier', '>= 1.0.3'
end
 
gem 'jquery-rails'
 
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
 
# To use Jbuilder templates for JSON
# gem 'jbuilder'
 
# Use unicorn as the app server
# gem 'unicorn'
 
# Deploy with Capistrano
# gem 'capistrano'
 
# To use debugger
# gem 'debugger'

Inside the gemfile, the rails gem is the gem for rails itself. “sqlite3″ is the gem for the ruby interface to the SQLite database. ”jquery-rails”  is for the jQuery javascript library. As you could notice there is a version 3.2.8 specified in the rails gem command. Unless the version is explicitly specified, rails automatically deploys the latest version of that gem.

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

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