0% found this document useful (0 votes)
312 views

Cloud Computing

Cloud computing installation of virtual box,install a compiler in the virtual machine,install google app engine.use gae launcher to launch the web application.develop a new web applicator.there are so many contents are available

Uploaded by

Muthu meena
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
312 views

Cloud Computing

Cloud computing installation of virtual box,install a compiler in the virtual machine,install google app engine.use gae launcher to launch the web application.develop a new web applicator.there are so many contents are available

Uploaded by

Muthu meena
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 100

PSNA

College of Engineering & Technology

Kothandaraman Nagar, Dindigul- 624 622.

TAMILNADU.

RECORD NOTE BOOK

Reg.No:

Certify that this is the bonafide record of work done by


Mr./Ms. _ of the Seventh Semester
B.Tech Information Technology Branch during the year 2020-2021 in the
IT8711 FOSS AND CLOUD COMPUTING LABORATORY.

Staff-in-Charge Head of the


Department

Submitted for the

UniversityPractical Examinationon 2020

1
InternalExaminer External Examiner

LIST OF EXPERIMENTS

EX.NO DATE NAME OF THE EXPERIMENT SIGNATU


RE

1 INSTALLATION OF
VIRTUALBOX\VMWARE WORKSTATION
WITH DIFFERENT FLAVOURS OF LINUX
OR WINDOWS OS

2 INSTALL A C COMPILER IN THE


VIRTUAL MACHINE CREATED USING
VIRTUAL BOX AND EXECUTE SIMPLE
PROGRAMS

3 INSTALL GOOGLE APP ENGINE AND


CREATE HELLO WORLD APP AND
OTHER SIMPLE APPLICATION USING
PYTHON OR JAVA

4 USE GAE LAUNCHER TO LAUNCH THE


WEB APPLICATION

5 SIMULATE A CLOUD SCENARIO USING


CLOUDSIM AND RUN A SCHEDULING
ALGORITHM THAT IS NOT PRESENT IN
CLOUDSIM

6. FIND A PROCEDURE TO TRANSFER THE


FILES FROM ONE VIRTUAL MACHINE TO

2
ANOTHER VIRTUAL MACHINE

7. PROCEDURE TO LAUNCH VIRTUAL


MACHINE USING OPENSTACK

8. INSTALLATION OF SINGLE NODE


HADOOP CLUSTER

9. WRITE A WORD COUNT PROGRAM TO

DEMONSTRATE THE USE OF MAP AND

REDUCE TASKS

10. DEVELOP A NEW WEB APPLICATION

FOR CALCULATOR

11. DEVELOP A NEW WEB APPLICATION FOR


DEVELOPING ONLINE REGISTRATION
FORM

3
Ex.No: 1 INSTALLATION OF VIRTUALBOX\VMWARE WORKSTATION WITH
DIFFERENT FLAVOURS OF LINUX OR WINDOWS OS

Date:

AIM:
To Install virtual box/ VM ware workstation with different flavours of Linux or Windows OS.

PROCEDURE:
VirtualBox:   

 Virtual machine like virtualbox you can virtually install multiple operating systems, without
having to buy any new hardware.
 VirtualBox is a piece of software published by Oracle. It allows you to emulate an operating
system on your own PC and use it like it’s running on real hardware.

VMware workstation:

 VMware Workstation is a virtual machine software that is used for x86 and x86-64
computers to run multiple operating systems over a single physical host computer.
 Each virtual machine can run a single instance of any operating system like Microsoft,
Linux,etc.simultaneously.
 VMware Workstation strongly supports hardware compatibility and works as a bridge
between the host and virtual machine for all kinds of hardware resources including hard
disks, USB devices and CD-ROMs.
 All device drivers are installed via the host machine.

Installing Linux inside Windows using VirtualBox

Requirements

 Good internet connection to download software and Linux ISO. (We prefer some other
computer with an internet connection to download these files.) 

 Windows system with at least 12 GB of free space.


 Windows system with 4GB of RAM. (It can work with less RAM as well, but your
system will start to lag while using Linux in the virtual machine.)
4
Step 1: Download and install VirtualBox

Go to the website of Oracle VirtualBox and get the latest stable version from
here:https://www.virtualbox.org/
Just double-click on the downloaded .exe file and follow the instructions on the screen. It is like
installing any regular software on Windows.

Step 2: Download the Linux ISO

Next,download the ISO file of the Linux distribution.I am using Ubuntu in this example,
download ISO images for Ubuntu from the link below:
https://ubuntu.com/desktop

5
Step 3: Install Linux using VirtualBox

Installed VirtualBox and downloaded the ISO for Linux, now set to install Linux in VirtualBox.
Start VirtualBox, and click on the New symbol. Give the virtual OS a relevant name.

Allocate RAM to the virtual OS.System has 8GB of RAM and I decided to allocate 2GB of it.
You can use more RAM if your system has enough extra.

Create a virtual disk. This serves as the hard disk of the virtual Linux system. It is where the
virtual system will store its files.

6
using the VDI file type here.

choose either the “Dynamically allocated” or the “Fixed size” option for creating the virtual hard
disk.

7
The recommended size is 10 GB. However, I suggest giving it more space if possible. 15-20 GB
is preferable.

Once everything is in place, it’s time to boot that ISO and install Linux as a virtual operating
system.

8
If VirtualBox doesn’t detect the Linux ISO, browse to its location by clicking the folder icon as
shown in the picture below:

find yourself inside Linux. It should be presented with the option to install it.

Things from here are Ubuntu-specific. Other Linux distributions may have slightly different
looking steps, but it won’t be complicated at all.

9
After clicking the install ubuntu button it starts installing,

Select ‘Erase disk and install Ubuntu’. It won’t delete anything on your Windows operating
system. You are using the virtual disk space of 15-20GB that we created in previous steps. It
won’t impact the real operating system.

10
Just click on Continue.

Things are pretty straightforward from here.

11
Try to choose a password that you can remember. You can also reset the password in Ubuntu if
you forget it.

12
You are almost done. It may take 10-15 minutes to complete the installation.

Once the installation finishes, restart the virtual system.

13
If it gets stuck on the screen below, you may close the VirtualBox.

Finally Ubuntu is installed in Virtualbox which is kept inside the windows Os.We can acess the
Ubuntu and windows os at a same time in a single system.

14
RESULT:

Thus the installation virtual box/ VM ware workstation with different flavors of Linux or
Windows OS is done.

15
EX.NO:2 INSTALL A C COMPILER IN THE VIRTUAL MACHINE CREATED USING
VIRTUAL BOX AND EXECUTE SIMPLE PROGRAMS

DATE:

AIM

To install a C compiler in the virtual machine created using virtual box and execute simple
programs.

PROCEDURE:

Install virtual box:

1.Open the http://www.virtualbox.org/wiki/downloads

2. Download VirtualBox platform packages for your OS

3. Open the Installation Package by double clicking Install VirtualBox .

4. Click continue and finish installing VirtualBox.

5. When finished installation, close the window.

16
DOWNLOAD LINUX:

1.Visit the page http://www.ubuntu.com/download/ubuntu/download

2. Choose the Latest version of Ubuntu and 32-bit and click “Start Download” CLICK

Install Linux using Virtual Box

1. Run VirtualBox by double-clicking the icon

17
2. Click “New” button on the top left corner MAC PC

3. Click “Continue” on the pop-up window

4. Type VM name, select “Linux” for the OS and choose “Ubuntu” for the version. MAC PC
Install Linux using Virtual Box

5. Choose the amount of memory to allocate (I suggest choosing between 512 MB to 1024 MB)

6. Click Continue or Next MAC PC Install Linux using Virtual Box

18
7. Choose create a new virtual hard disk

8. Click Continue or Next MAC PC Install Linux using Virtual Box

9. Choose VDI (VirtualBox Disk Image)

10. Click Continue or Next MAC PC Install Linux using Virtual Box

19
11. Choose “Dynamically Allocated” click continue. This way, the size of your Virtual Hard
Disk will grow as you use. MAC PC Install Linux using Virtual Box

12. Click the folder icon and choose the ubuntu iso file you downloaded.

13. Select the size of the Virtual Disk (I recommend choosing 8 GB) and click continue MAC
PC Install Linux using Virtual Box

14. Click Create

20
RUNNING LINUX:

1. Choose Ubuntu from left column and click Start MAC & PC Running Linux

2. Click continue on pop-up window Running Linux MAC PC

21
3. Click the folder icon and choose the ubuntu iso file you downloaded and click continue and
start Running Linux MAC PC Running Linux

22
4. Click Install Ubuntu Running Linux Check “Download updates” and click Forward Running
Linux

5. Choose “Erase disk and install Ubuntu” and click Forward (Don’t worry, it won’t wipe your
computer) Running Linux

23
6. Click “Install Now” and wait. Maybe grab a snack.

7. When finished, click Restart and press Enter.

24
C Programming on Linux

1. Open Terminal (Applications-Accessories-Terminal)

2. Open gedit by typing “gedit &” on terminal (You can also use any other Text Editor
application)
3. Type the following on gedit (or any other text editor)
#include main()
{
printf("Hello World\n");
}

25
Save this file as “helloworld.c” C Programming on Linux

5. Type “ls” on Terminal to see all files under current folder


6. Confirm that “helloworld.c” is in the current directory. If not, type cd
DIRECTORY_PATH to go to the directory that has “helloworld.c” C Programming on
Linux
7. Type “gcc helloworld.c” to compile, and type “ls” to confirm that a new executable file
“a.out” is created

26
8. Type “./a.out” on Terminal to run the program
9. If you see “Hello World” on the next line, you just successfully ran your first C program!
C Programming on Linux
10. Try other codes from “A Shotgun Introduction to C” on professor Edwards’s webpage.
You can also find many C programing guides online.

RESULT:

Thus the Installation of a C compiler in the virtual machine created using virtual box and
executed the Simple Programs and output is verified successfully.

27
EX.NO:3 INSTALL GOOGLE APP ENGINE AND CREATE HELLO WORLD APP
AND OTHER SIMPLE APPLICATION USING PYTHON OR JAVA
DATE:

AIM:
To Install Google App Engine. Create hello world app and other simple web applications using
python/java.

PROCEDURE:
Step1:
Download and Install Python 2.5.4 from:http://www.python.org/download/releases/2.5.4/

Step2:
Step2.1: Download and Install Google App Engine SDK by going to:
http://code.google.com/appengine/downloads.html
Step2.2: Download the appropriate install package.

Step2.3: Download the Windows installer – the simplest thing is to download it to Desktop or
another folder that remember.

Step2.4: Double Click on the Google Application Engine installer.

28
Step2.5: Click through the installation wizard, and it should install the App Engine.
Step2.6: Once the install is complete you can discard the downloaded installer.

Step3:To use Eclipse to create a Google App Engine (GAE) Python web project (hello


worldexample), run it locally, and deploy it to Google App Engine account.
Tools used :
 Python 2.7
 Eclipse 3.7 + PyDev plugin
 Google App Engine SDK for Python 1.6.4

Step3.1:Install PyDev plugin for Eclipse


Use following URL to install PyDev as Eclipse plugin.http://pydev.org/updates

Figure 1 – In Eclipse , menu, “Help –> Install New Software..” and put above URL. Select
“PyDev for Eclipse” option, follow steps, and restart Eclipse once completed.

29
Step3.2: Verify PyDev
After Eclipse is restarted, make sure PyDev’s interpreter is pointed to your “python.exe“.

Figure 2 – Eclipse -> Windows –> Preferences, make sure “Interpreter – Python” is configured
properly.

30
Step3.3: Python Hello World in Eclipse
Following steps to show you how to create a GAE project via Pydev plugin.

Figure 3.1 – Eclipse menu, File -> New -> Other… , PyDev folder, choose “PyDev Google App
Engine Project“.

Figure 3.2 – Type project name, if the interpreter is not configure yet (in step 2), you can do it
now. And select this option – “Create ‘src’ folder and add it to PYTHONPATH“.

31
Figure 3.3 – Click “Browse” button and point it to the Google App Engine installed directory (in
step 3).

Figure 3.4 – Name your application id in GAE, type anything, you can change it later. And
choose “Hello Webapp World” template to generate the sample files.

32
Figure 3.5 – Done, 4 files are generated, Both “.pydevproject” and “.project” are Eclipse project
files, ignore it.

Review the generated Python’s files :


File : helloworld.py – Just output a hello world.

File : app.yaml – GAE need this file to run and deploy your Python project, it’s quite self-
explanatory, for detail syntax and configuration, visit yaml and app.yaml reference.

Step3.4: Run it locally

33
To run it locally, right click on the helloworld.py, choose “Run As” –> “Run Configuration”,
create a new “PyDev Google App Run“.

Figure 4.1 – In Main tab -> Main module, manually type the directory path of
“dev_appserver.py“. “Browse” button is not able to help you, type manually.

Figure 4.2 – In Arguments tab -> Program arguments, put “${project_loc}/src“.

34
Figure 4.3 – Run it. By default, it will deploy to http://localhost:8080.

Figure 4.4  – Done.

Step5: Deploy to Google App Engine


Register an account on https://appengine.google.com/, and create an application ID for your
web application. Review “app.yaml” again, this web app will be deployed to GAE with
application ID “mkyong-python“.
File : app.yaml

To deploy to GAE, see following steps :

Figure 5.1 – Create another new “PyDev Google App Run”, In Main tab -> Main module,
manually type the directory path of “appcfg.py“.

35
Figure 5.2 – In Arguments tab -> Program arguments, put “update ${project_loc}/src“.

36
Figure 5.3 – During deploying process, you need to type your GAE email and password for
authentication.

Figure 5.4 – If success, the web app will be deployed to – http://mkyong-python.appspot.com/.

RESULT:
Thus, the installation of Google App Engine is done and the Creation of hello world app and
other simple web applications using python/java is done.

37
EX.NO:4 USE GAE LAUNCHER TO LAUNCH THE WEB APPLICATION
Date:

AIM:
To write a procedure to use GAE launcher to launch the web application.

Making  your  First  Application  :


Now  you  need  to  create  a  simple  application.      We  could  use  the  “+”  option  to have  
the  launcher  make  us  an  application  –  but  instead  we  will  do  it  by  hand  to get  a   better
sense  of  what  is  going  on. Make  a  folder  for  your  Google  App  Engine  applications.    I
am  going  to  make  the Folder  on  my  Desktop  called  “apps”  –  the  path  to  this  folder  is:  
C:\Documents  and  Settings\csev\Desktop\apps
And  then  make  a  sub-‐folder  in  within  apps  called  “ae-01-trivial”  –  the  path  to  this  
folder  would  be:
C:\  Documents  and  Settings  \csev\Desktop\apps\ae-01-trivial
Using  a  text  editor  such  as  JEdit  (www.jedit.org),  create  a  file  called  app.yaml  in  the  
ae-01-trivial  folder  with  the  following  contents:
application: ae-01-trivial
version: 1
runtime: python
api_version: 1
handlers: -
url: /.*
script: index.py
Then  create  a  file  in  the  ae-01-trivial  folder  called  index.py  with  three  lines  in  it:
print 'Content-Type: text/plain'
print ' '
print 'Hello there Chuck'
Then  start  the  GoogleAppEngineLauncher  program  that  can  be  found  under  
Applications.  Use  the  File  >  Add  Existing  Application  command  and  navigate   into  the
apps  directory  and  select  the  aetrivial  folder.    Once  you  have  added   the  application,
select  it  so  that  you  can  control  the  application  using  the  launcher.

38
Once  you  have  selected  your  application  and  press  Run. After  a  few  moments  your
application  will  start  and  the  launcher  will  show  a  little  green  icon  next  to  your
application.    Then  press  Browse  to  open  a  browser  pointing  at  your  application   which  is
running  at  
http://localhost:8080/
Paste http://localhost:8080  into  your  browser  and  you  should  see  your   application  as
follows:

Just  for  fun,  edit  the  index.py  to  change  the  name  “Chuck”  to  your  own  name  and  
press  Refresh  in  the  browser  to  verify  your  updates.
Watching  the  Log:
You  can  watch  the  internal  log  of  the  actions  that  the  web  server  is  performing  when  
you  are  interacting  with  your  application  in  the  browser.      Select  your  application  in   the
Launcher  and  press  the  Logs  button  to  bring  up  a  log  window:

39
Each  time  you  press  Refresh  in  your  browser  –  you  can  see  it  retrieving  the  output  
with  a  GET  request.
Dealing  With  Errors  :
With  two  files  to  edit,  there  are  two  general  categories  of  errors  that  you  may  
encounter.    If  you  make  a  mistake  on  the  app.yaml  file,  the  App  Engine  will  not  start  
and  your  launcher  will  show  a  yellow  icon  near  your  application:

To  get  more  detail  on  what  is  going  wrong,  take  a  look  at  the  log  for  the  application:

40
In  this  instance  –  the  mistake  is  mis-‐indenting  the  last  line  in  the  app.yaml  (line  8). If
you  make  a  syntax  error  in  the  index.py  file,  a  Python  trace  back  error  will  appear   in
your  browser.  

The  error  you  need  to  see  is  likely  to  be  the  last  few  lines  of  the  output  –  in  this  case
I  made  a  Python  syntax  error  on  line  one  of  our  one-‐line  application.
Reference:  http://en.wikipedia.org/wiki/Stack_trace
When  you  make  a  mistake  in  the  app.yaml  file  –  you  must  the  fix  the  mistake  and  
attempt  to  start  the  application  again.  
If  you  make  a  mistake  in  a  file  like  index.py,  you  can  simply  fix  the  file  and  press  
refresh  in  your  browser  –  there  is  no  need  to  restart  the  server.

41
Shutting  Down  the  Server:
To  shut  down  the  server,  use  the  Launcher,  select  your  application  and  press  the
Stop button.

RESULT:
Thus the use of GAE launcher to launch the web application is successfully verified.

42
Ex.No:5 SIMULATE A CLOUD SCENARIO USING CLOUDSIM AND RUN A
SCHEDULING ALGORITHM THAT IS NOT PRESENT IN CLOUDSIM

Date:

AIM:

To simulate a cloud scenario using cloudsim and run a scheduling algorithm that is not present
in cloudism.

ALGORITHM:

Download CloudSim installable files from https://code.google.com/p/cloudsim/downloads/list


and unzip

Open Eclipse

Create a new Java Project: File -> New

Import an unpacked CloudSim project into the new Java Project

The first step is to initialise the CloudSim package by initialising the CloudSim library, as
follows:CloudSim.init(num_user, calendar, trace_flag)

Data centres are the resource providers in CloudSim; hence, creation of data centres is a second
step. To create Datacenter, you need the DatacenterCharacteristics object that stores the
properties of a data centre such as architecture, OS, list of machines, allocation policy that covers
the time or spaceshared, the time zone and its price:

Datacenter datacenter9883 = new Datacenter(name, characteristics, new


VmAllocationPolicySimple(hostList), s

The third step is to create a broker:DatacenterBroker broker = createBroker();

The fourth step is to create one virtual machine unique ID of the VM, userId ID of the VM’s
owner, mips, number Of Pes amount of CPUs, amount of RAM, amount of bandwidth, amount
of storage, virtual machine monitor, and cloudletScheduler policy for cloudlets:

Vmvm = new Vm(vmid, brokerId, mips, pesNumber, ram, bw, size, vmm, new
CloudletSchedulerTimeShared())

Submit the VM list to the broker:

broker.submitVmList(vmlist)

43
Create a cloudlet with length, file size, output size, and utilisation model:

Cloudlet cloudlet = new Cloudlet(id, length, pesNumber, fileSize, outputSize, utilizationModel,


utilizationMode

Submit the cloudlet list to the broker:

broker.submitCloudletList(cloudletList)

12. Start the simulation:

CloudSim.startSimulation()

44
SCHEDULING IN CLOUDISM:

The Cloudsim simulation toolkit framework has effectively addressed the Scheduling scenario
and implemented it as a set of the programmable class hierarchies with parent class as:

 VmScheduler
 CloudletScheduler

Cloudsim Virtual Machine Scheduling

The VmScheduler is an abstract class that defines and implements the policy used to share
processing power among virtual machines running on a specified host. The hierarchy of the
cloudsim virtual machine scheduler classes is as:

 VmSchedulerTimeShared: This class implements the VM scheduling policy that allocates


one or more processing elements to a single Virtual machine and allows the sharing of
processing elements by multiple virtual machines with a specified time slice. This class
also considers the overhead of VM allocation switching(similar to context switching) in
policy definition. Here, the VM allocation will fail if the number of processing elements
requested is not available. for example, if the VM request for quad-core processor
whereas the allocated host has an only dual-core the allocation will fail.
 VmSchedulerSpaceShared: This class implements the VM scheduling policy that
allocates one or more processing elements to a single virtual machine, but this policy
implementation does not support sharing of processing elements (i.e.) all the requested

45
resources will be used by the allocated VM till the time the VM is not destroyed. Also,
Under this allocation policy, if any virtual machine requests a processing element and is
not available at that time, the allocation fails.
 VmSchedulerTimeSharedOverSubscription: This is an extended implementation of
VMSchedulerTimeShared VM scheduling policy, which allows over-subscription of
processing elements by the virtual machine(s) (i.e.) the scheduler still allows the
allocation of VMs that require more CPU capacity that is available. And this
oversubscription results in performance degradation.

Cloudsim Cloudlet Scheduling

The “CloudletScheduler” is an abstract class that defines the basic skeleton to implement the
policy to be used for cloudlet scheduling to be performed by a virtual machine. The hierarchy of
the cloudsim Cloudlet scheduler classes is as:

 CloudletSchedulerSpaceShared: This class implements a policy of scheduling for Virtual


machine to execute cloudlet(s) in space shared environment (i.e.) only one cloudlet will
be executed on a virtual machine at a time. It means cloudlets share the same queue and
requests are processed one at a time per computing core. Space-sharing is similar to
batch processing.
 CloudletSchedulerTimeShared: This class implements a policy of cloudlet scheduling for
Virtual machines to execute cloudlets in a time-shared environment (i.e.) more than one
cloudlet will be submitted to the virtual machine and each will get its specified share of
time. It means several requests (cloudlets) are processed at once but they must share the
computing power of that virtual machine(by simulating context switching), so they will
affect each other’s processing time. It basically influences the completion time of a

46
cloudlet in CloudSim. Time-sharing is probably referring to the concept of sharing
executing power (such as CPU, logical processor, GPU) and is commonly known as the
round-robin scheduling.
 CloudletSchedulerDynamicWorkload: This implements a special policy of scheduling for
virtual machine assuming that there is just one cloudlet which is working as an online
service with a different requirement of workload as per the need of peak/offpeak user
load at a specified period of time.

PROGRAM:

Starting CloudSimExample1...

Initialising...

Starting CloudSim version 3.0

Datacenter_0 is starting...

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>null

Broker is starting...

Entities started.

0.0: Broker: Cloud Resource List received with 1 resource(s)

0.0: Broker: Trying to Create VM #0 in Datacenter_0

0.1: Broker: VM #0 has been created in Datacenter #2, Host #0

0.1: Broker: Sending cloudlet 0 to VM #0

400.1: Broker: Cloudlet 0 received

47
400.1: Broker: All Cloudlets executed. Finishing...

400.1: Broker: Destroying VM #0

Broker is shutting down...

Simulation: No more future events

CloudInformationService: Notify all CloudSim entities for shutting down.

Datacenter_0 is shutting down...

Broker is shutting down...

Simulation completed.

Simulation completed.

OUTPUT:

========== OUTPUT ==========

Cloudlet ID STATUS Data center ID VM ID Time Start Time Finish Time

0 SUCCESS 2 0 400 0.1 400.1

*****Datacenter: Datacenter_0*****

User idDebt

35.6 CloudSimExample1 finished.

RESULT:

Thus, cloud scenario using CloudSim has been simulated and scheduling algorithm that is not
present in CloudSim.

48
EX.NO:6 FIND A PROCEDURE TO TRANSFER THE FILES FROM ONE VIRTUAL
MACHINE TO ANOTHER VIRTUAL MACHINE
DATE:
AIM:
To find procedure to transfer the files from one virtual machine to another virtual machine.

ALGORITHM:
1. You can copy few (or more) lines with copy & paste mechanism.

For this you need to share clipboard between host OS and guest OS, installing
GuestAddition on both the virtual machines (probably settingbidirectionaland restarting
them).You copy from guest OS in the clipboard that is shared with the host OS.

Then you paste from the host OS to the second guest OS.

2. You can enable drag and drop too with the same method (Click on the machine,
settings, general, advanced, drag and drop: set to bidirectional )

49
3. You can have commonShared Folders on both virtual machines and use one of the
directory shared as buffer to copy.

Installing Guest Additions you have the possibility to set Shared Folders too. As you put
a file in a shared folder from host OS or from guest OS, is immediately visible to the other.
(Keep in mind that can arise some problems for date/time of the files when there are
different clock settings on the different virtual machines).

If you use the same folder shared on more machines you can exchange files directly
copying them in this folder.

50
4. You can use usual method to copy files between 2 different computer with client-server
application. (e.g. scp with sshd active for linux, winscp... you can get some info about
SSHservers e.g. here)

You need an active server (sshd) on the receiving machine and a client on the sending
machine. Of course you need to have the authorization setted (via password or, better,
via an automatic authentication method).

51
Note: many Linux/Ubuntu distribution install sshd by default: you can see if it is
runningwith pgrepsshd from a shell. You can install with sudo apt-get install openssh-
server.

5. You can mount part of the file system of a virtual machine via NFS or SSHFS on the
other, or you can share file and directory with Samba.

You may find interesting the article Sharing files between guest and host without

VirtualBox shared folders with detailed step by step instructions.

You should remember that you are dialling with a little network of machines with different
operative systems, and in particular:

• Each virtual machine has its own operative system running on and acts as a
physical machine.

• Each virtual machine is an instance of a program owned by anuser in the hosting operative
system and should undergo the restrictions of the user in the hosting OS.

E.g Let we say that Hastur and Meow are users of the hosting machine, but they did not
allow each other to see their directories (no read/write/execute authorization). When each

52
of them run a virtual machine, for the hosting OS those virtual machine are two normal
programs owned by Hastur and Meow and cannot see the private directory of the other
user. This is a restriction due to the hosting OS. It's easy to overcame it: it's enough to give
authorization to read/write/execute to a directory or to chose a different directory in which
both users can read/write/execute.

• Windows likes mouse and Linux fingers. :-)

I mean I suggest you to enable Drag & drop to be cosy with the Windows machines
and the Shared folders or to be cosy with Linux.

When you will need to be fast with Linux you will feel the need of ssh-keygen and to
Generate once SSH Keys to copy files on/from a remote machine without writing
password anymore. In this way it functions bash auto-completion remotely too.

RESULT:

Thus , the files are transferred from one virtual machine to another virtual machine.

53
EX.NO:7 PROCEDURE TO LAUNCH VIRTUAL MACHINE USING OPENSTACK
Date:

Aim:

To install Openstack in Ubuntu 14.04 version and creation of virtual machine.

Mandatory prerequisite:

1. Linux 64 bit Operating System (The commands mentioned are for Ubuntu Linux Operating
System latest version).

Installation of Openstack

1. add new user named stack – This stack user is the adminstrator of the openstack services. To
add new user – run the command as root user.

adduser stack
2. run the command

apt-get install sudo -y || install -y sudo


3. Be careful in running the command – please be careful with the syntax. If any error in thsi
following command, the system will crash beacause of permission errors.

echo “stack ALL=(ALL) NOPASSWD:ALL” >> /etc/sudoers


4. Logout the system and login as stack user

5. Run the command (this installs git repo package)

Run in Root
export http_proxy=http://172.16.0.3:8080
sudo apt-get install git
6. Run the command (This clones updatesd version of dev-stack (which is binary auto-installer
package of Openstack)

stack@JBL01:/$ export http_proxy=http://172.16.0.3:8080 stack@JBL01:/$ export


https_proxy=http://172.16.0.3:8080 stack@JBL01:/$ git config --global http.proxy
$http_proxy stack@JBL01:/$ git config --global https.proxy $http_proxy
git clone http://git.openstack.org/openstack-dev/devstack ls (this shows a folder named
devstack)
cd devstack (enter into the folder)
7. create a file called local.conf. To do this run the command,

nano local.conf
stack@JBL01:/devstack$ sudo nano local.conf

54
8. In the file, make the following entry (Contact Your Network Adminstrator for doubts in these
values)

[[local|localrc]] FLOATING_RANGE=192.168.1.224/27 FIXED_RANGE=10.11.11.0/24


FIXED_NETWORK_SIZE=256 FLAT_INTERFACE=eth0 ADMIN_PASSWORD=root
DATABASE_PASSWORD=root RABBIT_PASSWORD=root
SERVICE_PASSWORD=root SERVICE_TOCKEN=root

9. Save this file

stack@JBL01:/devstack$ sudo gedit stackrc

Save this file


Change File Permission: stack@JBL01:~$ chown stack * -R

10. Run the command (This installs Opentack)


./stack.sh
11. If any error occurs, then run the command for uninistallation

./unstack.sh
1. update the packages

apt-get update
2. Then reinstall the package

./stack.sh
12. Open the browser, http://IP address of your machine, you will get the openstack portal.

13. If you restart the machine, then to again start open stack

open terminal,
su stack
cd devstack run ./rejoin.sh
14. Again you can access openstack services in the browser, http://IP address of your machine,

VIRTUAL MACHINE CREATION:

Launch an instance
1. Log in to the dashboard
2. Select the appropriate project from the drop down menu at the top left.
3. On the Project tab, open the Compute tab and click Instances category.

The dashboard shows the instances with its name, its private and floating IP addresses, size,
status, task, power state, and so on.

55
4. Click Launch Instance.
5. In the Launch Instance dialog box, specify the following values:

Details tab
Availability Zone
By default, this value is set to the availability zone given by the cloud provider (for example, us-
west or apac-south). For some cases, it could be nova.
Instance Name
Assign a name to the virtual machine.

Note:
The name you assign here becomes the initial host name of the server. If the name is longer than
63 characters, the Compute service truncates it automatically to ensure dnsmasq works correctly.
After the server is built, if you change the server name in the API or change the host name
directly, the names are not updated in the dashboard.
Server names are not guaranteed to be unique when created so you could have two instances with
the same host name.
Flavor
Specify the size of the instance to launch.
Note:
The flavor is selected based on the size of the image selected for launching an instance. For
example, while creating an image, if you have entered the value in the Minimum RAM (MB)
field as 2048, then on selecting the image, the default flavor is m1.small.
Instance Count
To launch multiple instances, enter a value greater than 1. The default is 1. Instance Boot Source
Your options are:
Boot from image
If you choose this option, a new field for Image Name displays. You can select the image from
the list.
Boot from snapshot
If you choose this option, a new field for Instance Snapshot displays. You can select the snapshot
from the list.
Boot from volume
If you choose this option, a new field for Volume displays. You can select the volume from the
list.
Boot from image (creates a new volume)

With this option, you can boot from an image and create a volume by entering the Device Size
and Device Name for your volume. Click the Delete Volume on Instance Delete option to delete
the volume on deleting the instance.
Boot from volume snapshot (creates a new volume)
Using this option, you can boot from a volume snapshot and create a new volume by choosing
Volume Snapshot from a list and adding a Device Name for your volume. Click the Delete
Volume on Instance Delete option to delete the volume on deleting the instance.

56
Image Name
This field changes based on your previous selection. If you have chosen to launch an instance
using an image, the Image Name field displays. Select the image name from the dropdown list.
Instance Snapshot
This field changes based on your previous selection. If you have chosen to launch an instance
using a snapshot, the Instance Snapshot field displays. Select the snapshot name from the
dropdown list.
Volume
This field changes based on your previous selection. If you have chosen to launch an instance
using a volume, the Volume field displays. Select the volume name from the dropdown list. If
you want to delete the volume on instance delete, check the Delete Volume on Instance Delete
option.
Access & Security tab Key Pair
Specify a key pair.
If the image uses a static root password or a static key set (neither is recommended), you do not
need to provide a key pair to launch the instance.
Security Groups
Activate the security groups that you want to assign to the instance.
Security groups are a kind of cloud firewall that define which incoming network traffic is
forwarded to instances.
If you have not created any security groups, you can assign only the default security group to the
instance.

Networking tab Selected Networks:

To add a network to the instance, click the + in the Available Networks field.
Network Ports tab Ports
Activate the ports that you want to assign to the instance. Post-Creation tab
Customization Script Source
Specify a customization script that runs after your instance launches. Advanced Options tab
Disk Partition
Select the type of disk partition from the dropdown list:
Automatic
Entire disk is single partition and automatically resizes. Manual
Faster build times but requires manual partitioning.

6. Click Launch.

The instance starts on a compute node in the cloud.


Note:
If you did not provide a key pair, security groups, or rules, users can access the instance only
from inside the cloud through VNC. Even pinging the instance is not possible without an ICMP
rule configured.
You can also launch an instance from the Images or Volumes category when you launch an
instance from an image or a volume respectively.

57
When you launch an instance from an image, OpenStack creates a local copy of the image on the
compute node where the instance starts.
When you launch an instance from a volume, note the following steps:
•To select the volume from which to launch, launch an instance from an arbitrary image
on the volume. The arbitrary image that you select does not boot. Instead, it is replaced
by the image on the volume that you choose in the next steps.
To boot a Xen image from a volume, the image you launch in must be the same type,
fully virtualized or paravirtualized, as the one on the volume.
•Select the volume or volume snapshot from which to boot. Enter a device name. Enter
vda for KVM images or xvda for Xen images.

58
59
60
61
62
CREATING USER:

63
64
65
66
67
Result:

Thus the virtual machine is launched in Ubuntu 14.04.

68
EX.NO:8 INSTALLATION OF SINGLE NODE HADOOPCLUSTER.

Date:

AIM

To develop a procedure to set up the one node Hadoop cluster.

Algorithm:
Install Hadoop

Step 1: Click hereto download the Java 8 Package. Save this file in your
home directory.

Step 2: Extract the Java Tar File.

Command: tar -xvf jdk-8u101-linux-i586.tar.gz

Fig: Hadoop Installation – Extracting Java Files

Step 3: Download the Hadoop 2.7.3 Package.

Command:wget https://archive.apache.org/dist/hadoop/core/hadoop-
2.7.3/hadoop- 2.7.3.tar.gz

Fig: Hadoop Installation – Downloading Hadoop

Step 4: Extract the Hadoop tar File.

69
Command: tar -xvf hadoop-2.7.3.tar.gz

Fig: Hadoop Installation – Extracting

Hadoop Files Step 5: Add the Hadoop and Java paths in the

bash file (.bashrc). Open. bashrc file. Now, add Hadoop and

Java Path as shown below.

Command: vi .bashrc

Fig: Hadoop Installation – Setting Environment Variable

Then, save the bash file and close it.

For applying all these changes to the current Terminal, execute the source command.

Command: source .bashrc

70
Fig: Hadoop Installation – Refreshing environment variables

To make sure that Java and Hadoop have been properly installed on your
system and can be accessed through the Terminal, execute the java
-version and hadoop version commands.

Command: java -version

Fig: Hadoop Installation – Checking Java Version

Command: hadoop version

Fig: Hadoop Installation – Checking Hadoop Version

Step 6: Edit the Hadoop Configuration files.

71
Command: cd hadoop-2.7.3/etc/hadoop/

Command: ls

All the Hadoop configuration files are located in hadoop-2.7.3/etc/hadoop


directory as you can see in the snapshot below:

Fig: Hadoop Installation – Hadoop Configuration Files

Step 7: Open core-site.xml and edit the property mentioned below inside
configuration tag:

core-site.xml informs Hadoop daemon where NameNode runs in the cluster.


It contains configuration settings of Hadoop core such as I/O settings that are
common to HDFS & MapReduce.

Command: vi core-site.xml

72
Fig: Hadoop Installation – Configuring core-site.xml

1
<?xmlversion="1.0"encoding="UTF-8"?>
2 <?xml-stylesheettype="text/xsl"href="configuration.xsl"?>

3 <configuration>

<property>
4
<name>fs.default.name</name>
5
<value>hdfs://localhost:9000</value>

6 </property>

7 </configuration>

8
Step 8: Edithdfs-site.xmland edit the property mentioned below
inside

configuration tag:
hdfs-site.xml contains configuration settings of HDFS daemons (i.e. NameNode,
DataNode, Secondary NameNode). It also includes the replication factor and
block size of HDFS.

Command: vi hdfs-site.xml

Fig: Hadoop Installation – Configuring hdfs-site.xml

73
1
<?xmlversion="1.0"encoding="UTF-8"?>
2
<?xml-stylesheettype="text/xsl"href="configuration.xsl"?>
3 <configuration>

4 <property>

<name>dfs.replication</name>
5
<value>1</value>
6
</property>
7 <property>

8 <name>dfs.permission</name>

<value>false</value>
9
</property>
10
</configuration>
11

12
Step 9: Edit the mapred-site.xml file and edit the property mentionedbelow

inside configuration tag:

mapred-site.xml contains configuration settings of MapReduce application


like number of JVM that can run in parallel, the size of the mapper and the
reducer process, CPU cores available for a process,etc.

In some cases, mapred-site.xml file is not available. So, we have to create the
mapred- site.xml file using mapred-site.xml template.

Command: cp mapred-site.xml.template mapred-site.xml

Command: vi mapred-site.xml.

74
Fig: Hadoop Installation – Configuring mapred-site.xml

1
<?xmlversion="1.0"encoding="UTF-8"?>
2 <?xml-stylesheettype="text/xsl"href="configuration.xsl"?>

3 <configuration>

<property>
4
<name>mapreduce.framework.name</name>
5
<value>yarn</value>

6 </property>

7 </configuration>

Step 10: Edit yarn-site.xml and edit the property mentioned below inside
configuration tag:

yarn-site.xml contains configuration settings of ResourceManager and


NodeManager like application memory management size, the operation
needed on program & algorithm, etc.

Command: vi yarn-site.xml

75
Fig: Hadoop Installation – Configuring yarn-site.xml

1
<?xmlversion="1.0">
2
<configuration>
3
<property>
4 <name>yarn.nodemanager.aux-services</name>

5 <value>mapreduce_shuffle</value>

</property>
6
<property>
7
<name>yarn.nodemanager.auxservices.mapreduce.shuffle.class</
8 name>

<value>org.apache.hadoop.mapred.ShuffleHandler</value>
9
</property>
1
</configuration>
0

1
Step 11: Edit hadoop-env.sh and add the Java Path as mentioned below:

hadoop-env.sh contains the environment variables that are used in the


script to run Hadoop like Java home path, etc.

Command: vi hadoop–env.sh

76
Fig: Hadoop Installation – Configuring

hadoop-env.sh Step 12: Go to Hadoop home directory and

format the NameNode. Command: cd

Command: cd hadoop-2.7.3

Command: bin/hadoop namenode –format

Fig: Hadoop Installation – Formatting NameNode

This formats the HDFS via NameNode. This command is only executed
for the first time. Formatting the file system means initializing the
directory specified by the dfs.name.dir variable.

Never format, up and running Hadoop filesystem. You will lose all your
data stored in theHDFS.

Step 13: Once the NameNode is formatted, go to hadoop-2.7.3/sbin


directory and start all the daemons.

Command: cd hadoop-2.7.3/sbin

Either you can start all daemons with a single command or do it individually.

Command: ./start-all.sh

The above command is a combination of start-dfs.sh, start-yarn.sh &mr-


jobhistory- daemon.shOr you can run all the services individually as below:

77
Start NameNode:

The NameNode is the centerpiece of an HDFS file system. It keeps the


directory tree of all files stored in the HDFS and tracks all the file stored
across the cluster.

Command: ./hadoop-daemon.sh start namenode

78
79
StartDataNode:
On startup, a DataNode connects to the Namenode and it responds to the requests from the
Namenode for differentoperations.

Command: ./hadp-daemon.sh start datanode

Fig: Hadoop Installation – Starting DataNode

Start ResourceManager:

ResourceManager is the master that arbitrates all the available cluster resources and thus helps in
managing the distributed applications running on the YARN system. Its work is to manage
each NodeManagers and the each application’s ApplicationMaster.

Command: ./yarn-daemon.sh start resourcemanager

Fig: Hadoop Installation – Starting ResourceManager

Start NodeManager:
The NodeManager in each machine framework is the agent which is responsible for managing
containers, monitoring their resource usage and reporting the same to the ResourceManager.
80
Command: ./yarn-daemon.sh start nodemanager

Fig: Hadoop Installation – Starting NodeManager

Start JobHistoryServer:

JobHistoryServer is responsible for servicing all job history related requests from client.

Command: ./mr-jobhistory-daemon.sh start historyserver

Step 14: To check that all the Hadoop services are up and running, run the below command.

Command: jps

Fig: Hadoop Installation – Checking Daemons

81
Step 15: Now open the Mozilla browser and go

to localhost:50070/dfshealth.html to check the NameNode interface.

Fig: Hadoop Installation – Starting WebUI

Hence,successfully installed a single node Hadoop cluster.

82
Ex.NO :9 WRITE A WORD COUNT PROGRAM TO DEMONSTRATE THE USE OF

MAP AND REDUCE TASKS

Date:

Aim:

To develop a word count program to demonstrate the use of Map

Algorithm

Required software for Linux includes

1. Java™ must be installed. Recommended Java versions are described at


HadoopJavaVersions.
2. ssh must be installed and sshd must be running to use the Hadoop scripts that manage
remote Hadoopdaemons.
3. f your cluster doesn’t have the requisite software you will need to installit.
4. For example on Ubuntu Linux:
5. $ sudo apt-get installssh
6. $ sudo apt-get installrsync
7. Unpack the downloaded Hadoop distribution. In the distribution, edit the file
etc/hadoop/hadoop-env.sh to define some parameters asfollows:
8. # set to the root of your Java installation
9. exportJAVA_HOME=/usr/java/latest
10. Try the followingcommand:
11. $ bin/hadoop
12. e following example copies the unpacked conf directory to use as input and then finds
and displays every match of the given regular expression. Output is written to the given
outputdirectory.
13. $ mkdir input
14. $ cp etc/hadoop/*.xmlinput
15. $ bin/hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.2.jar grep
input output'dfs[a-z.]+'
16. $ catoutput/*
Program:

import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
importorg.apache.hadoop.fs.Path;

83
import org.apache.hadoop.io.IntWritable;
importorg.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
public static class TokenizerMapper
extends Mapper<Object, Text, Text,
IntWritable>{ private final static IntWritable one = new
IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException
{ StringTokenizer itr = new
StringTokenizer(value.toString()); while
(itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
public static class IntSumReducer
extends Reducer<Text,IntWritable,Text,IntWritable>
{ private IntWritable result = new IntWritable();

public void reduce(Text key, Iterable<IntWritable> values,


Context context
) throws IOException, InterruptedException
{ int sum = 0;
for (IntWritable val : values)
{ sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception
{ Configuration conf = new Configuration();

84
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}

Output:

$ bin/hadoop fs -ls /user/joe/wordcount/input/ /user/joe/wordcount/input/file01


/user/joe/wordcount/input/file02

$ bin/hadoop fs -cat /user/joe/wordcount/input/file01


Hello World Bye World

$ bin/hadoop fs -cat /user/joe/wordcount/input/file02


Hello Hadoop Goodbye Hadoop

Run the application:


$ bin/hadoop jar wc.jar WordCount /user/joe/wordcount/input /user/joe/wordcount/output

85
Result:
Thus the above application for setting up the one Hadoop cluster is executed successfully.

Ex.No:10 DEVELOP A NEW WEB APPLICATION FOR CALCULATOR


Date:

AIM:
To develop a Web application for performing arithmetic operation like calculator.

PROGRAM:

HTML:
<html>

<head>

<meta charset="utf-8">

<title>JavaSctipt Calculator | Web Dev Trick</title>

<link rel="stylesheet" href="style.css">

</head>

<body>

<div class="container">

<form name="form">

<div class="display">

<input type="text" placeholder="0" name="displayResult" />

</div>

<div class="buttons">

<div class="row">

<input type="button" name="b7" value="7" onClick="calcNumbers(b7.value)">


86
<input type="button" name="b8" value="8" onClick="calcNumbers(b8.value)">

<input type="button" name="b9" value="9" onClick="calcNumbers(b9.value)">

<input type="button" name="addb" value="+" onClick="calcNumbers(addb.value)">

</div>

<div class="row">

<input type="button" name="b4" value="4" onClick="calcNumbers(b4.value)">

<input type="button" name="b5" value="5" onClick="calcNumbers(b5.value)">

<input type="button" name="b6" value="6" onClick="calcNumbers(b6.value)">

<input type="button" name="subb" value="-" onClick="calcNumbers(subb.value)">

</div>

<div class="row">

<input type="button" name="b1" value="1" onClick="calcNumbers(b1.value)">

<input type="button" name="b2" value="2" onClick="calcNumbers(b2.value)">

<input type="button" name="b3" value="3" onClick="calcNumbers(b3.value)">

<input type="button" name="mulb" value="*" onClick="calcNumbers(mulb.value)">

</div>

<div class="row">

<input type="button" name="b0" value="0" onClick="calcNumbers(b0.value)">

<input type="button" name="potb" value="." onClick="calcNumbers(potb.value)">

<input type="button" name="divb" value="/" onClick="calcNumbers(divb.value)">

<input type="button" class="red" value="="


onClick="displayResult.value=eval(displayResult.value)">

87
</div>

</div>

</form>

</div>

</body>

</html>

CSS:
body,

html {

background: #ecedef;

margin: 0;

padding: 0;

.container {

position: fixed;

top: 50%;

left: 50%;

transform: translate(-50%, -50%);

background: #fff;

box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.2);

border-radius: 14px;

padding-bottom: 20px;

width: 320px;

88
}

.display {

width: 100%;

height: 60px;

padding: 40px 0;

background: #ff0509;

border-top-left-radius: 14px;

border-top-right-radius: 14px;

.buttons {

padding: 20px 20px 0 20px;

.row {

width: 280px;

float: left;

input[type="button"] {

width: 60px;

height: 60px;

float: left;

padding: 0;

margin: 5px;

box-sizing: border-box;

background: #ecedef;

border: none;

89
font-size: 30px;

line-height: 30px;

border-radius: 50%;

font-weight: 700;

color: #5e5858;

cursor: pointer;

input[type="text"] {

width: 270px;

height: 60px;

float: left;

padding: 0;

box-sizing: border-box;

border: none;

background: none;

color: #ffffff;

text-align: right;

font-weight: 700;

font-size: 60px;

line-height: 60px;

margin: 0 25px;

.red {

background: #ff0509 !important;

color: #ffffff !important;

90
}

JS:
function calcNumbers(result) {

form.displayResult.value = form.displayResult.value + result;

OUTPUT:

RESULT:
Thus the program for performing arithmetic operation using web service was successfully
executed.

91
Ex.No:11 DEVELOP A NEW WEB APPLICATION FOR DEVELOPING ONLINE
REGISTRATION FORM
Date:

AIM:
To develop a Web application for developing online registration form

PROGRAM:

HTML:
<!DOCTYPE html>
<!-- H5FormValidation.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML Form Input Validation Using HTML5</title>
</head>

<body>
<h2>HTML Form Input Validation Using HTML5</h2>

<form id="formTest" method="get" action="processData">


<table>
<tr>
<td><label for="txtName">Name<span class="required">*</span></label></td>
<td><input type="text" id="txtName" name="name" required autofocus></td>
</tr>
<tr>
<td><label for="txtAddress">Address</label></td>
<td><input type="text" id="txtAddress" name="address"></td>
</tr>
<tr>
<td><label for="txtZipcode">Zip Code<span class="required">*</span></label></td>
<td><input type="text" id="txtZipcode" name="zipcode"
placeholder="enter a 5-digit code"
required pattern="^\d{5}$"
oninvalid="this.setCustomValidity('Enter a 5-digit zipcode')"
oninput="setCustomValidity('')"></td>

92
</tr>
<tr>
<td>Country<span class="required">*</span></td>
<td><select id="selCountry" name="country" required>
<option value="" selected>Please select...</option>
<option value="AA">AA</option>
<option value="BB">BB</option>
<option value="CC">CC</option>
</select></td>
</tr>
<tr>
<td>Gender<span class="required">*</span></td>
<td><label><input type="radio" name="gender" value="m" required>Male</label>
<label><input type="radio" name="gender" value="f">Female</label></td>
</tr>
<tr>
<td>Preferences<span class="required">*</span></td>
<td><label><input type="checkbox" name="color" value="r">Red</label>
<label><input type="checkbox" name="color" value="g" checked>Green</label>
<label><input type="checkbox" name="color" value="b">Blue</label></td>
</tr>
<tr>
<td><label for="txtPhone">Phone<span class="required">*</span></label></td>
<td><input type="tel" id="txtPhone" name="phone" required></td>
</tr>
<tr>
<td><label for="txtEmail">Email<span class="required">*</span></label></td>
<td><input type="email" id="txtEmail" name="email" required></td>
</tr>
<tr>
<td><label for="txtPassword">Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPassword" name="password"
required pattern="^\w{6,8}$"
placeholder="6-8 characters"></td>
</tr>
<tr>
<td><label for="txtPWVerified">Verify Password<span
class="required">*</span></label></td>
<td><input type="password" id="txtPWVerified" name="pwVerified" required></td>
</tr>
<tr>
<td><label for="dateBirthday">Birthday<span class="required">*</span></label></td>
<td><input type="date" id="dateBirthday" name="birthday" required></td>
</tr>
<tr>
<td><label for="timeAppt">Appointment<span class="required">*</span></label></td>

93
<td><input type="time" id="timeAppt" name="appointment" required></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="SEND" id="btnSubmit">&nbsp;
<input type="reset" value="CLEAR" id="btnReset"></td>
</tr>
</table>
</form>
</body>
</html>

CSS:
<!DOCTYPE html>
<!-- JSFormValidation.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML Form Input Validation Using JavaScript</title>
<link rel="stylesheet" href="JSFormValidation.css">
<script src="JSFormValidation.js"></script>
</head>

<body>
<h2>HTML Form Input Validation Using JavaScript</h2>

<form id="formTest" method="get" action="processData">


<table>
<tr>
<td><label for="txtName">Name<span class="required">*</span></label></td>
<td><input type="text" id="txtName" name="name"></td>
<td id="elmNameError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td><label for="txtAddress">Address</label></td>
<td><input type="text" id="txtAddress" name="address"></td>
<td id="elmAddressError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td><label for="txtZipcode">Zip Code<span class="required">*</span></label></td>
<td><input type="text" id="txtZipcode" name="zipcode"></td>
<td id="elmZipcodeError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td>Country<span class="required">*</span></td>
<td><select id="selCountry" name="country">
<option value="" selected>Please select...</option>
<option value="AA">AA</option>
<option value="BB">BB</option>

94
<option value="CC">CC</option>
</select></td>
<td id="elmCountryError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td>Gender<span class="required">*</span></td>
<td><label><input type="radio" name="gender" value="m">Male</label>
<label><input type="radio" name="gender" value="f">Female</label></td>
<td id="elmGenderError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td>Preferences<span class="required">*</span></td>
<td><label><input type="checkbox" name="color" value="r">Red</label>
<label><input type="checkbox" name="color" value="g">Green</label>
<label><input type="checkbox" name="color" value="b">Blue</label></td>
<td id="elmColorError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td><label for="txtPhone">Phone<span class="required">*</span></label></td>
<td><input type="text" id="txtPhone" name="phone"></td>
<td id="elmPhoneError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td><label for="txtEmail">Email<span class="required">*</span></label></td>
<td><input type="text" id="txtEmail" name="email"></td>
<td id="elmEmailError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td><label for="txtPassword">Password (6-8 characters)<span
class="required">*</span></label></td>
<td><input type="password" id="txtPassword" name="password"></td>
<td id="elmPasswordError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td><label for="txtPWVerified">Verify Password<span
class="required">*</span></label></td>
<td><input type="password" id="txtPWVerified" name="pwVerified"></td>
<td id="elmPWVerifiedError" class="errorMsg">&nbsp;</td></tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="SEND" id="btnSubmit">&nbsp;
<input type="reset" value="CLEAR" id="btnReset"></td>
<td>&nbsp;</td></tr>
</table>
</form>
</body>
</html>

JS:
// JSFormValidation.js
/*

95
* Run init() after the page is loaded
*/
window.onload = init;

/*
* Initialization
*/
function init() {
// Bind "onsubmit" event handler to the "submit" button
document.getElementById("formTest").onsubmit = validateForm;
// Bind "onclick" event handler to "reset" button
document.getElementById("btnReset").onclick = clearForm;
// Set initial focus
document.getElementById("txtName").focus();
}

/*
* The "onsubmit" event handler to validate the input fields.
*
* Most of the input validation functions take 3 arguments:
* inputElm: Input element to be validated.
* errMsg: the error message to be displayed if validation fails.
* errElm: to place the error message
*
* @param theForm: the form to be validated
*/
function validateForm(theForm) {
with(theForm) {
// return false would prevent default submission
return (isNotEmpty(txtName, "Please enter your name!", elmNameError)
&& isNumeric(txtZipcode, "Please enter a 5-digit zip code!", elmZipcodeError)
&& isLengthMinMax(txtZipcode, 5, 5, "Please enter a 5-digit zip code!",
elmZipcodeError)
&& isSelected(selCountry, "Please make a selection!", elmCountryError)
&& isChecked("gender", "Please check a gender!", elmGenderError)
&& isChecked("color", "Please check a color!", elmColorError)
&& isNumeric(txtPhone, "Please enter a valid phone number!", elmPhoneError)
&& isValidEmail(txtEmail, "Enter a valid email!", elmEmailError)
&& isValidPassword(txtPassword, "Password shall be 6-8 characters!",
elmPasswordError)
&& verifyPassword(txtPassword, txtPWVerified, "Different from new password!",
elmPWVerifiedError)
);
}
}

96
/*
* Helper function, to be called after validation, to show or clear
* existing error message, and to set focus to the input element
* for correcting error.
* If isValid is false, show the errMsg on errElm, and place the
* focus on the inputElm for correcting the error.
* Else, clear previous errMsg on errElm, if any.
*
* @param isValid (boolean): flag indicating the result of validation
* @param errMsg (string)(optional): error message
* @param errElm (object)(optional): if isValid is false, show errMsg; else, clear.
* @param inputElm (object)(optional): set focus to this element,
* if isValid is false
*/
function postValidate(isValid, errMsg, errElm, inputElm) {
if (!isValid) {
// Show errMsg on errElm, if provided.
if (errElm !== undefined && errElm !== null
&& errMsg !== undefined && errMsg !== null) {
errElm.innerHTML = errMsg;
}
// Set focus on Input Element for correcting error, if provided.
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.add("errorBox"); // Add class for styling
inputElm.focus();
}
} else {
// Clear previous error message on errElm, if provided.
if (errElm !== undefined && errElm !== null) {
errElm.innerHTML = "";
}
if (inputElm !== undefined && inputElm !== null) {
inputElm.classList.remove("errorBox");
}
}
}

/*
* Validate that input value is not empty.
*
* @param inputElm (object): input element
* @param errMsg (string): error message
* @param errElm (object): element to place error message
*/
function isNotEmpty(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim() !== "");

97
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}

/* Validate that input value contains one or more digits */


function isNumeric(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^\d+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}

/* Validate that input value contains only one or more letters */


function isAlphabetic(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^[a-zA-Z]+$/) !== null) ;
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}

/* Validate that input value contains one or more digits or letters */


function isAlphanumeric(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^[0-9a-zA-Z]+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}

/* Validate that input value length is between minLength and maxLength */


function isLengthMinMax(inputElm, minLength, maxLength, errMsg, errElm) {
var inputValue = inputElm.value.trim();
var isValid = (inputValue.length >= minLength) && (inputValue.length <= maxLength);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}

// Validate that input value is a valid email address


function isValidEmail(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}

/*
* Validate that a selection is made (not default of "") in <select> input
*
* @param selectElm (object): the <select> element
*/

98
function isSelected(selectElm, errMsg, errElm) {
// You need to set the default value of <select>'s <option> to "".
var isValid = (selectElm.value !== ""); // value in selected <option>
postValidate(isValid, errMsg, errElm, selectElm);
return isValid;
}

/*
* Validate that one of the checkboxes or radio buttons is checked.
* Checkbox and radio are based on name attribute, not id.
*
* @param inputName (string): name attribute of the checkbox or radio
*/
function isChecked(inputName, errMsg, errElm) {
var elms = document.getElementsByName(inputName);
var isChecked = false;
for (var i = 0; i < elms.length; ++i) {
if (elms[i].checked) {
isChecked = true;
break;
}
}
postValidate(isChecked, errMsg, errElm, null); // no focus element
return isChecked;
}

// Validate password, 6-8 characters of [a-zA-Z0-9_]


function isValidPassword(inputElm, errMsg, errElm) {
var isValid = (inputElm.value.trim().match(/^\w{6,8}$/) !== null);
postValidate(isValid, errMsg, errElm, inputElm);
return isValid;
}

// Verify password.
function verifyPassword(pwElm, pwVerifiedElm, errMsg, errElm) {
var isTheSame = (pwElm.value === pwVerifiedElm.value);
postValidate(isTheSame, errMsg, errElm, pwVerifiedElm);
return isTheSame;
}

/*
* The "onclick" handler for the "reset" button to clear the display,
* including the previous error messages and error box.
*/
function clearForm() {
// Remove class "errorBox" from input elements

99
var elms = document.querySelectorAll('.errorBox'); // class
for (var i = 0; i < elms.length; i++) {
elms[i].classList.remove("errorBox");
}

// Remove previous error messages


elms = document.querySelectorAll('[id$="Error"]'); // id ends with Error
for (var i = 0; i < elms.length; i++) {
elms[i].innerHTML = "";
}

// Set initial focus


document.getElementById("txtName").focus();
}

OUTPUT:

RESULT:
The online registration was successfully developed.

100

You might also like