Java J2EE Classroom Reference Guide
Java J2EE Classroom Reference Guide
Java 1.8
This documentation is for
reference purpose only
and is for those who have
attended the classroom
sessions at
Thinking Machines.
• During your classroom session appropriate theory needs to be
written against each example.
• You are required to bring this book daily for your classroom
sessions.
}
Generalized event notification system & creating abstract class to impose guidelines.
[Link] (will not compile)
// Assume that the following code is being written in year 2016
abstract class BulbEventListener
{
abstract public void wattageChanged(int oldWattage,int newWattage);
}
class Bulb
{
private int wattage;
private BulbEventListener bulbEventListener;
public void setBulbEventListener(BulbEventListener bulbEventListener)
{
[Link]=bulbEventListener;
}
public void setWattage(int wattage)
{
if(wattage!=[Link])
{
int oldWattage=[Link];
[Link]=wattage;
if([Link]!=null)
{
[Link](oldWattage,[Link]);
}
}
}
public int getWattage()
{
return [Link];
}
}
// Assume that the following code is being written after year 2016
class WattageChangedLogger
{
}
class EG2App
{
public static void main(String kk[])
{
Bulb b1=new Bulb();
WattageChangedLogger wcl=new WattageChangedLogger();
[Link](wcl);
[Link](60);
[Link](120);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 7
[Link](120);
[Link](0);
}
}
[Link] (will not compile)
// Assume that the following code is being written in year 2016
abstract class BulbEventListener
{
abstract public void wattageChanged(int oldWattage,int newWattage);
}
class Bulb
{
private int wattage;
private BulbEventListener bulbEventListener;
public void setBulbEventListener(BulbEventListener bulbEventListener)
{
[Link]=bulbEventListener;
}
public void setWattage(int wattage)
{
if(wattage!=[Link])
{
int oldWattage=[Link];
[Link]=wattage;
if([Link]!=null)
{
[Link](oldWattage,[Link]);
}
}
}
public int getWattage()
{
return [Link];
}
}
// Assume that the following code is being written after year 2016
class WattageChangedLogger extends BulbEventListener
{
}
class EG2App
{
public static void main(String kk[])
{
Bulb b1=new Bulb();
WattageChangedLogger wcl=new WattageChangedLogger();
[Link](wcl);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 8
[Link](60);
[Link](120);
[Link](120);
[Link](0);
}
}
[Link] (will compile)
// Assume that the following code is being written in year 2016
abstract class BulbEventListener
{
abstract public void wattageChanged(int oldWattage,int newWattage);
}
class Bulb
{
private int wattage;
private BulbEventListener bulbEventListener;
public void setBulbEventListener(BulbEventListener bulbEventListener)
{
[Link]=bulbEventListener;
}
public void setWattage(int wattage)
{
if(wattage!=[Link])
{
int oldWattage=[Link];
[Link]=wattage;
if([Link]!=null)
{
[Link](oldWattage,[Link]);
}
}
}
public int getWattage()
{
return [Link];
}
}
// Assume that the following code is being written after year 2016
class WattageChangedLogger extends BulbEventListener
{
public void wattageChanged(int oldWattage,int newWattage)
{
[Link]("Wattage change from %d to %d\n",oldWattage,newWattage);
}
}
class EG2App
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 9
{
public static void main(String kk[])
{
Bulb b1=new Bulb();
WattageChangedLogger wcl=new WattageChangedLogger();
[Link](wcl);
[Link](60);
[Link](120);
[Link](120);
[Link](0);
}
}
Problems associated with creating abstract class to impose guidelines
What if the programmer of WattageChangedLogger class wants to extend the WattageChangedLogger
class from another class. He cannot do so as java doesn't support Multiple Inheritance. In such scenario
extending an abstract class seems to be a burden which might not be acceptable in some scenarios. The
creators of java introduced the feature of creating interface to impose guidelines.
}
[Link] (will not compile)
interface aaaa
{
public void john(); // correct
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 10
}
class bbb implements aaaa // wrong
{
}
abstract class ccc implements aaaa // correct
{
}
class ddd implements aaaa // correct
{
public void john()
{
// some code or whatever is required
}
public void tom()
{
// whatever
}
}
[Link] (will not compile)
interface aaaa
{
public void john(); // correct
}
class psp
{
public static void main(String gg[])
{
aaaa a; // correct
a=new aaaa(); // incorrect
}
}
[Link] (will not compile)
interface aaaa
{
public void john(); // correct
}
class bbb implements aaaa // correct
{
public void john()
{
// some code or whatever is required
}
public void tom()
{
// whatever
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 11
}
}
class ccc extends bbb
{
// some functions
}
class ddd
{
public void john()
{
// some code
}
}
class psp
{
public static void main(String gg[])
{
aaaa a; // correct
a=new bbb(); // correct
[Link](); // correct
[Link](); // incorrect
a=new ccc(); // correct
a=new ddd(); // incorrect
}
}
Some more cases
Assume that the implemented interfaces and extended classes exist
class jjjj extends pqr implements aaaa // correct
}
class bbb implements aaaa
{
public void tom()
{
x=20; // wrong
x=10; // wrong
}
}
[Link] (will not compile)
interface aaaa
{
public void sam()
{
[Link]("Great");
}
}
[Link] (will compile)
interface aaaa
{
default public void sam()
{
[Link]("Great");
}
}class bbb implements aaaa
{
public void tom()
{
[Link]("Cool");
}
}
class EG3App
{
public static void main(String kk[])
{
aaaa a=new bbb();
[Link]();
}
}
[Link] (will compile)
interface aaaa
{
default public void sam()
{
[Link]("Great");
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 13
char m;
[Link]("Enter a character : ");
try
{
m=(char)[Link]();
[Link](m);
}catch(IOException ioException)
{
[Link](ioException);
}
}
}
[Link] (will compile)
import [Link].*;
class EG6App
{
public static void main(String kk[])
{
InputStreamReader isr;
isr=new InputStreamReader([Link]);
BufferedReader br;
br=new BufferedReader(isr);
char m;
[Link]("Enter a character : ");
try
{
m=(char)[Link]();
[Link](m);
}catch(IOException ioException)
{
[Link](ioException);
}
char t;
[Link]("Enter another character : ");
try
{
t=(char)[Link]();
}catch(IOException ioException)
{
[Link](ioException);
}
}
}
[Link] (will compile)
import [Link].*;
class EG7App
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 15
{
public static void main(String kk[])
{
InputStreamReader isr;
isr=new InputStreamReader([Link]);
BufferedReader br;
br=new BufferedReader(isr);
char m;
[Link]("Enter a character : ");
try
{
m=(char)[Link]();
while([Link]()) [Link]();
[Link](m);
}catch(IOException ioException)
{
[Link](ioException);
}
char t;
[Link]("Enter another character : ");
try
{
t=(char)[Link]();
while([Link]()) [Link]();
}catch(IOException ioException)
{
[Link](ioException);
}
String k;
[Link]("Enter a string : ");
try
{
k=[Link]();
[Link](k);
}catch(IOException ioException)
{
[Link](ioException);
}
}
}
Generalized Keyboard class
[Link] (will compile)
import [Link].*;
class Keyboard
{
private static BufferedReader bufferedReader=new BufferedReader(new
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 16
InputStreamReader([Link]));
private Keyboard()
{
}
public static char readCharacter()
{
char m=' ';
try
{
m=(char)[Link]();
while([Link]())
{
[Link]();
}
}catch(IOException ioException)
{
}
return m;
}
public static char readCharacter(String message)
{
[Link](message);
return readCharacter();
}
public static int readInteger()
{
return [Link](readString());
}
public static int readInteger(String message)
{
[Link](message);
return readInteger();
}
public static double readDouble()
{
return [Link](readString());
}
public static double readDouble(String message)
{
[Link](message);
return readDouble();
}
public static String readString()
{
String m="";
try
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 17
{
m=[Link]();
}catch(IOException ioException) {}
return m;
}
public static String readString(String message)
{
[Link](message);
return readString();
}
/* write implementations for
readLong()
readShort()
readByte()
readDouble()
readFloat()
readBoolean()
overload all the above to accept a string as message
*/
}
class EG8App
{
public static void main(String gg[])
{
char a;
a=[Link]("Enter a character : ");
[Link](a);
char b=[Link]("Enter another character : ");
[Link](b);
int x;
x=[Link]("Enter a number : ");
[Link]("Enter another number : ");
int y;
y=[Link]();
int z=x+y;
[Link]("Total is %d\n",z);
String g;
g=[Link]("Enter a string :");
[Link](g);
}
}
Predefined Scanner class
[Link] (will compile)
import [Link].*;
class EG9App
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 18
}
int code=[Link](data[0]);
String name=data[1];
int salary=[Link](data[2]);
try
{
File f=new File("[Link]");
if([Link]()==false)
{
[Link]("Invalid code");
return;
}
RandomAccessFile raf;
raf=new RandomAccessFile(f,"rw");
if([Link]()==0)
{
[Link]("Invalid code");
[Link]();
return;
}
int vCode;
String vName;
int vSalary;
boolean found=false;
while([Link]()<[Link]())
{
vCode=[Link]([Link]());
vName=[Link]();
vSalary=[Link]([Link]());
if(vCode==code)
{
found=true;
break;
}
}
if(found==false)
{
[Link]();
[Link]("Invalid code");
return;
}
[Link](0); // seek will move the internal file pointer to desired location
File tmpFile=new File("[Link]");
if([Link]())
{
[Link]();
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 21
{
File f=new File("[Link]");
if([Link]()==false)
{
[Link]("Invalid code");
return;
}
RandomAccessFile raf;
raf=new RandomAccessFile(f,"rw");
if([Link]()==0)
{
[Link]("Invalid code");
[Link]();
return;
}
int vCode;
String vName;
int vSalary;
boolean found=false;
while([Link]()<[Link]())
{
vCode=[Link]([Link]());
vName=[Link]();
vSalary=[Link]([Link]());
if(vCode==code)
{
found=true;
break;
}
}
if(found==false)
{
[Link]();
[Link]("Invalid code");
return;
}
[Link](0); // seek will move the internal file pointer to desired location
File tmpFile=new File("[Link]");
if([Link]())
{
[Link]();
}
RandomAccessFile tmpraf=new RandomAccessFile(tmpFile,"rw");
while([Link]()<[Link]())
{
vCode=[Link]([Link]());
vName=[Link]();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 23
vSalary=[Link]([Link]());
if(code!=vCode)
{
[Link](vCode+"\n"+vName+"\n"+vSalary+"\n");
}
}
[Link](0);
[Link](0);
while([Link]()<[Link]())
{
[Link]([Link]()+"\n");
}
[Link]([Link]());
[Link](0);
[Link]();
[Link]();
[Link]("Employee deleted.....");
}catch(Exception exception)
{
[Link](exception);
}
}
}
[Link] (will compile)
import [Link].*;
class GetEmployee
{
public static void main(String data[])
{
if([Link]!=1)
{
[Link]("Invalid use of module : GetEmployee");
[Link]("Usage : java GetEmployee code");
return;
}
int code=[Link](data[0]);
try
{
File f;
f=new File("[Link]");
if([Link]()==false)
{
[Link]("Invalid employee code");
return;
}
RandomAccessFile raf;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 24
raf=new RandomAccessFile(f,"rw");
if([Link]()==0)
{
[Link]();
[Link]("Invalid employee code");
return;
}
int vCode;
String vName;
int vSalary;
while([Link]()<[Link]())
{
vCode=[Link]([Link]());
vName=[Link]();
vSalary=[Link]([Link]());
if(vCode==code)
{
[Link]();
[Link]("Name : "+vName);
[Link]("Salary : "+vSalary);
return;
}
}
[Link]();
[Link]("Invalid employee code");
}catch(IOException ioException)
{
[Link]("Problem : "+[Link]());
}
}
}
RDBMS (SQLite)
Download [Link] and [Link]
Unzip the contents from [Link] and copy the contents to c:\sqlite3 folder.
Copy the [Link] to c:\sqlite3 folder
set PATH=c:\windows;c:\windows\system32;c:\jdk1.8\bin;c:\sqlite3
create a folder named as sqleg on c:\
Now while staying in c:\sqleg folder, create a database using the following statement
sqlite3 [Link]
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 25
sqlite prompt will appear, type the following sql statements and terminate them with ;
Note down all the results in your copy, even if it takes a long time to do that. It is necessary to
understand sql statements once and for all.
.headers on
This page has been intentionally left blank for SQL Statements.
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 27
This page has been intentionally left blank for SQL Statements.
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 28
JDBC
[Link] (will compile)
import [Link].*;
class jdbc1
{
public static void main(String gg[])
{
try
{
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:sqlite:[Link]");
Statement s=[Link]();
[Link]("insert into item values(101,'Screw','Nos')");
[Link]();
[Link]();
[Link]("Record added");
}catch(Exception e)
{
[Link](e);
}
}
}
compile the above code using (javac [Link])
You should see the record that we added from a java code
Now create the following java file to update record
[Link] (will compile)
import [Link].*;
class jdbc2
{
public static void main(String gg[])
{
try
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 29
{
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:sqlite:[Link]");
Statement s=[Link]();
[Link]("update item set name='Computer',unit_of_measurement='Packet' where code=101");
[Link]();
[Link]();
[Link]("Record updated");
}catch(Exception e)
{
[Link](e);
}
}
}
to compile (javac [Link])
you should see a message (record updated) now go into sqlite3 and check if the record has been
updated or not.
Type the following code to delete a record
Now let us make the values dynamic by accepting them as command line arguments
[Link] (will compile)
import [Link].*;
class jdbc4
{
public static void main(String data[])
{
try
{
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:sqlite:[Link]");
Statement s=[Link]();
[Link]("insert into item values("+data[0]+",'"+data[1]+"','"+data[2]+"')");
[Link]();
[Link]();
[Link]("Record added");
}catch(Exception e)
{
[Link](e);
}
}
}
compile the above code using (javac [Link])
for execution
java -classpath c:\sqlite3\sqlite;.jar jdbc4 101 Screw Packet
[Link]();
[Link]("Record updated");
}catch(Exception e)
{
[Link](e);
}
}
}
compile and run as learnt earlier
[Link] (will compile)
import [Link].*;
class jdbc6
{
public static void main(String data[])
{
try
{
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:sqlite:[Link]");
Statement s=[Link]();
[Link]("delete from item where code="+data[0]);
[Link]();
[Link]();
[Link]("Record deleted");
}catch(Exception e)
{
[Link](e);
}
}
}
[Link] (will compile)
import [Link].*;
class jdbc7
{
public static void main(String data[])
{
try
{
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:sqlite:[Link]");
Statement s=[Link]();
ResultSet r;
r=[Link]("select * from item");
int vCode;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 32
String vName;
String vUOM;
while([Link]())
{
vCode=[Link]("code");
vName=[Link]("name").trim();
vUOM=[Link]("unit_of_measurement").trim();
[Link](vCode+","+vName+","+vUOM);
}
[Link]();
[Link]();
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}
Now let us learn joins
create the following 3 tables (country,state and city using the following SQL statements)
following is the SQLite dump for sql statement, understand the basics yourself
C:\sqleg>sqlite3 [Link]
SQLite version [Link] 2012-12-19 20:39:10
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 33
2|U.P.|1|India
3|Maharashtra|1|India
4|Punjab|2|Pakistan
sqlite> select [Link] as "city",[Link] as "state",[Link] as "countr
y" from city,state,country
...> ;
sqlite> insert into city values(1,'Ujjain',1);
sqlite> insert into city values(2,'Indore',1);
sqlite> insert into city values(3,'Mumbai',3);
sqlite> insert into city values(4,'Pune',3);
sqlite> insert into city values(5,'Satara',3);
sqlite> select [Link] as "city",[Link] as "state",[Link] as "countr
y" from city,state,country
...> ;
city|state|country
Ujjain|M.P.|India
Ujjain|U.P.|India
Ujjain|Maharashtra|India
Ujjain|Punjab|India
Indore|M.P.|India
Indore|U.P.|India
Indore|Maharashtra|India
Indore|Punjab|India
Mumbai|M.P.|India
Mumbai|U.P.|India
Mumbai|Maharashtra|India
Mumbai|Punjab|India
Pune|M.P.|India
Pune|U.P.|India
Pune|Maharashtra|India
Pune|Punjab|India
Satara|M.P.|India
Satara|U.P.|India
Satara|Maharashtra|India
Satara|Punjab|India
Ujjain|M.P.|Pakistan
Ujjain|U.P.|Pakistan
Ujjain|Maharashtra|Pakistan
Ujjain|Punjab|Pakistan
Indore|M.P.|Pakistan
Indore|U.P.|Pakistan
Indore|Maharashtra|Pakistan
Indore|Punjab|Pakistan
Mumbai|M.P.|Pakistan
Mumbai|U.P.|Pakistan
Mumbai|Maharashtra|Pakistan
Mumbai|Punjab|Pakistan
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 35
Pune|M.P.|Pakistan
Pune|U.P.|Pakistan
Pune|Maharashtra|Pakistan
Pune|Punjab|Pakistan
Satara|M.P.|Pakistan
Satara|U.P.|Pakistan
Satara|Maharashtra|Pakistan
Satara|Punjab|Pakistan
sqlite> select [Link] as "city",[Link] as "state",[Link] as "countr
y" from city,state,country where city.state_code=[Link] and state.country_co
de=[Link];
city|state|country
Ujjain|M.P.|India
Indore|M.P.|India
Mumbai|Maharashtra|India
Pune|Maharashtra|India
Satara|Maharashtra|India
sqlite>
sqlite> select count(*) from city;
5
sqlite> select count(*) from city where state_code=3;
3
sqlite> select count(*) from city where state_code=(select code from state where
name='M.P.');
2
sqlite> select name from state where code not in (select state_code from city);
U.P.
Punjab
sqlite>
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 36
MySQL
Install MySql.
While installing don't change the default port number (3306) and for root user assign your surname as
root password.
Locate the installation folder of MySQL Server. (It must be under Program Files or Program Files (x86)
folder, in the MySQL Server installation folder there must be a bin folder, in the bin folder resides the
[Link] (the Command Line Interface client tool to connect to the MySQL Server).
Now copy the [Link] to c:\mysqleg (or add the path upto the bin folder that contains the [Link]
to the PATH environment variable)
Note : replace kelkar with whatever is your root password. Also note that there is not space after -u and
-p.
If everything is correct, you should see the mysql prompt as shown below.
Note : End all the SQL Statements with a semicolon (;). Till you don't type semicolon, all the
statements are stored in buffer by mysql and when the semicolon is provided in the end, the collected
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 37
statement is fired.
Now let us create a user account named as tmdbuser with password also as tmdbuser, for that type
Now let us grant all the rights of the ThinkingMachinesDB to tmdbuser, for that type
Now again login, but this time as tmdbuser, for that type
If everything was done properly, you should see the mysql prompt, now to select the database type
use ThinkingMachinesDB
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 38
Note : you can create individual sql statement in a separate file using any plain text editor (for example
[Link] which contains the sql statement to create item table) and then on mysql prompt you can type
source [Link]
To get list of tables, you can type
show tables;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 39
Now let us create triggers to update the item table whenever insert/update/delete operations are
performed on sale_item and purchase_item tables.
First of all quit from tmdbuser login, then login as root user using (mysql -uroot -pyoursurname)
grant super on *.* to 'tmdbuser'@'%'
now quit from root user
Create a file named as [Link] with following sql statements.
[Link]
create trigger sale_item_insert after insert on sale_item for each row
begin
update item set total_sales=total_sales+[Link],closing_stock=closing_stock-[Link] where
code=new.item_code;
end;//
create trigger sale_item_delete after delete on sale_item for each row
begin
update item set total_sales=total_sales-[Link],closing_stock=closing_stock+[Link] where
code=old.item_code;
end;//
create trigger sale_item_update after update on sale_item for each row
begin
update item set total_sales=total_sales-[Link],closing_stock=closing_stock+[Link] where
code=old.item_code;
update item set total_sales=total_sales+[Link],closing_stock=closing_stock-[Link] where
code=new.item_code;
end;//
create trigger purchase_item_insert after insert on purchase_item for each row
begin
update item set
total_purchases=total_purchases+[Link],closing_stock=closing_stock+[Link] where
code=new.item_code;
end;//
create trigger purchase_item_delete after delete on purchase_item for each row
begin
update item set total_purchases=total_purchases-[Link],closing_stock=closing_stock-[Link]
where code=old.item_code;
end;//
create trigger purchase_item_update after update on purchase_item for each row
begin
update item set total_purchases=total_purchases-[Link],closing_stock=closing_stock-[Link]
where code=old.item_code;
update item set
total_purchases=total_purchases+[Link],closing_stock=closing_stock+[Link] where
code=new.item_code;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 40
end;//
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 41
customer_data.sql
insert into customer (name) values ('Sameer');
insert into customer (name) values ('Rakesh');
insert into customer (name) values ('Mohan');
Login into mysql using (tmdbuser) and type (source customer_data.sql) to insert records
Now view the records from item table using (select * from customer), note down the codes of the
inserted records, in my case it is (1 to 3)
supplier_data.sql
insert into supplier (name) values ('Sam');
insert into supplier (name) values ('Tom');
insert into supplier (name) values ('John');
insert into supplier (name) values ('Joy');
insert into supplier (name) values ('Tony');
Login into mysql using (tmdbuser) and type (source supplier_data.sql) to insert records
Now view the records from item table using (select * from supplier), note down the codes of the
inserted records, in my case it is (1 to 5)
Following are the records at my end
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 43
Now you need to insert record in sale table, get the bill_number assigned to the inserted record and
then insert some records in sale_item table and then see the effect of trigger on item table.
Then update some records of the sale_item table and again see the effect of trigger on item table
Then delete some records of the sale_item table and again see the effect of trigger on item table
Similarly perform more operations as per your requirement. I am pasting all the sql statements fired by
me as follows.
Now you do some calculations to check of the records of item table has correct information. Everything
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 47
is correct at my end.
Now let us create some views.
Note : I will be creating separate sql files, I assume that you already know how to run its contents.
sale_view.sql
create view sale_view
as
select sale.bill_number,sale.bill_date,sale.customer_code,[Link],sum(quantity*rate) as
bill_amount from
sale,customer,sale_item where sale.customer_code=[Link] and
sale.bill_number=sale_item.bill_number
group by sale.bill_number,sale.bill_date,sale.customer_code;
After creating the view you can type
select * from sale_view
purchase_view.sql
create view purchase_view
as
select
purchase.reference_number,purchase.bill_number,purchase.bill_date,purchase.supplier_code,supplier.n
ame,sum(quantity*rate) as bill_amount from
purchase,supplier,purchase_item where purchase.supplier_code=[Link] and
purchase.reference_number=purchase_item.reference_number
group by purchase.reference_number,purchase.bill_number,purchase.bill_date,purchase.supplier_code;
After creating the view you can type
select * from purchase_view
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 48
sale_bill_item_view.sql
create view sale_bill_item_view
as
select
sale_item.bill_number,sale_item.item_code,[Link],sale_item.quantity,sale_item.rate,sale_item.quan
tity*sale_item.rate as amount from
sale_item inner join item on sale_item.item_code=[Link] order by sale_item.bill_number;
After creating the view you can type
select * from sale_bill_item_view
purchase_bill_item_view.sql
create view purchase_bill_item_view
as
select
purchase_item.reference_number,purchase_item.item_code,[Link],purchase_item.quantity,purchas
e_item.rate,purchase_item.quantity*purchase_item.rate as amount from
purchase_item inner join item on purchase_item.item_code=[Link] order by
purchase_item.reference_number;
After creating the view you can type
select * from purchase_bill_item_view
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 49
Now let us write a java code to print all information about sale bills.
[Link](1,billNumber);
r2=[Link]();
sno=0;
while([Link]())
{
sno++;
itemCode=[Link]("item_code");
itemName=[Link]("name").trim();
quantity=[Link]("quantity");
rate=[Link]("rate");
amount=[Link]("amount");
[Link]("%3d %-45s %7d %7d %10d\n",sno,itemName+"
("+itemCode+")",quantity,rate,amount);
}
[Link]();
[Link]();
[Link]("-------------------------------------------------------------------------------");
[Link]("%64s : %10d\n","Total",billAmount);
[Link]("-------------------------------------------------------------------------------");
}
[Link]();
[Link]();
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}
to run the above code, type
java -classpath c:\mysql\*;. jdbc8
Do something similar to print all purchase bill data with reference number.
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 51
{
[Link]("Customer inserted successfully with code as : "+customerCode);
}
}catch(Exception e)
{
[Link](e);
}
}
}
compile the above code and to run type
java -classpath c:\mysql\*;. Jdbc9 someName
Note : replace someName with name of your choice, try adding duplicate name and see what happens
Now let us create function to update customer
update_customer.sql
create function update_customer(oldName char(50),newName char(50)) returns boolean
Begin
declare updated Boolean default true;
declare v_code int;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION set updated=false;
select code into v_code from customer where name=oldName limit 1;
if v_code is NULL then
set updated=false;
else
update customer set name=newName where code=v_code;
end if;
return updated;
end; //
To run, first login into mysql (tmdbuser)
then type
delimiter //
then type
source update_customer.sql
then type
delimiter ;
java code to call update_customer function
[Link] (will compile)
import [Link].*;
class jdbc10
{
public static void main(String data[])
{
try
{
String oldName=data[0];
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 53
String newName=data[1];
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:mysql://localhost:3306/ThinkingMachinesDB","tmdbuser","tm
dbuser");
CallableStatement cs=[Link]("{? = call update_customer(?,?)}");
[Link](1,[Link]);
[Link](2,oldName);
[Link](3,newName);
[Link]();
Boolean updated=[Link](1);
[Link]();
if(!updated)
{
[Link]("Customer not updated");
}
else
{
[Link]("Customer updated");
}
}catch(Exception e)
{
[Link](e);
}
}
}
Compile & Run the above code. (Pass 2 arguments – oldName and newName). You can then drop
function update_customer and then recreate it to accept code and newName instead of oldName and
newName and then modify the jdbc code to pass customerCode and newName as arguments.
Similarly create (delete_customer.sql with delete_customer function) and jdbc code to call the
delete_customer function. The function should accept customerCode as argument.
Now let us create a procedure
Create a file named as add_supplier.sql
add_supplier.sql
create procedure add_supplier(v_name char(50))
Begin
declare cnt int default 0;
select count(*) into cnt from supplier where name=v_name;
if cnt>0 then
signal SQLSTATE '45000' set MESSAGE_TEXT = 'Supplier exists';
else
insert into supplier (name) values(v_name);
end if;
end; //
login into mysql (tmdbuser)
then type
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 54
delimiter //
then type
source add_supplier.sql
then type
delimiter ;
then type
call add_supplier('Varun');
then type
call add_supplier('Shankar');
then type
call add_supplier('Varun');
you should see the error message (Supplier Exists)
Now the jdbc code to call the procedure.
[Link] (will compile)
import [Link].*;
class jdbc11
{
public static void main(String data[])
{
Connection c=null;
try
{
String name=data[0];
[Link]("[Link]");
c=[Link]("jdbc:mysql://localhost:3306/ThinkingMachinesDB","tmdbuser","tm
dbuser");
CallableStatement cs=[Link]("{call add_supplier(?)}");
[Link](1,name);
[Link]();
[Link]("Supplier added");
}catch(Exception e)
{
[Link](e);
}
finally
{
try
{
[Link]();
}catch(Exception m)
{
[Link](m);
}
}
}
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 55
Compile the above code and run as done earlier. Add some supplier and try adding duplicate suppliers
and you should see the message, SQLException : Supplier Exists
creating scrollable and updatable ResultSet
[Link] (will compile)
import [Link].*;
class jdbc12
{
public static void main(String kk[])
{
Connection c=null;
try
{
[Link]("[Link]");
c=[Link]("jdbc:mysql://localhost:3306/ThinkingMachinesDB","tmdbuser","tm
dbuser");
Statement s=[Link]();
ResultSet r=[Link]("select * from item order by name");
int code;
String name;
boolean b;
b=[Link]();
[Link](b);
if(b)
{
code=[Link]("code");
name=[Link]("name").trim();
[Link]("Code %d, Name %s\n",code,name);
}
b=[Link]();
[Link](b);
if(b)
{
code=[Link]("code");
name=[Link]("name").trim();
[Link]("Code %d, Name %s\n",code,name);
}
b=[Link]();
[Link](b);
if(b)
{
code=[Link]("code");
name=[Link]("name").trim();
[Link]("Code %d, Name %s\n",code,name);
}
b=[Link]();
[Link](b);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 56
if(b)
{
code=[Link]("code");
name=[Link]("name").trim();
[Link]("Code %d, Name %s\n",code,name);
}
[Link]();
[Link]();
}catch(Exception e)
{
[Link](e);
}
finally
{
try
{
[Link]();
}catch(Exception m)
{
[Link](m);
}
}
}
}
[Link] (will compile)
import [Link].*;
import [Link].*;
class jdbc13
{
public static void main(String gg[])
{
Connection c=null;
try
{
[Link]("[Link]");
c=[Link]("jdbc:mysql://localhost:3306/ThinkingMachinesDB","tmdbuser","tm
dbuser");
Statement s=[Link]();
[Link]("insert into item (name) values('Laptop')");
[Link]("insert into item (name) values('Pen Drive')");
[Link]("insert into item (name) values('Sharpner')");
[Link]("insert into item (name) values('Eraser')");
[Link]("insert into item (name) values('Pen')");
[Link]("insert into item (name) values('Ink Bottle')");
[Link]("insert into item (name) values('Scale')");
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 57
[Link]();
}
}
[Link]();
[Link]();
[Link]("After Updation");
s=[Link]();
r=[Link]("select * from item");
while([Link]())
{
code=[Link]("code");
name = [Link]("name").trim();
[Link]("Code : %d, Name %s\n",code,name);
}
[Link]();
[Link]();
}catch(Exception e)
{
[Link](e);
}
finally
{
try
{
[Link]();
}catch(Exception m)
{
[Link](m);
}
}
}
}
Backing up MySQL Database
[Link] (will compile)
import [Link].*;
class jdbc14
{
public static void main(String kk[])
{
String baseDirectory=null;
Connection c=null;
try
{
[Link]("[Link]");
c=[Link]("jdbc:mysql://localhost:3306/ThinkingMachinesDB","tmdbuser","tm
dbuser");
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 59
Statement s=[Link]();
ResultSet r=[Link]("select @@BASEDIR as base_directory");
if([Link]())
{
baseDirectory=[Link]("base_directory").trim();
}
[Link]();
[Link]();
}catch(Exception e)
{
[Link](e);
}
finally
{
try
{
[Link]();
}catch(Exception m)
{
[Link](m);
}
if(baseDirectory==null)
{
[Link]("Cannot extract information about MySql");
}
else
{
[Link](baseDirectory);
}
}
}
}
[Link] (will compile)
import [Link].*;
import [Link].*;
class jdbc15
{
public static void main(String data[])
{
String backupFileName=data[0];
String baseDirectory=null;
Connection c=null;
try
{
[Link]("[Link]");
c=[Link]("jdbc:mysql://localhost:3306/ThinkingMachinesDB","tmdbuser","tm
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 60
dbuser");
Statement s=[Link]();
ResultSet r=[Link]("select @@BASEDIR as base_directory");
if([Link]())
{
baseDirectory=[Link]("base_directory").trim();
}
[Link]();
[Link]();
}catch(Exception e)
{
[Link](e);
}
finally
{
try
{
[Link]();
}catch(Exception m)
{
[Link](m);
}
if(baseDirectory==null)
{
[Link]("Cannot extract information about MySql, hence cannot take backup.");
return;
}
baseDirectory=baseDirectory;
File outputFile=new File(backupFileName);
if([Link]()) [Link]();
File errorFile=new File("[Link]");
if([Link]()) [Link]();
String command=baseDirectory+"bin/[Link]";
ProcessBuilder processBuilder=new ProcessBuilder(command,"-uroot","-
pkelkar","ThinkingMachinesDB");
[Link](outputFile);
[Link](errorFile);
try
{
Process process=[Link]();
if([Link]()==false)
{
[Link]("Unable to take backup, view [Link] for errors");
}
else
{
[Link]("Backup taken");
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 61
}
}catch(Exception e)
{
[Link](e);
}
}
}
}
Run the above code, pass file name in which you want to take backup for eg.
java -classpath c:\mysql\*;. jdbc15 [Link]
If everything is correct, then the [Link] file will be created, which can be used later on to restore
database.
Ideally in a project, we will generate the backup file name dynamically using date time etc.
Restoring from backup file
I am assuming that you have taken backup in [Link]
First of all let us drop the ThinkingMachinesDB, for that login into mysql (root user) and type
drop database ThinkingMachinesDB;
to verify, type
use ThinkingMachinesDB;
you should get an error message
Now type
create database ThinkingMachinesDB;
then type
using ThinkingMachinesDB;
then type
source [Link];
Done, your database has been restored, you can exit from mysql, login as tmdbuser and check the
restored records.
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 62
}
}
}
Note : run this code many times, every time change the load factor on OS (run many apps in parallel)
[Link] (will compile)
class aaa implements Runnable
{
aaa()
{
Thread t;
t=new Thread(this);
[Link](); // the run will be loaded on a separate Thread to which (t) is pointing
}
public void run()
{
for(int j=2001;j<=2200;j++)
{
[Link](j+" ");
}
}
}
// When we write java psp, JVM creates a thread and loads the
// entry point function on it
class psp
{
public static void main(String gg[])
{
aaa a;
a=new aaa();
int x;
x=1;
while(x<=200)
{
[Link](x+" ");
x++;
}
}
}
Run this code many times as discussed earlier
[Link] (will compile)
class aaa extends Thread
{
aaa()
{
start();
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 64
{
private cmn cc;
private String ss;
worker(cmn c,String s)
{
cc=c;
ss=s;
start();
}
public void run()
{
[Link](ss);
}
}
class thread5
{
public static void main(String gg[])
{
cmn c=new cmn();
worker w1=new worker(c,"Hello");
worker w2=new worker(c,"Boys");
worker w3=new worker(c,"Girls");
}
}
Run this code many times as done earlier
[Link] (will compile)
// Solution to the previous problem
class cmn
{
private String m;
synchronized public void sam(String g)
{
m=g;
[Link](m);
try{
[Link](1000); // Thread goes to sleep for 1 second(1000 milliseconds)
}catch(InterruptedException ie)
{
}
[Link](m);
}
}
class worker extends Thread
{
private cmn cc;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 66
cc=c;
ss=s;
start();
}
public void run()
{
synchronized(cc)
{
[Link](ss);
}
}
}
class thread7
{
public static void main(String gg[])
{
cmn c=new cmn();
worker w1=new worker(c,"Hello");
worker w2=new worker(c,"Boys");
worker w3=new worker(c,"Girls");
}
}
Classic producer / consumer scenario and synchronization
Run this code many times as done earlier
[Link] (will compile)
class mdm
{
private int num;
public void setNumber(int n)
{
num=n;
[Link]("Produced : "+num);
}
public int getNumber()
{
[Link]("Consumed : "+num);
return num;
}
}
class Producer extends Thread
{
private mdm m;
Producer(mdm m)
{
this.m=m;
start();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 68
}
public void run()
{
for(int x=201;x<=250;x++)
{
[Link](x);
}
}
}
class Consumer extends Thread
{
private mdm m;
Consumer(mdm m)
{
this.m=m;
start();
}
public void run()
{
int e,f;
for(e=1;e<=50;e++)
{
f=[Link]();
}
}
}
class thread8
{
public static void main(String gg[])
{
mdm m=new mdm();
Producer p=new Producer(m);
Consumer c=new Consumer(m);
}
}
Run this code many times as done earlier
[Link] (will compile)
class mdm
{
private int num;
private boolean b=false;
synchronized public void setNumber(int n)
{
if(b==true)
{
try
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 69
{
wait();
}catch(InterruptedException ie)
{
}
}
num=n;
[Link]("Produced : "+num);
b=true;
notify();
}
synchronized public int getNumber()
{
if(b==false)
{
try
{
wait();
}catch(InterruptedException ie)
{
}
}
[Link]("Consumed : "+num);
b=false;
notify();
return num;
}
}
class Producer extends Thread
{
private mdm m;
Producer(mdm m)
{
this.m=m;
start();
}
public void run()
{
for(int x=201;x<=250;x++)
{
[Link](x);
}
}
}
class Consumer extends Thread
{
private mdm m;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 70
Consumer(mdm m)
{
this.m=m;
start(); }
public void run()
{
int e,f;
for(e=1;e<=50;e++)
{
f=[Link]();
}
}
}
class thread9
{
public static void main(String gg[])
{
mdm m=new mdm();
Producer p=new Producer(m);
Consumer c=new Consumer(m);
}
}
Local inner classes
[Link] (will compile)
class aaa
{
private int x;
aaa(int e)
{
x=e;
}
public void joy()
{
[Link]("I am joy of class aaa");
}
public void sam()
{
class bbb
{
public void joy()
{
[Link]("I am joy of local inner class bbb");
}
public void tiger()
{
[Link](x);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 71
[Link]();
[Link]();
}
}
bbb b=new bbb();
[Link]();
}
}
class inner1
{
public static void main(String gg[])
{
aaa a=new aaa(20);
[Link]();
}
}
Inner classes
[Link] (will compile)
class aaa
{
private int x;
class bbb
{
public void joy()
{
[Link]("I am joy of inner class bbb");
}
public void tiger()
{
[Link](x);
[Link]();
[Link]();
}
}
aaa(int e)
{
x=e;
}
public void joy()
{
[Link]("I am joy of class aaa");
}
public void sam()
{
bbb b=new bbb();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 72
[Link]();
}
public void lion()
{
bbb b=new bbb();
[Link]();
}
}
class inner2
{
public static void main(String gg[])
{
aaa a=new aaa(20);
[Link]();
[Link]();
}
}
[Link] (will not compile)
class aaa
{
private int x;
class bbb
{
public void joy()
{
[Link]("I am joy of inner class bbb");
}
public void tiger()
{
[Link](x);
[Link]();
[Link]();
}
}
aaa(int e)
{
x=e;
}
public void joy()
{
[Link]("I am joy of class aaa");
}
public void sam()
{
bbb b=new bbb();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 73
[Link]();
}
public void lion()
{
bbb b=new bbb();
[Link]();
}
}
class inner3
{
public static void main(String gg[])
{
[Link] b=new [Link]();
}
}
[Link] (will not compile)
class aaa
{
private int x;
static class bbb
{
public void joy()
{
[Link]("I am joy of inner class bbb");
}
public void tiger()
{
[Link](x);
[Link]();
[Link]();
}
}
aaa(int e)
{
x=e;
}
public void joy()
{
[Link]("I am joy of class aaa");
}
public void sam()
{
bbb b=new bbb();
[Link]();
}
public void lion()
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 74
{
bbb b=new bbb();
[Link]();
}
}
class inner4
{
public static void main(String gg[])
{
[Link] b=new [Link]();
}
}
[Link] (will compile)
class aaa
{
private int x;
static class bbb
{
public void joy()
{
[Link]("I am joy of inner class bbb");
}
public void tiger()
{
[Link]();
}
}
aaa(int e)
{
x=e;
}
public void joy()
{
[Link]("I am joy of class aaa");
}
public void sam()
{
bbb b=new bbb();
[Link]();
}
public void lion()
{
bbb b=new bbb();
[Link]();
}
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 75
class inner5
{
public static void main(String gg[])
{
[Link] b=new [Link]();
[Link]();
}
}
Anonymous classes
[Link] (will compile)
class aaa
{
public void sam()
{
[Link]("Cool");
}
public void toy()
{
[Link]("great");
}
}
class anonymous1
{
public static void main(String gg[])
{
aaa a=new aaa(){
public void tom()
{
[Link]("Really great");
}
};
[Link]();
[Link]();
}
}
[Link] (will not compile)
abstract class aaa
{
abstract public void sam();
}
class anonymous2
{
public static void main(String gg[])
{
aaa a=new aaa(){
public void tiger()
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 76
{
[Link]("Cool");
}
};
}
}
[Link] (will compile)
abstract class aaa
{
abstract public void sam();
}
interface bbb
{
public void lion();
}
class anonymous3
{
public static void main(String gg[])
{
aaa a=new aaa(){
public void tiger()
{
[Link]("Cool");
}
public void sam()
{
[Link]("Great");
}
};
bbb b=new bbb(){
public void lion()
{
[Link]("Really great");
}
};
[Link]();
[Link]();
}
}
[Link] (will compile)
class anonymous4
{
public static void main(String gg[])
{
Runnable r=new Runnable(){
public void run()
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 77
{
for(int j=2001;j<=2200;j++)
{
[Link](j+" ");
}
}
};
Thread t=new Thread(r);
[Link]();
int x;
x=1;
while(x<=200)
{
[Link](x+" ");
x++;
}
}
}
[Link] (will compile)
class anonymous5
{
public static void main(String gg[])
{
Thread t=new Thread(){
public void run()
{
for(int j=2001;j<=2200;j++)
{
[Link](j+" ");
}
}
};
[Link]();
int x;
x=1;
while(x<=200)
{
[Link](x+" ");
x++;
}
}
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 78
Lambda
[Link] (will compile)
interface Host
{
public void welcome(String name);
}
interface FeeCalculator
{
public int getCourseFee(String course);
}
class lambda1
{
public static void main(String gg[])
{
Host indianHost=(message)-> { [Link]("Namaste %s\n",message);};
Host americanHost=(message)-> { [Link]("Hello %s\n",message);};
[Link]("Sameer");
[Link]("Sameer");
FeeCalculator javaCourse=(course)->{
if([Link]("Java")) return 10000;
};
}
}
[Link] (will compile)
interface calculator
{
public int calculate(int num1,int num2);
}
class lambda2
{
public static void main(String gg[])
{
calculator add=(number1,number2)->number1+number2;
calculator substract=(number1,number2)->number1-number2;
calculator multiply=(number1,number2)->number1*number2;
calculator divide=(number1,number2)->number1/number2;
[Link]("Total is %d\n",[Link](10,2));
[Link]("Difference is %d\n",[Link](10,2));
[Link]("Product is is %d\n",[Link](10,2));
[Link]("Quotient is %d\n",[Link](10,2));
}
}
[Link] (will not compile)
interface calculator
{
public int calculate(int num1,int num2);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 79
}
class lambda3
{
public static void main(String gg[])
{
calculator add=(number1,number2)-> return number1+number2;
calculator substract=(number1,number2)-> return number1-number2;
calculator multiply=(number1,number2)-> return number1*number2;
calculator divide=(number1,number2)-> return number1/number2;
[Link]("Total is %d\n",[Link](10,2));
[Link]("Difference is %d\n",[Link](10,2));
[Link]("Product is is %d\n",[Link](10,2));
[Link]("Quotient is %d\n",[Link](10,2));
}
}
[Link] (will compile)
interface calculator
{
public int calculate(int num1,int num2);
}
class lambda4
{
public static void main(String gg[])
{
calculator add=(number1,number2)-> { return number1+number2; };
calculator substract=(number1,number2)-> { return number1-number2; };
calculator multiply=(number1,number2)-> { return number1*number2; };
calculator divide=(number1,number2)-> { return number1/number2; };
[Link]("Total is %d\n",[Link](10,2));
[Link]("Difference is %d\n",[Link](10,2));
[Link]("Product is is %d\n",[Link](10,2));
[Link]("Quotient is %d\n",[Link](10,2));
}
}
Multithreading – Concurrency - The new technique.
[Link] (will compile)
class concurr1
{
public static void main(String gg[])
{
Runnable r=()->{
for(int y=301;y<=350;y++)
{
[Link](y+" ");
}
};
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 80
[Link]();
}
}
Note : After running the following code, wait for some time, don't press Control C
Concurrency – Callable interface & Future task
[Link] (will compile)
import [Link].*;
class concurr4
{
public static void main(String gg[])
{
Callable<Integer> work=()->{
[Link](10);
return 5000;
};
ExecutorService es=[Link]();
Future<Integer> future=[Link](work);
[Link]([Link]());
try
{
[Link]([Link]());
}catch(Exception ie)
{
[Link](ie);
}
[Link]([Link]());
[Link]();
}
}
Concurrency – Thread Pools
[Link] (will compile)
import [Link].*;
class mdm
{
private String m;
public void sam(String g)
{
m=g;
[Link](m);
try
{
[Link](1000);
}catch(InterruptedException ie)
{
}
[Link](m);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 82
}
}
class concurr5
{
public static void main(String gg[])
{
String s1="Hello";
String s2="Boys";
String s3="Girls";
mdm c=new mdm();
ExecutorService es;
es=[Link](3);
Runnable r1=()->{
synchronized(c) { [Link](s1); }
};
Runnable r2=()->{
synchronized(c) { [Link](s2); }
};
Runnable r3=()->{
synchronized(c) { [Link](s3); }
};
[Link](r1);
[Link](r2);
[Link](r3);
[Link]();
}
}
Concurrency – Locks
[Link] (will compile)
import [Link].*;
import [Link].*;
class mdm
{
private String m;
ReentrantLock lock=new ReentrantLock();
public void sam(String g)
{
[Link]();
m=g;
[Link](m);
try
{
[Link](1000);
}catch(InterruptedException ie)
{
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 83
[Link](m);
[Link]();
}
}
class concurr6
{
public static void main(String gg[])
{
String s1="Hello";
String s2="Boys";
String s3="Girls";
mdm c=new mdm();
ExecutorService es;
es=[Link](3);
Runnable r1=()->{
[Link](s1);
};
Runnable r2=()->{
[Link](s2);
};
Runnable r3=()->{
[Link](s3);
};
[Link](r1);
[Link](r2);
[Link](r3);
[Link]();
}
}
Object Serialization / Deserialization
[Link] (will compile)
import [Link].*;
class Student
{
int rollNumber;
String name;
public void setRollNumber(int rollNumber) { [Link]=rollNumber; }
public int getRollNumber() { return [Link]; }
public void setName(String name) { [Link]=name; }
public String getName() { return [Link]; }
}
class serialize1
{
public static void main(String gkk[])
{
try
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 84
{
Student s1=new Student();
[Link](101);
[Link]("Sameer");
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
[Link](s1);
[Link]();
byte bytes[];
bytes=[Link]();
[Link]("Object serialized to byte array of length : "+[Link]);
}catch(Exception e)
{
[Link](e);
}
}
}
[Link] (will compile)
import [Link].*;
class Student implements Serializable
{
int rollNumber;
String name;
public void setRollNumber(int rollNumber) { [Link]=rollNumber; }
public int getRollNumber() { return [Link]; }
public void setName(String name) { [Link]=name; }
public String getName() { return [Link]; }
}
class serialize2
{
public static void main(String gkk[])
{
try
{
Student s1=new Student();
[Link](101);
[Link]("Sameer");
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
[Link](s1);
[Link]();
byte bytes[];
bytes=[Link]();
[Link]("Object serialized to byte array of length : "+[Link]);
ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
ObjectInputStream ois=new ObjectInputStream(bais);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 85
Student s2=(Student)[Link]();
[Link]("Byte array data deserialized");
[Link]("Roll number %d, Name %s\n",[Link](),[Link]());
if(s1==s2)
{
[Link]("Same object");
}
else
{
[Link]("Another object");
}
}catch(Exception e)
{
[Link](e);
}
}
}
[Link] (will compile)
import [Link].*;
class Country implements Serializable
{
private int code;
private String name;
public void setName(String name)
{
[Link]=name;
}
public void setCode(int code)
{
[Link]=code;
}
public String getName()
{
return [Link];
}
public int getCode()
{
return [Link];
}
}
class State implements Serializable
{
private int code;
private String name;
private Country country;
public void setName(String name)
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 86
{
[Link]=name;
}
public void setCode(int code)
{
[Link]=code;
}
public String getName()
{
return [Link];
}
public int getCode()
{
return [Link];
}
public void setCountry(Country country)
{
[Link]=country;
}
public Country getCountry()
{
return [Link];
}
}
class City implements Serializable
{
private int code;
private String name;
private State state;
public void setName(String name)
{
[Link]=name;
}
public void setCode(int code)
{
[Link]=code;
}
public String getName()
{
return [Link];
}
public int getCode()
{
return [Link];
}
public void setState(State state)
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 87
[Link]=state;
}
public State getState()
{
return [Link];
}
}
class Category implements Serializable
{
private int code;
private String name;
public void setName(String name)
{
[Link]=name;
}
public void setCode(int code)
{
[Link]=code;
}
public String getName()
{
return [Link];
}
public int getCode()
{
return [Link];
}
}
class Branch implements Serializable
{
private int code;
private String name;
public void setName(String name)
{
[Link]=name;
}
public void setCode(int code)
{
[Link]=code;
}
public String getName()
{
return [Link];
}
public int getCode()
{
return [Link];
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 88
}
}
class Student implements Serializable
{
private int rollNumber;
private String name;
private City city;
private Branch branch;
private Category category;
private String hobbies[];
private int marks[];
public void setRollNumber(int rollNumber)
{
[Link]=rollNumber;
}
public void setName(String name)
{
[Link]=name;
}
public void setCity(City city)
{
[Link]=city;
}
public void setBranch(Branch branch)
{
[Link]=branch;
}
public void setCategory(Category category)
{
[Link]=category;
}
public void setHobbies(String hobbies[])
{
[Link]=hobbies;
}
public void setMarks(int marks[])
{
[Link]=marks;
}
public int getRollNumber()
{
return [Link];
}
public String getName()
{
return [Link];
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 89
[Link](city);
[Link](branch);
[Link](category);
try
{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
[Link](student1);
byte bytes[]=[Link]();
[Link]("Object serialized to byte array of length : "+[Link]);
Student student2;
ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
ObjectInputStream ois=new ObjectInputStream(bais);
student2=(Student)[Link]();
[Link]("Byte array data deserialized");
city=[Link]();
state=[Link]();
country=[Link]();
branch=[Link]();
category=[Link]();
String []hobbies=[Link]();
int []marks=[Link]();
[Link]("Roll number : "+[Link]());
[Link]("Name : "+[Link]());
[Link]("City : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("State : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("Country : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("Branch : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("Category : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("Hobbies : ");
for(int i=0;i<[Link];i++)
{
[Link]("\t %s\n",hobbies[i]);
}
[Link]("Marks : ");
for(int i=0;i<[Link];i++)
{
[Link]("\t %d\n",marks[i]);
}
}catch(Exception exception)
{
[Link](exception);
}
}
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 91
}
}
}
class ChotaServer
{
private ServerSocket serverSocket;
private int portNumber;
ChotaServer(int portNumber)
{
[Link]=portNumber;
try
{
serverSocket=new ServerSocket([Link]);
startListening();
}catch(Exception e)
{
[Link](e);
[Link](0);
}
}
public void startListening()
{
try
{
InputStream is;
InputStreamReader isr;
OutputStream os;
OutputStreamWriter osw;
StringBuffer sb;
String request;
int x;
int c1,c2;
String pc1,pc2,pc3;
int rollNumber;
String name;
String gender;
Socket ck;
String response;
while(true)
{
[Link]("Server is listening on port : "+[Link]);
ck=[Link]();
[Link]("Request arrived ");
is=[Link]();
isr=new InputStreamReader(is);
sb=new StringBuffer();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 93
while(true)
{
x=[Link]();
if(x=='#' || x==-1)
{
break;
}
[Link]((char)x);
}
request=[Link]();
[Link]("Request : "+request);
c1=[Link](",");
c2=[Link](",",c1+1);
pc1=[Link](0,c1);
pc2=[Link](c1+1,c2);
pc3=[Link](c2+1);
rollNumber=[Link](pc1);
name=pc2;
gender=pc3;
[Link]("Roll number : "+rollNumber);
[Link]("Name : "+name);
[Link]("Gender : "+gender);
// code to save data
response="Data saved#";
os=[Link]();
osw=new OutputStreamWriter(os);
[Link](response);
[Link]();
[Link]("Response sent");
[Link]();
}
}catch(Exception e)
{
[Link](e);
}
}
public static void main(String data[])
{
int portNumber=[Link](data[0]);
ChotaServer cs=new ChotaServer(portNumber);
}
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 94
After compiling the above code. Open 2 command windows, resize size them to smaller size and keep
them vertically in parallel to each other.
move into the socket1 folder in both of them.
In one of them type
java ChotaServer 6000
Note : You can connect two machines, note down their IP Addresses, then while running the client
application, you can specify the IP Address of the machines running the server application.
I have specified (localhost) as the server is running on the same machine on which the client is running.
}
class ChotaServer
{
private ServerSocket serverSocket;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 96
try
{
InputStream is;
InputStreamReader isr;
OutputStream os;
OutputStreamWriter osw;
StringBuffer sb;
String request;
int x;
int c1,c2;
String pc1,pc2,pc3;
int rollNumber;
String name;
String gender;
String response;
is=[Link]();
isr=new InputStreamReader(is);
sb=new StringBuffer();
while(true)
{
x=[Link]();
if(x=='#' || x==-1)
{
break;
}
[Link]((char)x);
}
request=[Link]();
[Link]("Request : "+request);
c1=[Link](",");
c2=[Link](",",c1+1);
pc1=[Link](0,c1);
pc2=[Link](c1+1,c2);
pc3=[Link](c2+1);
rollNumber=[Link](pc1);
name=pc2;
gender=pc3;
[Link]("Roll number : "+rollNumber);
[Link]("Name : "+name);
[Link]("Gender : "+gender);
// code to save data
response="Data saved#";
os=[Link]();
osw=new OutputStreamWriter(os);
[Link](response);
[Link]();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 98
[Link]("Response sent");
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}
run the socket2 code as done in case of socket1
Socket Programming – Sending serialized objects over the network
Create a folder named as socket3
in it create [Link]
[Link] (will compile)
import [Link].*;
import [Link].*;
class Student implements Serializable
{
private int rollNumber;
private String name;
private String gender;
public void setRollNumber(int rollNumber)
{
[Link]=rollNumber;
}
public int getRollNumber()
{
return [Link];
}
public void setName(String name)
{
[Link]=name;
}
public String getName()
{
return [Link];
}
public void setGender(String gender)
{
[Link]=gender;
}
public String getGender()
{
return [Link];
}
}
class StudentClient
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 99
{
public static void main(String data[])
{
String server=data[0];
int portNumber=[Link](data[1]);
int rollNumber=[Link](data[2]);
String name=data[3];
String gender=data[4];
Student student=new Student();
[Link](rollNumber);
[Link](name);
[Link](gender);
try
{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
[Link](student);
[Link]();
byte bytes[]=[Link]();
Socket socket=new Socket(server,portNumber);
OutputStream outputStream=[Link]();
int bufferSize=1024;
int numberOfBytesToWrite;
int i=0;
[Link]("Sending data....");
while(i<[Link])
{
numberOfBytesToWrite=bufferSize;
if(i+bufferSize>[Link])
{
numberOfBytesToWrite=[Link]-i;
}
[Link](bytes,i,numberOfBytesToWrite);
[Link]();
i=i+bufferSize;
}
[Link]("Data sent.......");
InputStream is=[Link]();
baos=new ByteArrayOutputStream();
byte b[]=new byte[1024];
int byteCount;
while(true)
{
byteCount=[Link](b);
if(byteCount<0) break;
[Link](b,0,byteCount);
// break; // This line needs to be discussed in classroom session, This implementation has a bug
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 100
}
b=[Link]();
String response=new String(b);
[Link]();
[Link](response);
}catch(Exception exception)
{
[Link](exception);
}
}
}
class StudentServer
{
private ServerSocket serverSocket;
private int portNumber;
StudentServer(int portNumber)
{
[Link]=portNumber;
try
{
serverSocket=new ServerSocket([Link]);
startListening();
}catch(Exception e)
{
[Link](e);
[Link](0);
}
}
public void startListening()
{
try
{
Socket ck;
while(true)
{
[Link]("Server is listening on port : "+[Link]);
ck=[Link]();
[Link]("Request arrived ");
new RequestProcessor(ck);
}
}catch(Exception e)
{
[Link](e);
}
}
public static void main(String data[])
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 101
int portNumber=[Link](data[0]);
StudentServer cs=new StudentServer(portNumber);
}
}
class RequestProcessor extends Thread
{
private Socket ck;
RequestProcessor(Socket socket)
{
[Link]=socket;
start();
}
public void run()
{
try
{
InputStream is;
OutputStream os;
is=[Link]();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte b[]=new byte[1024];
int byteCount;
[Link]("Fetching data....");
while(true)
{
byteCount=[Link](b);
[Link]("Got : "+byteCount+" bytes");
if(byteCount<0) break;
[Link](b,0,byteCount);
break;
}
[Link]("Data fetched, now parsing it");
b=[Link]();
ByteArrayInputStream bais=new ByteArrayInputStream(b);
ObjectInputStream ois=new ObjectInputStream(bais);
Student student=(Student)[Link]();
[Link]("Roll number : "+[Link]());
[Link]("Name : "+[Link]());
[Link]("Gender : "+[Link]());
os=[Link]();
String response="OK";
//we can change the following code to convert object to byte array
// and then write 1024 at a time
// we will do it later one in our project
byte bytes[]=[Link]();
[Link](bytes,0,[Link]);
[Link]();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 102
[Link]("Response sent");
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}
compile and run the server using (java StudentServer 6000) and the client using (java StudentClient
localhost 6000 101 Sameer M)
[Link] (will compile)
Your assignment is to remove the bug as discussed in the classroom session
import [Link].*;
import [Link].*;
class Student implements Serializable
{
private int rollNumber;
private String name;
private String gender;
public void setRollNumber(int rollNumber)
{
[Link]=rollNumber;
}
public int getRollNumber()
{
return [Link];
}
public void setName(String name)
{
[Link]=name;
}
public String getName()
{
return [Link];
}
public void setGender(String gender)
{
[Link]=gender;
}
public String getGender()
{
return [Link];
}
}
class StudentClient
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 103
}
[Link](bytes,i,numberOfBytesToWrite);
[Link]();
i=i+bufferSize;
}
[Link]("Data sent.......");
InputStream is=[Link]();
baos=new ByteArrayOutputStream();
byte b[]=new byte[1024];
int byteCount;
while(true)
{
byteCount=[Link](b);
if(byteCount<0) break;
[Link](b,0,byteCount);
}
b=[Link]();
String response=new String(b);
[Link]();
[Link](response);
}catch(Exception exception)
{
[Link](exception);
}
}
}
class StudentServer
{
private ServerSocket serverSocket;
private int portNumber;
StudentServer(int portNumber)
{
[Link]=portNumber;
try
{
serverSocket=new ServerSocket([Link]);
startListening();
}catch(Exception e)
{
[Link](e);
[Link](0);
}
}
public void startListening()
{
try
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 105
Socket ck;
while(true)
{
[Link]("Server is listening on port : "+[Link]);
ck=[Link]();
[Link]("Request arrived ");
new RequestProcessor(ck);
}
}catch(Exception e)
{
[Link](e);
}
}
public static void main(String data[])
{
int portNumber=[Link](data[0]);
StudentServer cs=new StudentServer(portNumber);
}
}
class RequestProcessor extends Thread
{
private Socket ck;
RequestProcessor(Socket socket)
{
[Link]=socket;
start();
}
public void run()
{
try
{
byte header[]=new byte[10];
InputStream is;
OutputStream os;
is=[Link]();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte b[]=new byte[1024];
int byteCount;
[Link]("Fetching data....");
[Link](header);
int contentLength=0;
int e,f;
for(e=0;e<=9;e++)
{
[Link](header[e]+" ");
}
e=9;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 106
f=1;
while(e>=0)
{
contentLength=contentLength+(header[e]*f);
e--;
f=f*10;
}
[Link]("Content length : "+contentLength);
int bytesRead=0;
while(true)
{
byteCount=[Link](b);
if(byteCount<0) break;
bytesRead+=byteCount;
[Link](b,0,byteCount);
if(bytesRead==contentLength) break;
}
[Link]("Data fetched, now parsing it");
b=[Link]();
ByteArrayInputStream bais=new ByteArrayInputStream(b);
ObjectInputStream ois=new ObjectInputStream(bais);
Student student=(Student)[Link]();
[Link]("Roll number : "+[Link]());
[Link]("Name : "+[Link]());
[Link]("Gender : "+[Link]());
os=[Link]();
String response="OK";
//we can change the following code to convert object to byte array
// and then write 1024 at a time
// we will do it later one in our project
byte bytes[]=[Link]();
[Link](bytes,0,[Link]);
[Link]();
[Link]("Response sent");
[Link]();
}catch(Exception e)
{
[Link](e);
}
}
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 107
if(byteRead==lengthOfFileName) break;
}
[Link]("Serialized form of file name received");
bytes=[Link]();
[Link](response,0,headerSize);
[Link]();
String fileName;
ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
ObjectInputStream ois=new ObjectInputStream(bais);
fileName=(String)[Link]();
[Link]("Receiving file : "+fileName);
[Link](header);
[Link](response,0,headerSize);
[Link]();
long lengthOfFile;
lengthOfFile=0;
e=headerSize-1;
f=1;
while(e>=0)
{
lengthOfFile=lengthOfFile+(header[e]*f);
e--;
f=f*10;
}
[Link]("Length of file : "+lengthOfFile);
File file=new File(fileName);
if([Link]()) [Link]();
FileOutputStream fileOutputStream;
fileOutputStream=new FileOutputStream(file);
BufferedOutputStream bos=new BufferedOutputStream(fileOutputStream);
bytes=new byte[1024];
int i=0;
int bytesRead;
while(true)
{
bytesRead=[Link](bytes);
if(bytesRead<0) break;
i=i+bytesRead;
[Link](bytes,0,bytesRead);
[Link]();
if(i==lengthOfFile) break;
}
[Link](response,0,headerSize);
[Link]();
[Link]();
[Link]("File received");
}catch(Exception e)
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 110
{
[Link](e);
}
}
}
Compile the FTServer code and to run type
java FTServer 60000
[Link] (will compile)
import [Link].*;
import [Link].*;
class FTClient
{
public static void main(String data[])
{
try
{
String server=data[0];
int port=[Link](data[1]);
String filePath=data[2];
File file=new File(filePath);
if([Link]()==false)
{
[Link]("File Not Found : "+filePath);
return;
}
String fileName=[Link]();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
[Link](fileName);
byte [] fileNameByteArray;
fileNameByteArray=[Link]();
int lengthOfFileName=[Link];
int headerSize=20;
byte header[];
header=new byte[headerSize];
int k=headerSize-1;
long f=lengthOfFileName;
while(k>=0)
{
header[k]=(byte)(f%10);
f=f/10;
k--;
}
Socket socket=new Socket(server,port);
OutputStream outputStream;
outputStream=[Link]();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 111
[Link](header,0,headerSize);
[Link]();
byte response[]=new byte[headerSize];
InputStream inputStream=[Link]();
[Link](response);
int i;
int bufferSize=1024;
int numberOfBytesToWrite=bufferSize;
i=0;
while(i<[Link])
{
if(i+bufferSize>[Link])
{
numberOfBytesToWrite=[Link]-i;
}
[Link](fileNameByteArray,i,numberOfBytesToWrite);
[Link]();
[Link](header);
i=i+bufferSize;
}
long lengthOfFile=[Link]();
k=headerSize-1;
f=lengthOfFile;
while(k>=0)
{
header[k]=(byte)(f%10);
f=f/10;
k--;
}
[Link](header,0,headerSize);
[Link]();
[Link](response);
[Link]("header with length of file sent "+lengthOfFile);
FileInputStream fileInputStream;
fileInputStream=new FileInputStream(file);
BufferedInputStream bis=new BufferedInputStream(fileInputStream);
byte contents[]=new byte[1024];
int bytesRead;
i=0;
while(i<lengthOfFile)
{
bytesRead=[Link](contents);
if(bytesRead<0) break;
[Link](contents,0,bytesRead);
[Link]();
i=i+bytesRead;
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 112
[Link]();
[Link]("bytes of file sent : "+i);
[Link](response);
// some more code required over here to parse the response
[Link]();
[Link]("File sent");
}catch(Exception exception)
{
[Link](exception);
}
}
}
Compile the FTClient code, and to run type
java FTClient localhost 60000 filename
in my case I typed the filename as 10004.mp4
Then in the FTServer folder check the existence of the file that you transferred
The FTServer
TheFTClient
}
public void setCountry(Country country)
{
[Link]=country;
}
public Country getCountry()
{
return [Link];
}
}
class City implements Serializable
{
private int code;
private String name;
private State state;
public void setName(String name)
{
[Link]=name;
}
public void setCode(int code)
{
[Link]=code;
}
public String getName()
{
return [Link];
}
public int getCode()
{
return [Link];
}
public void setState(State state)
{
[Link]=state;
}
public State getState()
{
return [Link];
}
}
class Category implements Serializable
{
private int code;
private String name;
public void setName(String name)
{
[Link]=name;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 115
}
public void setCode(int code)
{
[Link]=code;
}
public String getName()
{
return [Link];
}
public int getCode()
{
return [Link];
}
}
class Branch implements Serializable
{
private int code;
private String name;
public void setName(String name)
{
[Link]=name;
}
public void setCode(int code)
{
[Link]=code;
}
public String getName()
{
return [Link];
}
public int getCode()
{
return [Link];
}
}
class Student implements Serializable
{
private int rollNumber;
private String name;
private City city;
private Branch branch;
private Category category;
private String hobbies[];
private int marks[];
public void setRollNumber(int rollNumber)
{
[Link]=rollNumber;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 116
}
public void setName(String name)
{
[Link]=name;
}
public void setCity(City city)
{
[Link]=city;
}
public void setBranch(Branch branch)
{
[Link]=branch;
}
public void setCategory(Category category)
{
[Link]=category;
}
public void setHobbies(String hobbies[])
{
[Link]=hobbies;
}
public void setMarks(int marks[])
{
[Link]=marks;
}
public int getRollNumber()
{
return [Link];
}
public String getName()
{
return [Link];
}
public City getCity()
{
return [Link];
}
public Branch getBranch()
{
return [Link];
}
public Category getCategory()
{
return [Link];
}
public String [] getHobbies()
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 117
return [Link];
}
public int[] getMarks()
{
return [Link];
}
}
interface StudentServerInterface extends Remote
{
public void addStudent(Student student) throws RemoteException;
public int getNumberOfStudents() throws RemoteException;
}
class StudentServer extends UnicastRemoteObject implements StudentServerInterface
{
StudentServer() throws RemoteException
{
[Link]("Student server instantiated.....");
}
public void addStudent(Student student) throws RemoteException
{
[Link]("Request arrived");
City city=[Link]();
State state=[Link]();
Country country=[Link]();
Branch branch=[Link]();
Category category=[Link]();
String []hobbies=[Link]();
int []marks=[Link]();
[Link]("Roll number : "+[Link]());
[Link]("Name : "+[Link]());
[Link]("City : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("State : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("Country : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("Branch : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("Category : Code - %d, Name - %s\n",[Link](),[Link]());
[Link]("Hobbies : ");
for(int i=0;i<[Link];i++)
{
[Link]("\t %s\n",hobbies[i]);
}
[Link]("Marks : ");
for(int i=0;i<[Link];i++)
{
[Link]("\t %d\n",marks[i]);
}
}
public int getNumberOfStudents() throws RemoteException
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 118
{
return 605;
}
public static void main(String data[])
{
try
{
String name=data[0];
StudentServer ss=new StudentServer();
[Link](name,ss);
[Link]("Server is ready....");
}catch(Exception exception)
{
[Link](exception);
}
}
}
class StudentClient
{
public static void main(String data[])
{
try
{
String server=data[0];
String serverName=data[1];
StudentServerInterface ssi;
ssi=(StudentServerInterface)[Link]("rmi://"+server+"/"+serverName);
[Link](10001);
[Link]("Sameer Gupta");
[Link](new String[]{"Reading fiction","Solving Crossword Puzzles","Robotics"});
[Link](new int[]{91,93,92,85,93});
[Link](city);
[Link](branch);
[Link](category);
[Link](student);
[Link]("Number of students : "+[Link]());
}catch(Exception e)
{
[Link](e);
}
}
}
To compile the above code
javac [Link]
then (not necessary in case of jdk1.8, but still do it, you may get some warnings, ignore them)
rmic StudentServer
Then open 3 command windows,
move into the rmi1 folder (in all 3 of them)
in first one type (rmiregistry)
in second one type (java StudentServer LionKing)
in third one type (java StudentClient localhost LionKing)
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 120