codedecoder

breaking into the unknown…


1 Comment

sending email in rails

Sending email in rails is mange by ActionMailer::Base. The detail of this class is available here. I will show you here to send a simple welcome email. You can read it in more detail here at rubyonrail.org

STEP 1: configuring the mailer in your environment file

First we need to tell our application to handle email request. The basic configuration in your development environment related to action_mailer should look like this

  config.action_mailer.default_url_options = {:host => 'localhost:3000'} 
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.perform_deliveries = true # If set to false, mail will be not delivered in 
  reality, but you can see it in the terminal logs. In development it is false by default, but I 
  suggest to make it true even in development as you can check it directly in your mail box. 
  For testing if you do not want to use a real email id, you can create dummy email 
  on http://www.yopmail.com/en/
  config.action_mailer.raise_delivery_errors = true # it will show error while delivering the mail. 
  generally people keep it false in production environment
  config.action_mailer.default :charset => "utf-8"

  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    domain: "example.com",
    authentication: "plain",
    enable_starttls_auto: true,
    user_name: "arunprojects@gmail.com", # this should be a real gmail id
    password: "my_password" # this should be real password of your gmail id
  }

NOTE :
1->If you do not use real gmail id and password in above setting it will throw NET:SMTP authentication error
2->I have used google smtp setting i,e the mail will be delivered by gmail smtp server. There is other smtp service provider also like mandrill . I will discuss there smtp setting in some other post

STEP 2: generating the mailer

As , you generate controller for your application, you can also generate the mailer, which in turn will create some files and folder for you. The mailer class is exactly same as controller, where each action have its associated view and all instance variable in a action is available in the corresponding views also. The only difference is that, you do not write routes for the mailer action

$ rails generate mailer UserMailer # Iam assuming you are using rails3 or above, 
for earlier version use the corresponding command. for example  
ruby/script generate mailer UserMailer for rails2.3.5
create  app/mailers/user_mailer.rb
invoke  erb
create    app/views/user_mailer
invoke  rspec
create    spec/mailers/user_mailer_spec.rb

So, You can see that , it has created user_mailer.rb file and user_mailer folder for you

STEP 3: Defining mailer action

We are assuming that, a user get created in our system with dummy password and we need to send a email to him on his account creation with his username and password. Let we call this mailer action as welcome_email. The code of user_mailer.rb will look like this

class UserMailer < ActionMailer::Base   
  default :from => "no_reply@gmail.com" # if from is not specified it will be set as from.
  def welcome_email(user_info)
    email = user_info[:mail]
    @username = user_info[:username]
    @password = user_info[:temp_password]
    @url  = new_user_session_url
    mail(:to => email, :subject => "Your Login credential")
  end
end

NOTE :
see how we have created the @url object to which user will be redirected from his email. Here, you should use new_user_session_url instead of new_user_session_path. This is because, user email do not have any context to your application so realtive path will not work, you need to specify the absolute path. the url generated by the two is as below

new_user_session_url -> http://localhost:3000/users/sign_in # absoulte path generated with _url suffix. the localhost:3000 coming from your setting in step1
new_user_session_path -> /users/sign_in # relative path generated with _path suffix

STEP 4: generating the mailer view

In the view we will define how our email will look to the user. . Create a erb file with the same name as our mailer action in app/views/user_mailer . So our, mailer view will be welcome_email.erb. The content of this file is simple html as shown below

Welcome to my_finance.com

You have successfully signed up with MyFinance Your login credential is as below :

username: <%= @username %> 
password: <%= @password %> 

To login to the site, just follow this link: <%=link_to @url, @url %> 

Thanks for joining and have a great day!

Note :

The view above is simple text. You can wrap it in html structure as in a normal view file i,e wraped in <head>, <body> etc. .

STEP 5: delivering the email

Now, we come to the last step i,e triggering the email. You can trigger any mailer action anywhere with below syntax

Mailer_class_name.action_name.deliver # This syntax is for rails3 and above

Mailer_class.deliver_action_name # This syntax is for rails version before 3

Example : In our case It will become

UserMailer.welcome_email(@user_info).deliver # It will not throw any exception

UserMailer.welcome_email(@user_info).deliver! # the ! make the deference i,e it will throw exception if anything goes wrong. use this form if want to handle the exception in begin end block. You can read more on exception handling here.

UserMailer.deliver_welcome_email(@user_info) # for rails version older than 3

A sample controller action triggering this email on user creation is as below

class UsersController < ApplicationController 
  def new 
    @user = User.new() 
  end 

  def create 
    @user = User.new() 
    @user = params[:user] 
    if @user.save 
      user_info = {:mail => @user.email, :username => @user.username, 
      :temp_password => @user.temp_password } # we are creating hash of information 
      which we need to pass to our welcome_email method
      UserMailer.welcome_email(user_info).deliver #this will deliver the mail
    else
     render new
     flash[:notice] = "User failed to create"
    end
  end
end

Restart your server, create a user. Go to the user email. You can find the welcome message there in the inbox. If not there check the spam folder also. Well….I hope you got the email ūüôā

Advertisements


10 Comments

requested resource (/openam/json/users/) is not available

I am experimenting out with openam (installation discussed here ) as solution to my single sign on ( SSO ) need when I got below error while making API call to its REST services. The detail of all its REST services is available here .

The requested resource (/openam/json/users/) is not available

This is very strange as I am making the calls exactly as specified in there documentation here . Some of the base URL they have mentioned as example  is as below.

https://openam.example.com:8443/openam/json/users/?_action=create # for creating users
https://openam.example.com:8443/openam/json/users/bjensen # for updating user called bjensen

The documentation, expect json data in the payload

So, I’ am doing everything right, but strangely error keep occurring. From, the error itself I can figure out that the problem is with the REST API url they have documented i,e the URL itself is not valid. But, now what I can do. May, be Iam using older version of openam. But it is not the case as I have downloaded and installed the latest version 10.1.3 .

Pulling, my hair for hours, before deciding to use there older API available here .

Strangely, It worked. It specified the REST url as below

https://openam.example.com:8443/openam/identity/create # for user creation

https://openam.example.com:8443/openam/identity/update # for user updation

https://openam.example.com:8443/openam/identity/delete # for user deletion

SOLUTION : Use the old REST API of openam instead of current one. The legacy API is documented here . I think, they have released the documentation before releasing the version which support it. So use the older API and it will work fine.


1 Comment

Installing openam on ubuntu

OpenAM provides open source Authentication, Authorization, Entitlement and Federation software. You can setup it to provide single sign on ( SSO ) for your different website. For example, say you are a banking organization having different sites for catering different vertical of your business (insurance, loans, deposits etc). Now, your user is same for all these sites, so no need to maintain separate user database for them. It can be manage by openam. You can create, update, delete and validate users of all your site with openam.

With, the short introduction of openam above, we will now proceed to install it on our ubuntu system. Detail installation instruction is available here.

STEP 1: Prerequisite

-> create fqdn for your system

fqdn is fully qualified domain name. You can read more on fqdn here on wiki. In simple word I can say that, You system should be accessible from browser. For your local system localhost(127.0.01) is fqdn. when you do localhost in browser it load a page with message “Its working”. Since, we are experimenting with openam in local, If localhost in your browser give “Its working” message, you are ready to proceed to next step

-> Install java # I will write a blog on this soon. For , now manage it yourself¬† ūüôā

-> Installing Application Server

A no of application server is available which work with openam. We will go with tomcat.  You can find detail instruction on tomcat installation in this post.

STEP 2: Downloading openam

You can download latest stable version from here.  extract the downloaded folder. The extracted folder have name like openam_10.1.3, where 10.1.3 is the version number. remove the version number i,e rename to just call it openam. If you do not, in url you have to type openam_10.1.3  instead of openam.

STEP  3: Put openam in tomcat container.

Copy the openam folder of step 2 into /var/lib/tomcat7/webapps/

STEP 4: configuration change

openam will try to use usr/share/tomcat folder, So we must grant all access to this folder. So, run below command on the terminal

$ chmod 777 -R /usr/share/tomcat7 # this will give all permission to this directory

STEP 5: Running openam in browser

Assuming, you have installed tomcat as described here, and is running at port 8080. go to the browser and type below url.

http://localhost:8080/openam . It will take you to the basic configuration page http://localhost:8080/openam/config/options.htm , as you have yet not set username and password. It will give you two options : basic configuration and custom configuration . We will go with basic configuration to create a password and will do advance custom configuration from openam UI itself later on when needed. So , click on Default Configuration. Fill in your password and submit on successful password creation, you will be taken to the login page. Note that, you have only set password no username. It’s O.K as for default configuration the username is always amadmin. You can Login with below credential

username : amadmin

password: your_password.

Great…..You are loged in to openam, up and running.¬† Make configuration and other settings as per your need.


Leave a comment

browser not laoding any wab page

Recently, I get into strange problem, none of the browser I have on my ubuntu system: – firefox, chrome, internet explorer loading any of the web page, not even google.com get loaded. I tried to ping google from terminal but still no result. This problem generally occur if your internet conection is down. But my internet is up as I can see the connection icon up there on Right hand side of my system, Infact I can login to skype and chat with my friends. So, No doubt the problem is not with the Internet connection. Then what the hell going on here…..???

I uninstalled and installed back firefox, but issue remain same. Looking back, I realised that, everything is working when I left the office in night, so it must have to do something with VPN connection I was using last night, may be it is the culprit. Finally, I got the solution by googling for hours

SOLUTION: delete etc/resolv.conf file and create it back. restarting the browser will solve the problem

You better backup the file before deleting it as you may need to see  it back if someone has made some custom change to this and want you to restore the things back.

arun@arun-yadav:~$ sudo su – # you need to be root user to edit file in etc
[sudo] password for arun: #your password
root@arun-yadav:~# cd /etc/ # moved to etc folder
root@arun-yadav:/etc# cat resolv.conf # let us see the content of this file
search my_finance.com
nameserver 10.1.5.169
root@arun-yadav:/etc# rm resolv.conf # delete the file
root@arun-yadav:/etc# touch resolv.conf # create the file again
root@arun-yadav:/etc# cat resolv.conf # try to see the content after running the browser, it is empty.

Recently, I am on a system with Ubuntu 15.1 . Here resolv.conf is not a normal file but a symlink file pointing to /run/resolvconf/resolv.conf , so unlike older version, here after deleting the /etc/resolv.conf file we need to recreate as symlink pointing to /run/resolvconf/resolv.conf .

root@arun-yadav:/etc# ln -s  /run/resolvconf/resolv.conf resolv.conf

If the problem still exist, check the content of /etc/hosts file. In my case, it look as below.

# BEGIN hosts added by Network Connect
72.28.98.14   sportal.thirdpillar.com
# END hosts added by Network Connect
127.0.0.1       localhost
127.0.1.1       rorexpert

You can see at top that, sportal.thirdpillar.com added by Network connect. It get deleted automatically when you logout of VPN, since you didn’t logged out and shut down the system or the VPN crashed, the above line failed to delete. So delete them, so that it look as below

127.0.0.1       localhost
127.0.1.1       rorexpert

Now restart the network with below command.

sudo /etc/init.d/networking restart

close the browser and start it again. It will work now .

EXPLAINATION OF PROBLEM

PROBLEM : Internet up skype working but browser not laoding any wab page
The content of resolv.conf file is getting added by juniper, which provide VPN(virtual private network) for the financial website Iam working on. When I started juniper and again see the file, I see the both entry again.
root@arun-yadav:/etc# cat resolv.conf
search my_finance.com
nameserver 10.1.5.169

Now, I logout of the juniper and try to see this file again

root@arun-yadav:/etc# cat resolv.conf #it print nothing

I read about resolv.conf file here and try to make some sense of the problem with which I was pulling my hair.I do not know exactly, but can make out below explanation:

when you request a page say google.com,Then name server (often known as DNS) on your system will resolve google.com to its IP address. generally, if nothing specified in resolv.conf file, the nameserver will be assumed to be that of localhost running at port 53. But, if you define it in resolv.conf file,it will be regarded as nameserver for your system, Infact If you give multiple nameserver in resolv.conf file, they will be tried in that order i,e If first nameserver not able to resolve the url into IP, the next nameserver in the list will try. So, you should mention the most reliable nameserver at top.

Below, is my system nameserver before loging in to juniper VPN and after login to it

arun@arun-yadav:~/Projects/third-pillar$ nslookup localhost # not logedin to VPN, so my DNS is at my localhost port 53 i,e 127.0.0.1#53
Server:        127.0.0.1
Address:    127.0.0.1#53

Non-authoritative answer:
Name:    localhost
Address: 127.0.0.1

arun@arun-yadav:~/Projects/third-pillar$ nslookup localhost # loged in to VPN and so DNS get changed
Server:        10.1.5.169
Address:    10.1.5.169#53

Non-authoritative answer:
Name:    localhost
Address: 127.0.0.1

Now above we have seen that, when we start juniper it introduce a nameserver in resolv.conf file and when we logout of it, the entry also get removed. But, last night I switched off the system without loging out of juniper, so the entry get remained there. Now, in morning, when I start to access any web page, it is trying to use DNS of juniper, which will obviously not work as Iam not connected to it, Nor I can connect as juniper url https://my_finance.com/dana/home/index.cgi will itself not get resolved. It resulted in deadlock which get removed only by deleting the etc/resolv.conf file and recreating it.

Anyway….Thank God it get sorted out ūüôā


Leave a comment

attr_reader attr_writer attr_accessor in ruby

To understand this we will create a Model Employee with single field “name“, we will then experiment with its object in rails console

$ rails g model employee name:string
create    db/migrate/20130119195707_create_tests.rb
create    app/models/test.rb

The content of the model and migration file look like this

#model
class Employee < ActiveRecord::Base
end

#migration
class CreateEmployees < ActiveRecord::Migration
  def change
    create_table :employees do |t|
    t.string :name
   end
  end
end

Run the migration

$ rake db:migrate

So now we have a Employee model which map to employees table with a single field name .Now let us experiment out with the employee object in the console.

Note : If you make any change in file, reload the console, before trying out your changes, otherwise it will not reflect

1.9.2-p290 :003 > reload!
Reloading...
=> true

1.9.2-p290 :038 > employee=Employee.new # creating instance i,e object of Employee
=> #<Employee id: nil, name: nil>

1.9.2-p290 :002 > employee.name
=> nil #output is o.k as we have not set any name yet
1.9.2-p290 :003 > employee.name = "Arun"
=> "Arun" # employee name set to Arun
1.9.2-p290 :004 > employee.name
=> "Arun" # employee name is correctly output

Now, let us try to set age of employee

1.9.2-p290 :004 > employee.age = 23
NoMethodError: undefined method `age=' for #<Employee:0x97aac48>

let us try to see age of employee

1.9.2-p290 :004 > employee.age = 23
NoMethodError: undefined method `age' for #<Employee:0x97aac48>

What, is this , why we are not able to see or set age in the same way as we are doing for employee name. You may thought, the error is because we have name filed in employees table but not the age filed.But you see it is not a database error but undefined method `age=’ error. O.k so they are looking for method age= and age, let us define them

class Employee < ActiveRecord::Base
  def age= val
    @age = val # age set to val
  end

  def age
    @age # age is returned i,e read
  end

#let us define some other method to try them in console

#we want secret to be only set on object but no one to read them
  def secret= val
    @secret = val
  end

#we want employee code to be only read from object no one can set it
  def employee_code
    @employee_code
  end
end

Now, let us checkout different operation on console

1.9.2-p290 :038 > employee=Employee.new # creating instance i,e object of Employee
=> #<Employee id: nil, name: nil>
1.9.2-p290 :004 > employee.age=23
=> 23
1.9.2-p290 :005 > employee.age
=> 23
1.9.2-p290 :007 > employee.secret = "xyzw"
=> "xyzw"
1.9.2-p290 :008 > employee.secret
1.9.2-p290 :009 > employee.employee_code
=> nil
1.9.2-p290 :010 > employee.employee_code = 1234
NoMethodError: undefined method `employee_code=' for #<Employee:0x9c7e6ac>

So, we can see that any one can set and read age from the object, but for security reason they can only set secret but can’t read and in case of employee_code they can only read it but not set it.

But, still we can’t see any name method in our model then how it is working and from where it is coming, Actually, ruby do a lot of things for you from behind the scene, It has defined name and name= method internally for you along with a large no of other methods which you are not even aware of….you better know them as it will reduce your line of code. all methods available to any object can be listed by calling methods on it

1.9.2-p290 :011 > employee.methods
=> [:age=, :age, :secret=, :employee_code, :name, :name=, :name_before_type_cast, 
:name?, :name_changed?, :name_change, :name_will_change!, :name_was, :reset_name!
,............so on.......]

So, you can see a no of methods being created for name filed, you can try all of them in console, as for name field these methods are created for all the fields in the corresponding table of a model….great… so what about any attributes which we do not have in table but just want on a object after its creation…well you have attr_reader attr_writer attr_accessor for that.

Let us cut down our model code to three line. This will internally generate all the methods, you have defined above

class Employee < ActiveRecord::Base
  attr_accessor :age   # make age writable and redable
  attr_writer :secret #make secret only writable
  attr_reader :employee_code # make it only readable
end

If you again check in console, you will find your required method there

1.9.2-p290 :011 > employee.methods
=> [:age=, :age, :secret=, :employee_code, :name, :name=, :name_before_type_cast, :name?,  :name_changed?,

:name_change, :name_will_change!, :name_was, :reset_name!,…………so on…….]


2 Comments

devise_confirmable : email not send and Net::SMTPAuthenticationError problem

Devise is a great gem to manage user authentication. You can also implement user confirmation using this i,e a confirmation email will be send when a user registered and he will we able to login only after clicking to that email. By default devise_confirmable module is inactive for devise but you can activate it with few changes. Devise provide different support for user confirmation like triggering email, validating confirmation etc. The detail list of methods is documented here. I will just list here the changes which will make you existing devise authentication to support devise_confirmable. I am assuming that the model you are authenticating with devise is User. I will underline any modification we made to existing code

STEP 1: Add filed required for  devise_confirmable  to user model

If you see Your user migration, you will find different devise introduced fields. many of the field which is not needed by default is commented out. Below is the default migration generated by devise for user

class DeviseCreateUsers < ActiveRecord::Migration   
    def change    
      create_table(:users) do |t|       
      ## Database authenticatable       
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, :default => 0
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at

      ## Token authenticatable
      # t.string :authentication_token

    end

    add_index :users, :email,                :unique => true
    add_index :users, :reset_password_token, :unique => true
    # add_index :users, :confirmation_token,   :unique => true
    # add_index :users, :unlock_token,         :unique => true
    # add_index :users, :authentication_token, :unique => true
  end
end

So you can see that field needed for Confirmable, Lockable and Token authenticatable module of devise is commented out as they are not the default. whenever you want to activate any module you need to add those fields to the users table. You can see that for authenticable module we need 4 more  field and then add index to that. So we will define a new migration and add the required field

class AddAuthenticationTokenToUser < ActiveRecord::Migration   
  class AddConfirmableToUsers < ActiveRecord::Migration   
    # Note: You can't use change, as User.update_all will fail in the down migration   
    def up     
      add_column :users, :confirmation_token, :string     
      add_column :users, :confirmed_at, :datetime     
      add_column :users, :confirmation_sent_at, :datetime     
      add_column :users, :unconfirmed_email, :string # add it Only if are using reconfirmable 

      add_index :users, :confirmation_token, :unique => true
     end

    def down
      remove_column :users, :confirmation_token, :confirmed_at, :confirmation_sent_at
      # remove_column :users, :unconfirmed_email # Only if using reconfirmable
    end
 end

run the migration to introduce the newly added filed rake db:migrate

STEP 2: Modifying the model

In model we will do below modification

class User < ActiveRecord::Base

  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable,
    :validatable, :timeoutable, :omniauthable , :token_authenticatable, :confirmable 
    # to use devise_confirmable module, registerable and confirmable module must be there
end

STEP 3: Modifying the config/intializers/devise.rb

devise confirmable module implement reconfirmable by default i,e if a user has not clicked the confirmation link and try to login then it will send the confirmation link again, if you do not want this, you can deactivate it by setting false in config/intializers/devise.rb as below

config.reconfirmable = false

STEP  4: Setting up smtp server

The mailer setting is written in individual environment file. For example, for development we write it in config/environments/development.rb. My file look like this(Iam showing only mailer code)

config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"

config.action_mailer.smtp_settings = {
address: "smtp.gmail.com", #this is you remote mail server, if you do not specify it rails will use 
mail server installed in your localhost
port: 587, # the port at which mail server is running, for local host it is at 25
domain: "example.com", # just giving a domain name to you smtp server, you can use any name
authentication: "plain", # If your mail server requires authentication, you need to specify 
the authentication type here.This is a symbol and one of :plain, :login, :cram_md5.
enable_starttls_auto: true,
user_name: "xyz@yopmail.com",
password:  "test123"
}

STEP 5: See it working.

restart the server, go to signup page and register a user. Strange, your user did’nt get any email at say arun@yopmail.com with which he has registered. But when you see the console, you do see that email is getting delivered.

Problem 1: confirmation email not really getting delivered to user although he can see it triggered in terminal log.

Solution : This is happening because, you are running your app in development mode for which mail delivery is disabled by default . In your setting in step 4, you should change the value of the below line to true
config.action_mailer.perform_deliveries = false # it is preventing real delivery of the email
config.action_mailer.perform_deliveries = true # now your email will get delivered

Restart the server and try to register a user again.. Now If you are using setting of step4 ,you will encounter the next error

Problem 2: Net::SMTPAuthenticationError in Devise::ConfirmationsController

Solution : The problem here is that devise do authentication of the user you have passed in setting of step 4 i,e the username and password you have passed in step 4 should be a real gmail user. Note that you have set dummy value like user_name: “xyz@yopmail.com”, password:¬† “test123”. This user_name and password should be replaced with
a real gmail account detail. I put user_name: arunprojects@gmail.com and password: mypassword and it start working ūüôā

So, Now when a user register himself, he will get a confirmation email, when he will click the email link he will able to login otherwise get message, “You have not activated your account” but the problem here is that, all the user existed earlier will not able to login as at the time of there creation. confirmation module is not activated so they, did’nt get the email. But now since devise_confirmable module is active those user will not bale to login. We need to fix this. We will write a rake task for this in next step

STEP 6 : writing rake task to update existing user as confirmed

Create a user.rake file in lib/tasks folder of your app and below line to it

namespace :users do
  desc "set all old user as confirmed by devise confirmable module"
  task :confirm_existing_user => :environment do
    User.update_all(:confirmed_at => Time.now)
  end
end

Now go to condole and run below command

$ rake users:confirm_existing_user # it will update all user as confirmed


6 Comments

tomcat on ubuntu : install configure start stop

Tomcat is application server .  more detail on it is available here. In simple words, tomcat is container for memory resident java program called servlets. Since, servlets are memory-resident, they can quickly respond to requests, as they do not incur the overhead of process creation and subsequent cleanup, unlike CGI-based scripting, e.g. perl, etc.

Although, there is no context of JSP in this post, I just want to mention it here as servlets and jsp is at the core of java and if you have to do any thing with java you must know servlets and JSP. So,  JSP is comparable to other technologies such as PHP and ASP, which combine programming/scripting with a markup language like HTML. The key difference being the programming language of choice. For example, PHP uses a C/C++/Java hybrid, ASP uses VBScript, and JSP utilizes the full power of the Java programming language.

With, the above introduction we will now install and configure tomcat. I have referenced myself from ubuntu help center here.

STEP 1 -> Prerequisite :

NOTE : I’ am using ubuntu 12.04 and current tomcat version available with it is tomcat7 if you get any higher version say 8 then replace all 7 with the current version i,e say 8

$ which java # check that java is installed if not install it. I will write a post on it some other day.

/usr/bin/java # so our java is present at the given location, if you do not find any you need to install java before proceeding further.

NOTE : the /usr/bin/java is symlinked file i,e it just contain information about the location of jvm. You must know the location of your jvm. Depending on how you have installed java, it may be present at different location. In my case it is present at /usr/lib/jvm. Further, you may have multiple java installed within your jvm folder, you just need to specify one of them in your tomcat configuration. If you find it difficult to locate your jvm folder, you can try below in terminal.

Locating installed java on ubuntu

$ which java
/usr/bin/java # so you java is installed and present in /usr/bin/java
$ cd /usr/bin/ # let us move to /usr/bin
$ ls -l | grep java # list the file with name java
lrwxrwxrwx 1 root   root          22 Oct 16 14:20 java -> /etc/alternatives/java
lrwxrwxrwx 1 root   root          23 Oct 16 14:21 javac -> /etc/alternatives/javac
lrwxrwxrwx 1 root   root          25 Oct 16 14:21 javadoc -> /etc/alternatives/javadoc
lrwxrwxrwx 1 root   root          32 Oct 16 14:21 javafxpackager -> /etc/alternatives/javafxpackager
lrwxrwxrwx 1 root   root          23 Oct 16 14:21 javah -> /etc/alternatives/javah
lrwxrwxrwx 1 root   root          23 Oct 16 14:21 javap -> /etc/alternatives/javap
lrwxrwxrwx 1 root   root          25 Oct 16 14:20 java_vm -> /etc/alternatives/java_vm
lrwxrwxrwx 1 root   root          24 Oct 16 14:20 javaws -> /etc/alternatives/javaws

NOTE : the files are again symlinked file pointing to /etc/alternatives i,e we need to find 
our jvm there
$ cd /etc/alternatives/ #moving to /etc/alternatives


$ ls -l | grep java # listing java file within it
.......many more lines 
lrwxrwxrwx 1 root root  34 Oct 16 14:21 jar -> /usr/lib/jvm/java-7-oracle/bin/jar
lrwxrwxrwx 1 root root  39 Oct 16 14:20 java -> /usr/lib/jvm/java-7-oracle/jre/bin/java

NOTE : the files are again symlinked file pointing to /usr/lib/jvm/java-7-oracle. Now if you go 
to /usr/lib/jvm, you can find different installed java, in my case, I am having only java-7-oracle. 
So my JVM_HOME will be /usr/lib/jvm/java-7-oracle

$ sudo apt-get install libtomcat7-java # it install java related dependency of tomcat7

$ sudo apt-get install tomcat7-common  # it will install some other common dependency of tomcat

STEP 2 ->Installing Tomcat :

$ sudo apt-get install tomcat7 # the last few lines are, check them as it will tell you about any 
faults or other things you need to do

Unpacking tomcat7 (from .../tomcat7_7.0.26-1ubuntu1.1_all.deb) ...
Selecting previously unselected package authbind.
Unpacking authbind (from .../authbind_1.2.0build3_i386.deb) ...
Processing triggers for ureadahead ...
ureadahead will be reprofiled on next reboot
Processing triggers for man-db ...
Setting up libcommons-collections3-java (3.2.1-5) ...
Setting up libcommons-pool-java (1.5.6-1) ...
Setting up libcommons-dbcp-java (1.4-1ubuntu1) ...
Setting up libecj-java (3.5.1-3) ...
Setting up libservlet3.0-java (7.0.26-1ubuntu1.1) ...
Setting up libtomcat7-java (7.0.26-1ubuntu1.1) ...
Setting up tomcat7-common (7.0.26-1ubuntu1.1) ...
Setting up tomcat7 (7.0.26-1ubuntu1.1) ...

Creating config file /etc/default/tomcat7 with new version
Adding system user `tomcat7' (UID 120) ...
Adding new user `tomcat7' (UID 120) with group `tomcat7' ...
Not creating home directory `/usr/share/tomcat7'.
* no JDK found - please set JAVA_HOME
invoke-rc.d: initscript tomcat7, action "start" failed.
Setting up authbind (1.2.0build3) ...

Since the log tell us to set java home, we will set it

NOTE : In ubuntu anything you install through sudo apt-get command install it to /etc folder , so you can find a tomcat7 folder here. If you install anything through download package it will get installed to /usr/local folder

$ sudo su – # you need to be root user to edit /etc/default/tomcat7 file

$ nano /etc/default/tomcat7 # to use nano editor see here. You can use any other editor also to edit this file, but at end you should be able to add java_home to it

JAVA_HOME=/usr/lib/jvm/java-7-oracle

~# exit # exist as the root user
logout

STEP 3 -> Starting tomcat

If you install any thing with sudo apt-get install the start file resides in /etc/init.d folder

$ sudo /etc/init.d/tomcat7 start #the other options are  stop restart try-restart force-reload and status

STEP 4 -> See it running in the browser

http://localhost:8080 # on browser will load the page with message its working.

If the port 8080 is allready in use by some other server, you can change it by changing below line in /etc/tomcat6/server.xml

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
...
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

Step 5 -> Installing standard webapps

Tomcat is shipped with webapps that you can install for documentation, administration or demo purposes.

$ sudo apt-get install tomcat7-docs # it will install the documentation for your reference

http://localhost:8080/docs/ # you can see the complete reference in your local browser onward

Step 6 -> Installing tomcat admin # will provide you a interface to administer tomact i,e start stop this

$ sudo apt-get install tomcat7-admin

Try to login to the admin page
http://localhost:8080/manager/html # it will ask you for username password¬† Access to the host-manager application is also protected by default:¬† you need to define a user with the role “admin” in¬† /etc/tomcat6/tomcat-users.xml¬† before you can access it.

add below line to this file

<tomcat-users>
<role rolename="manager-gui" />
<user username="arun" password="happyarun" roles="manager-gui" />
</tomcat-users>

restart the server

# sudo /etc/init.d/tomcat7 restart

reload the page and enter username and  password ..you can see the admin page

For security reasons, the tomcat7 user cannot write to the /etc/tomcat7 directory by default. Some features in these admin webapps (application deployment, virtual host creation) need write access to that directory. If you want to use these features execute the following, to give users in the tomcat7 group the necessary rights:

$ sudo chgrp -R tomcat7 /etc/tomcat7
$ sudo chmod -R g+w /etc/tomcat7

STEP 7 -> Installing tomcat example package

The tomcat7-examples package contains two webapps that can be used to test or demonstrate Servlets and JSP features, which you can access them by default at http://yourserver:8080/examples. You can install them by entering the following command in the terminal prompt:

$ sudo apt-get install tomcat7-examples # after completion see the example app in browser as below

http://localhost:8080/examples/ # will show you the example web app