DIS Lab Manual
DIS Lab Manual
DIS Lab Manual
LABORATORY MANUAL
DISTRIBUTED SYSTEMS LAB
BE VII Semester (CBCS): 2020-21
NAME: ___________________________________________________________________
ROLL NO:__________________________________________________________________
BRANCH:__________________ SEM:______________________________________
VISION
To produce ethical, socially conscious and innovative professionals
who would contribute to sustainable technological development of the
society.
MISSION
To impart quality engineering education with latest technological
developments and interdisciplinary skills to make students succeed in
professional practice.
DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
LABORATORY MANUAL
Prepared
By
Dr. Vuppu Padmakar,
Associate Professor.
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND TECHNOLOGY
VISION
MISSION
PROGRAM OUTCOMES
Engineering graduates will be able to:
PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the
Engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations,
and give and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
PO12: Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.
At the end of 4 years, Computer Science and Engineering graduates at MCET will be
able to:
PSO1: Apply the knowledge of Computer Science and Engineering in various domains like
networking and data mining to manage projects in multidisciplinary environments.
PSO3: Design and develop solutions by following standard software engineering principles
and implement by using suitable programming languages and platforms
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND TECHNOLOGY
SEMESTER: VII
Taxonomy
CO No. Course Outcome
Level
PC752CS.1 Write programs that communicate data between two hosts Creating
PC752CS.2 Configure Network File Systems Understanding
PC752CS.3 Use distributed data processing frameworks and mobile
Applying
application tool kits
PC752CS.4 Trace Communication protocols in distributed systems Analyze
PC752CS.5 Develop an application using a technology from distributed
Creating
system
PC752CS.6 Design of algorithm distributed system Creating
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND TECHNOLOGY
a. Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab
session.
b. Laboratory Record updated up to the last session experiments.
c. Formal dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems,
which should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during
the lab sessions. Misuse of the equipment, misbehaviours with the staff and systems
etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out. If
anybody found loitering outside the lab / class without permission during working
hours will be treated seriously and punished appropriately.
10. Students should SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is
kept properly.
All students must observe the dress code while in the laboratory
Footwear is NOT allowed
Foods, drinks and smoking are NOT allowed
All bags must be left at the indicated place
The lab timetable must be strictly followed
Be PUNCTUAL for your laboratory session
All programs must be completed within the given time
Noise must be kept to a minimum
Workspace must be kept clean and tidy at all time
All students are liable for any damage to system due to their own negligence
Students are strictly PROHIBITED from taking out any items from the laboratory
Report immediately to the lab programmer if any damages to equipment
Lab In – charge
METHODIST
Estd:2008 COLLEGE OF ENGINEERING AND TECHNOLOGY
LIST OF EXPERIMENTS
SI.
Name of the Experiment Date of Date of Faculty
Page No
No. Experiment Submission Signature
SI.
Name of the Experiment Date of Date of Faculty
Page No
No. Experiment Submission Signature
Implementing Publish/Subscribe 48
8 paradigm using Web Services, ESB
and JMS
Introduction
Distributed Computing is a field of computer science that studies distributed systems. A distributed
syste is a model in which components located on networked computers communicate and
coordinate their actions by passing messages. The components interact with each other in order to
achieve a common goal. Thee significant characteristics of distributed systems are : concurrency of
components, lack of a global clock, and independent failure of components. Examples of distributed
systems vary from SOA-based systems to massively multiplayer online games to peer-to-peer
applications.
A computer program that runs in a distributed system is called a distributed program, and
distributed programmming is the process of writing such programs. There are many alternatives for
the message passing mechanism, including pure HTTP, RPC-like connectors and message queues.
A goal and challenge pursued by some computer scientists and practitioners in distributed systems
is location transparency; however, this goal has fallen out of favour in industry, as distributed
systems are different from conventional non-distributed systems, and the differences, such as
network partitions, partial system failures, and partial upgrades, cannot simply be “prepared over”
by attempts at “transparency”
Page 1
MCET DISTRIBUTED SYSTEMS LAB MANUAL
There are two main reasons for using distributed systems and distributed computing. First, the very
nature of the application may require the use of a communication network that connects several
computers. For example, data is produced in one physical location and it is needed in another
location.
Second, there are many cases in which the use of a single computer would be possible in principle,
but the use of a distributed system is beneficial for practical reasons. For example, it may be more
cost-efficient to obtain the desired level of performance by using a cluster of several low-end
computers, in comparison with a single high-end computer. A distributed system can be more
reliable than a non-distributed system, as there is no single point of failure. Moreover, a distributed
system may be easier to expand and manage than a monolithic uniprocessor system.
Examples of distributed systems and applications of distributed computing include the
following
Telecommunication networks:
Telephone networks and cellular networks
Computer networks such as the Internet.
Wireless sensor networks.
Routing algorithms
Network applications:
World Wide Web and peer-to-peer networks
Massively multiplayer online games and virtual reality communities
Distributed databases and distributed database management systems.
Network files systems.
Distributed information processing systems such as banking systems and airline reservation
systems
Real-time process control:
Aircraft control systems
Industrial control systems
Parallel computation:
Scientific computing, including cluster computing and grid computing and various volunteer
computing projects; see the list of distributed computing projects.
Page 2
MCET DISTRIBUTED SYSTEMS LAB MANUAL
FTP Client:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
class One extends JFrame implements ActionListener
{
/* ctrl space */
Page 3
MCET DISTRIBUTED SYSTEMS LAB MANUAL
b1=new JButton("Download");
l1=new JLabel("Downlaod a file");
lmsg2=new JLabel("");
setLayout(new GridLayout(2,3,10,10));
add(l);add(b);add(lmsg1);add(l1);add(b1);add(lmsg2);
b.addActionListener(this);
b1.addActionListener(this);
setVisible(true);
setSize(600,500);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
try {
/* String s=e.getActionCommand();
if(s.equals("Upload"))*/
if (b.getModel().isArmed())
{
Page 4
MCET DISTRIBUTED SYSTEMS LAB MANUAL
val=j.showOpenDialog(One.this);
String filename=j.getSelectedFile().getName();
String path=j.getSelectedFile().getPath();
if (b1.getModel().isArmed())
{
Socket s=new Socket("localhost",1010);
System.out.println("Client connected to server");
String remoteadd=s.getRemoteSocketAddress().toString();
System.out.println(remoteadd);
JFileChooser j1=new JFileChooser(remoteadd);
int val;
val=j1.showOpenDialog(One.this);
String filename=j1.getSelectedFile().getName();
String filepath=j1.getSelectedFile().getPath();
System.out.println("File name:"+filename);
PrintStream out=new PrintStream(s.getOutputStream());
out.println("Download");
out.println(filepath);
Page 5
MCET DISTRIBUTED SYSTEMS LAB MANUAL
}
public class FTPClient
{
public static void main(String[] args)
{
new One();
}
}
Page 6
MCET DISTRIBUTED SYSTEMS LAB MANUAL
FTP Server:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args)
{
try {
while (true)
{
ServerSocket ss=new ServerSocket(1010);
Socket sl=ss.accept();
System.out.println("Server scoket is created....");
System.out.println(" test1");
DataInputStream fromserver=new DataInputStream(sl.getInputStream());
System.out.println(" test2");
String option=fromserver.readLine();
if (option.equalsIgnoreCase("upload"))
{
System.out.println("upload test");
String filefromclient=fromserver.readLine();
File clientfile=new File(filefromclient);
Page 7
MCET DISTRIBUTED SYSTEMS LAB MANUAL
}
if (option.equalsIgnoreCase("download"))
{
System.out.println("download test");
String filefromclient=fromserver.readLine();
File clientfile=new File(filefromclient);
} //while
}
}
catch (Exception e)
{
System.out.println(e);
// TODO: handle exception
}
}
}
Page 8
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 9
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 10
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Aim: Develop a client server application which implements Name Server. Let the
client like a web browser sends a request containing a hostname, then a piece of software such
as name server resolver sends a request to the name server to obtain the IP address of a
hostname.
Description: Name server is a client / server network communication protocol. Name server clients
send request to the server while name servers send response to the client. Client request contain a
name which is converted into in IP address known as a forward name server lookups while requests
containing an IP address which is converted into a name known as reverse name server lookups.
Name server implements a distributed database to store the name of all the hosts available on the
internet. If a client like a web browser sends a request containing a hostname, then a piece of
software such as name server resolver sends a request to the name server to obtain the IP address of
a hostname. If name server does not contain the IP address associated with a hostname then it
forwards the request to another name server. It IP address has arrived at the resolver, which in turn
completes the request over the internet protocol.
Page 11
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Program:
import java.net.*;
import java.io.*;
import java.util.*;
public class DNS
{
public static void main(String[] args)
{
int n;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
do
{
System.out.println("\n Menu: \n 1. DNS 2. Reverse DNS 3. Exit \n");
System.out.println("\n Enter your choice");
n = Integer.parseInt(System.console().readLine());
if(n==1)
{
try
{
System.out.println("\n Enter Host Name ");
String hname=in.readLine();
InetAddress address;
address = InetAddress.getByName(hname);
System.out.println("Host Name: " + address.getHostName());
System.out.println("IP: " + address.getHostAddress());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
if(n==2)
{
try
{
Page 12
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 13
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Aim: To develop a client server application this implements Chat Server. Let the client side
request for message and the server side displays it and sends to the client.
Description: A client / server program into a fully functioning chat client / server. A simple server
that will accept a single client connection and display everything the client says on the screen. If the
client user’s types “OK” the client and the server will both quit. A server as before, but this time it
will remain open for additional connection once a client has quit. The server can handle at most one
connection at a time. A server as before but his time it can handle multiple clients simultaneously.
The output from all connected clients will appear on the server’s screen. A server as before, but his
time it sends all text received from any of the connected clients to all clients. This means that the
server has to receive and send the client has to send as well as receive.
Program:
CCLogin.java
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
Page 14
MCET DISTRIBUTED SYSTEMS LAB MANUAL
public CCLogin()
{
this.frame1 = new JFrame("Login Page");
this.tf = new JTextField(10);
this.button = new JButton("Login");
Page 15
MCET DISTRIBUTED SYSTEMS LAB MANUAL
c1.main(null);
}
catch(Exception localIOException)
{
}
}
}
EXPECTED OUTPUT:
ChatMultiServer:
import java.net.*;
import java.io.*;
class A implements Runnable
{
Thread t;
Socket s;
A(Socket x)
{
s=x;
t=new Thread(this);
t.start();
}
public void run()
{
try
{
/* Reading data from client */
InputStream is=s.getInputStream();
byte data[]=new byte[50];
is.read(data);
String mfc=new String(data);
Page 16
MCET DISTRIBUTED SYSTEMS LAB MANUAL
mfc=mfc.trim();
System.out.println(mfc);
class ChatMultiServer
{
static int c=0;
public static void main(String args[]) throws Exception
{
System.out.println("ServerSocket is creating");
ServerSocket ss=new ServerSocket(1010);
System.out.println("ServerSocket is created");
System.out.println("waiting for the client from the client");
while(true)
{
Socket s=ss.accept();
new A(s);
}
}
}
Page 17
MCET DISTRIBUTED SYSTEMS LAB MANUAL
EXPECTED OUTPUT:
Client1.java
import java.net.*;
import java.io.*;
class Client1
{
static String name="";
public Client1(String n)
{
name=n;
}
public static void main(String args[]) throws Exception
{
System.out.println("connecting to server");
System.out.println("client1 connected to server");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Page 18
MCET DISTRIBUTED SYSTEMS LAB MANUAL
}
}
}
EXPECTED OUTPUT:
Page 19
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Program:
Study of Network File Systems
1. Create a Folder nfs/abc.txt
2. Know the ipaddress
Applications->System Settings->Network—edit ( ipaddress, subnetmask)
(or) In terminal type ifconfig
3. Enable the desired services
1. System Services->Server Settings->Services
Network (Enable)
Nfs (Enable)
Iptables (Disable) (we do not firewalls)
2. System Settings ->Security Level (Firewall options-disable, Selinux-disable)
Page 20
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Index.py
@board.route('/')
def index():
join.py
import pymysql
@board.route('/join')
def join():
return render_template('join.html')
@board.route('/join_process', methods=['POST'])
def join_process():
Page 21
MCET DISTRIBUTED SYSTEMS LAB MANUAL
id = request.form['id']
password = request.form['password_1']
email = request.form['email']
db_address = current_app.config['DB_ADDRESS']
db_port = current_app.config['DB_PORT']
db_id = current_app.config['DB_ID']
db_password = current_app.config['DB_PASSWORD']
db_name = current_app.config['DB_NAME']
conn = pymysql.connect(host=db_address,
port=int(db_port),
user=db_id,
password=db_password,
db=db_name,
charset='utf8')
try:
cursor = conn.cursor()
sql = "INSERT INTO users(id, password, email) VALUES('%s', '%s', '%s')" % (id, password,
email)
cursor.execute(sql)
conn.commit()
finally:
conn.close()
Page 22
MCET DISTRIBUTED SYSTEMS LAB MANUAL
list.py
import pymysql
@board.route('/list', methods=['GET'])
def list():
page = request.args.get('page')
db_address = current_app.config['DB_ADDRESS']
db_port = current_app.config['DB_PORT']
db_id = current_app.config['DB_ID']
db_password = current_app.config['DB_PASSWORD']
db_name = current_app.config['DB_NAME']
conn = pymysql.connect(host=db_address,
port=int(db_port),
user=db_id,
password=db_password,
db=db_name,
charset='utf8')
try:
cursor = conn.cursor()
sql = "SELECT `no`, `content`, `writer`, `read` FROM board ORDER BY `write_time` DESC"
cursor.execute(sql)
rows = cursor.fetchall()
Page 23
MCET DISTRIBUTED SYSTEMS LAB MANUAL
finally:
conn.close()
login.py
import pymysql
def login_required(f):
@wraps(f)
try:
session_key = request.cookies.get(current_app.config['SESSION_COOKIE_NAME'])
print('session_key:[%s]' % session_key)
is_login = False
is_login = True
if not is_login:
except Exception as e:
Page 24
MCET DISTRIBUTED SYSTEMS LAB MANUAL
return decorated_function
@board.route('/login')
def login_page():
id = request.args.get('id', '')
return render_template('login.html')
@board.route('/login', methods=['POST'])
def login_process():
next_url = request.args.get('next')
id = request.form['id']
password = request.form['password']
db_address = current_app.config['DB_ADDRESS']
db_port = current_app.config['DB_PORT']
db_id = current_app.config['DB_ID']
db_password = current_app.config['DB_PASSWORD']
db_name = current_app.config['DB_NAME']
conn = pymysql.connect(host=db_address,
port=int(db_port),
user=db_id,
password=db_password,
db=db_name,
charset='utf8')
Page 25
MCET DISTRIBUTED SYSTEMS LAB MANUAL
try:
cursor = conn.cursor()
sql = "SELECT `usn`, `id`, `email`, `update_time` FROM users WHERE `id`='%s' AND
`password`='%s' LIMIT 1" % (id, password)
print(sql)
cursor.execute(sql)
rows = cursor.fetchall()
if rows:
session.parmanent = True
usn = row_data[0]
id = row_data[1]
email = row_data[2]
update_time = row_data[3]
session['usn'] = usn
session['user'] = id
session['email'] = email
return redirect(url_for(next_url))
else:
return redirect(url_for('.list'))
else:
Page 26
MCET DISTRIBUTED SYSTEMS LAB MANUAL
finally:
conn.close()
logout.py
@board.route('/logout')
def logout():
session.clear()
return redirect(url_for('.list'))
write.py
import pymysql
def write():
if request.method == 'POST':
writer = request.form['writer']
content = request.form['content']
else:
return render_template('write.html')
db_address = current_app.config['DB_ADDRESS']
Page 27
MCET DISTRIBUTED SYSTEMS LAB MANUAL
db_port = current_app.config['DB_PORT']
db_id = current_app.config['DB_ID']
db_password = current_app.config['DB_PASSWORD']
db_name = current_app.config['DB_NAME']
conn = pymysql.connect(host=db_address,
port=int(db_port),
user=db_id,
password=db_password,
db=db_name,
charset='utf8')
try:
cursor = conn.cursor()
print(sql)
cursor.execute(sql)
conn.commit()
finally:
conn.close()
return redirect(url_for('.list'))
Board_blueprint.py
board_config.py
Page 28
MCET DISTRIBUTED SYSTEMS LAB MANUAL
class FlaskBoardConfig(object):
DB_ADDRESS = ''
DB_PORT = ''
DB_ID = ''
DB_PASSWORD = ''
DB_NAME = ''
Board_logger.py
import logging
class Log:
__log_level_map = {
'debug' : logging.DEBUG,
'info' : logging.INFO,
'warn' : logging.WARN,
'error' : logging.ERROR,
'critical' : logging.CRITICAL
__my_logger = None
@staticmethod
Log.__my_logger = getLogger(logger_name);
Log.__my_logger.setLevel(Log.__log_level_map.get(log_level, 'warn'))
console_handler = logging.StreamHandler()
Page 29
MCET DISTRIBUTED SYSTEMS LAB MANUAL
console_handler.setFormatter(formatter)
Log.__my_logger.addHandler(console_handler)
file_handler = \
file_handler.setFormatter(formatter)
Log.__my_logger.addHandler(file_handler)
@staticmethod
def debug(msg):
Log.__my_logger.debug(msg)
@staticmethod
def info(msg):
Log.__my_logger.info(msg)
@staticmethod
def warn(msg):
Log.__my_logger.warn(msg)
@staticmethod
def error(msg):
Log.__my_logger.error(msg)
@staticmethod
def critical(msg):
Log.__my_logger.critical(msg)
Page 30
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Expected Output:
Page 31
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Program-6: Implement a word count application which counts the number of occurrences
of each words a large collection of documents Using Map Reduce model.
Aim: To develop to implement a word count application which counts the number of
occurrences of each words a large collection of documents Using Map Reduce model.
Description: In Hadoop, MapReduce is a computation that decomposes large manipulation jobs
into individual tasks that can be executed in parallel across a cluster of servers. The results of task
can be joined together to compute final results.
MapReduce consists of 2 steps:
Map Function – it takes a set of data and converts it into another set of data, where individual
elements are broken down into tuples (Key-Value pair)
Example - (Map function in word count)
Bus, Car, bus, car, train, car, bus, car, train, bus, TRAIN,BUS,
Input Set of data
buS, caR, CAR, car, BUS, TRAIN
Reduce Function –Takes the output from Map as an input and combines those data tuples
into a smaller set of tuples.
Example – (Reduce function in word count)
(BUS,7),
Converts
Output into smaller (CAR,7),
set of tuples
(TRAIN,4)
Page 32
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 33
MCET DISTRIBUTED SYSTEMS LAB MANUAL
package PackageDemo;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.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;
import org.apache.hadoop.util.GenericOptionsParser;
public class WordCount {
public static void main(String [] args) throws Exception
{
Configuration c=new Configuration();
String[] files=new GenericOptionsParser(c,args).getRemainingArgs();
Path input=new Path(files[0]);
Path output=new Path(files[1]);
Job j=new Job(c,"wordcount");
j.setJarByClass(WordCount.class);
j.setMapperClass(MapForWordCount.class);
j.setReducerClass(ReduceForWordCount.class);
j.setOutputKeyClass(Text.class);
j.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(j, input);
FileOutputFormat.setOutputPath(j, output);
System.exit(j.waitForCompletion(true)?0:1);
}
public static class MapForWordCount extends Mapper<LongWritable, Text, Text, IntWritable>{
public void map(LongWritable key, Text value, Context con) throws IOException,
InterruptedException
{
Page 34
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 35
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Expected Output
To move this into Hadoop directly, open the terminal and enter the following commands:
[training@localhost ~]$ hadoop fs -put wordcountFile wordCountFile
2. Run the jar file:
(Hadoop jar jarfilename.jar packageName.ClassName PathToInputTextFile
PathToOutputDirectry)
[training@localhost ~]$ hadoop jar MRProgramsDemo.jar PackageDemo.WordCount
wordCountFile MRDir1
3. Open the result:
[training@localhost ~]$ hadoop fs -ls MRDir1
Found 3 items
-rw-r--r-- 1 training supergroup 0 2016-02-23 03:36 /user/training/MRDir1/_SUCCESS
drwxr-xr-x - training supergroup 0 2016-02-23 03:36 /user/training/MRDir1/_logs
-rw-r--r-- 1 training supergroup 20 2016-02-23 03:36 /user/training/MRDir1/part-r-00000
[training@localhost ~]$ hadoop fs -cat MRDir1/part-r-00000
BUS 7
CAR 4
TRAIN 6
Result: A word count application which counts the number of occurrences of each word a large
collection of documents Using Map Reduce model was successfully developed.
Page 36
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Program-7: Develop an application (small game like scrabble, Tic-tac-Toe Using Android
SDK)
Aim & Description: Creating the Board, First step is to create the Board for the Tic-Tac-Toe
game. The Board class will store the elements of the grid in an array and will contain a Boolean
indicating if the game is ended or no.
The play method will let you to set the mark of the currentPlayer on the grid at a given (x, y)
position. A changePlayer method will be used to change the current player for the next play. Besides,
a computer method is defined to let the user to randomly place a mark on the grid. Finally, we define
a checkEnd method to check if the game is ended. The game is ended if there is a winner or a draw:
all the cases of the grids are filled and no one wins the game.
This gives us the following code for the Board class:
package com.ssaurel.tictactoe;
import java.util.Random;
public class Board {
private static final Random RANDOM = new Random();
private char[] elts;
private char currentPlayer;
private boolean ended;
public Board() {
elts = new char[9];
newGame();
}
public boolean isEnded() {
return ended;
}
public char play(int x, int y) {
if (!ended && elts[3 * y + x] == ' ') {
elts[3 * y + x] = currentPlayer;
changePlayer();
}
return checkEnd();
}
public void changePlayer() {
currentPlayer = (currentPlayer == 'X' ? 'O' : 'X');
Page 37
MCET DISTRIBUTED SYSTEMS LAB MANUAL
}
public char getElt(int x, int y) {
return elts[3 * y + x];
}
public void newGame() {
for (int i = 0; i < elts.length; i++) {
elts[i] = ' ';
}
currentPlayer = 'X';
ended = false;
}
public char checkEnd() {
for (int i = 0; i < 3; i++) {
if (getElt(i, 0) != ' ' &&
getElt(i, 0) == getElt(i, 1) &&
getElt(i, 1) == getElt(i, 2)) {
ended = true;
return getElt(i, 0);
}
if (getElt(0, i) != ' ' &&
getElt(0, i) == getElt(1, i) &&
getElt(1, i) == getElt(2, i)) {
ended = true;
return getElt(0, i);
}
}
if (getElt(0, 0) != ' ' &&
getElt(0, 0) == getElt(1, 1) &&
getElt(1, 1) == getElt(2, 2)) {
ended = true;
return getElt(0, 0);
}
if (getElt(2, 0) != ' ' &&
getElt(2, 0) == getElt(1, 1) &&
getElt(1, 1) == getElt(0, 2)) {
Page 38
MCET DISTRIBUTED SYSTEMS LAB MANUAL
ended = true;
return getElt(2, 0);
}
for (int i = 0; i < 9; i++) {
if (elts[i] == ' ')
return ' ';
}
return 'T';
}
public char computer() {
if (!ended) {
int position = -1;
do {
position = RANDOM.nextInt(9);
} while (elts[position] != ' ');
elts[position] = currentPlayer;
changePlayer();
}
return checkEnd();
}
}
Rendering the Board on the Screen
Next step is to create a BoardView class to render our Board on the screen. Our BoardView will
extend the View class and we will draw the Board and its elements on the Canvas object associated.
It is a good way to discover how to draw simple shapes on a Canvas of a specific View too.
Furthermore, we must manage the touch events of the users on the Board to let it to play to our Tic-
Tac-Toe game. For that, we override the on TouchEvent method from the View parent class. In that
method, we convert a point touched on the screen to a case on our grid. Then, we make the play on
the Board object. After that, we need to call the gameEnded method of the parent activity if the game
is ended to display the win dialog to the user. If not, we make the play for the computer. Like you
can see, the heart of the logic game will be located in this method.
This gives us the following code for the BoardView object :
package com.ssaurel.tictactoe;
import android.content.Context;
Page 39
MCET DISTRIBUTED SYSTEMS LAB MANUAL
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class BoardView extends View {
private static final int LINE_THICK = 5;
private static final int ELT_MARGIN = 20;
private static final int ELT_STROKE_WIDTH = 15;
private int width, height, eltW, eltH;
private Paint gridPaint, oPaint, xPaint;
private GameEngine gameEngine;
private MainActivity activity;
public BoardView(Context context) {
super(context);
}
public BoardView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
gridPaint = new Paint();
oPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
oPaint.setColor(Color.RED);
oPaint.setStyle(Paint.Style.STROKE);
oPaint.setStrokeWidth(ELT_STROKE_WIDTH);
xPaint = new Paint(oPaint);
xPaint.setColor(Color.BLUE);
}
public void setMainActivity(MainActivity a) {
activity = a;
}
public void setGameEngine(GameEngine g) {
gameEngine = g;
}
@Override
Page 40
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 41
MCET DISTRIBUTED SYSTEMS LAB MANUAL
} else if (c == 'X') {
float startX = (eltW * x) + ELT_MARGIN;
float startY = (eltH * y) + ELT_MARGIN;
float endX = startX + eltW - ELT_MARGIN * 2;
float endY = startY + eltH - ELT_MARGIN;
canvas.drawLine(startX, startY, endX, endY, xPaint);
float startX2 = (eltW * (x + 1)) - ELT_MARGIN;
Page 42
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 43
MCET DISTRIBUTED SYSTEMS LAB MANUAL
android:title="New Game"
app:showAsAction="always" />
</menu>
package com.ssaurel.tictactoe;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import static com.ssaurel.tictactoe.R.id.board;
public class MainActivity extends AppCompatActivity {
private BoardView boardView;
private GameEngine gameEngine;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boardView = (BoardView) findViewById(board);
gameEngine = new GameEngine();
boardView.setGameEngine(gameEngine);
boardView.setMainActivity(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Page 44
MCET DISTRIBUTED SYSTEMS LAB MANUAL
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_new_game) {
newGame();
}
return super.onOptionsItemSelected(item);
}
public void gameEnded(char c) {
String msg = (c == 'T') ? "Game Ended. Tie" : "GameEnded. " + c + " win";
new AlertDialog.Builder(this).setTitle("Tic Tac Toe").
setMessage(msg).
setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
newGame();
}
}).show();
}
private void newGame() {
gameEngine.newGame();
boardView.invalidate();
}
}
Page 45
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Expected Output:
Page 46
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 47
MCET DISTRIBUTED SYSTEMS LAB MANUAL
ADDITIONAL PROGRAMS
PROGRAM-8
Aim: Implementing Publish/Subscribe Paradigm using Web Services, ESB and JMS
Description: JMS supports two models for messaging as follows:
Queues: point-to-point
Topics: publish and subscribe
There are many business use cases that can be implemented using the publisher-subscriber pattern.
For example, consider a blog with subscribed readers. The blog author posts a blog entry, which the
subscribers of that blog can view. In other words, the blog author publishes a message (the blog
post content) and the subscribers (the blog readers) receive that message. Popular publisher /
subscriber patterns like these can be implemented using JMS topics as described in the following
Configuring the broker server
Configuring the publisher
Configuring the subscribers
Publishing the topic
Page 48
MCET DISTRIBUTED SYSTEMS LAB MANUAL
topic.MyTopic = example.MyTopic
topic.SimpleStockQuoteService = SimpleStockQuoteService
2. Next, add a proxy service named StockQuoteProxy and configure it to publish to the
topic SimpleStockQuoteService. You can add the proxy service to the ESB using the management
console, either by building the proxy service in the design view or by copying the XML
configuration into the source view. Alternatively, you can add an XML file
named StockQuoteProxy.xml to <ESB_HOME>/repository/deployment/server/synapse-configs/
default/ proxy-services. A sample XML code segment that defines the proxy service is given below.
Notice that the address URI specifies properties for configuring the JMS transport
<definitions xmlns="http://ws.apache.org/ns/synapse">
<proxy name="StockQuoteProxy"
transports="http"
startOnLoad="true"
trace="disable">
<target>
<endpoint>
<address
uri="jms:/SimpleStockQuoteService?transport.jms.ConnectionFactoryJNDIName=TopicConnection
Factory&java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory
&java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=topic"/>
</endpoint>
<inSequence>
<property name="OUT_ONLY" value="true"/>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
</proxy>
</definitions>
Page 49
MCET DISTRIBUTED SYSTEMS LAB MANUAL
<definitions xmlns="http://ws.apache.org/ns/synapse">
<proxy name="SimpleStockQuoteService1"
transports="jms"
startOnLoad="true"
trace="disable">
<description/>
<target>
<inSequence>
<property name="OUT_ONLY" value="true"/>
<log level="custom">
<property name="Subscriber1" value="I am Subscriber1"/>
</log>
<drop/>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
<parameter name="transport.jms.ContentType">
<rules>
<jmsProperty>contentType</jmsProperty>
<default>application/xml</default>
</rules>
</parameter>
<parameter name="transport.jms.ConnectionFactory">myTopicConnectionFactory</parameter>
<parameter name="transport.jms.DestinationType">topic</parameter>
<parameter name="transport.jms.Destination">SimpleStockQuoteService</parameter>
</proxy>
<proxy name="SimpleStockQuoteService2"
transports="jms"
Page 50
MCET DISTRIBUTED SYSTEMS LAB MANUAL
startOnLoad="true"
trace="disable">
<description/>
<target>
<inSequence>
<property name="OUT_ONLY" value="true"/>
<log level="custom">
<property name="Subscriber2" value="I am Subscriber2"/>
</log>
<drop/>
</inSequence>
<outSequence>
<send/>
</outSequence>
</target>
<parameter name="transport.jms.ContentType">
<rules>
<jmsProperty>contentType</jmsProperty>
<default>application/xml</default>
</rules>
</parameter>
<parameter name="transport.jms.ConnectionFactory">myTopicConnectionFactory</parameter>
<parameter name="transport.jms.DestinationType">topic</parameter>
<parameter name="transport.jms.Destination">SimpleStockQuoteService</parameter>
</proxy>
</definitions>
Next, you configure two proxy services that subscribe to the JMS topic SimpleStockQuoteService,
so that whenever this topic receives a message, it is sent to these subscribing proxy services.
Following is the sample configuration for these proxy services.
Publishing to the topic
Start the ESB with one of the following commands:
<ESB_HOME>/bin/wso2server.sh (on Linux)
<MB_HOME>/bin/wso2server.bat (on Windows)
Page 51
MCET DISTRIBUTED SYSTEMS LAB MANUAL
INFO {org.wso2.andes.server.store.CassandraMessageStore} -
To invoke the publisher, use the sample stockquote client service by navigating
to <ESB_HOME>/samples/axis2Client and running the following command:
ant stockquote -Daddurl=http://localhost:8280/services/StockQuoteProxy -Dmode=placeorder -
Dsymbol=MSFT
Result : Implementing Publish/Subscribe Paradigm using Web Services, ESB and JMS is
successfully executed
Page 52
MCET DISTRIBUTED SYSTEMS LAB MANUAL
PROGRAM-9
Page 53
MCET DISTRIBUTED SYSTEMS LAB MANUAL
VIVA Questions:
Page 54
MCET DISTRIBUTED SYSTEMS LAB MANUAL
Page 55