0% found this document useful (0 votes)
17 views120 pages

Java J2EE Classroom Reference Guide

This document serves as a reference guide for Java 1.8, specifically for participants of classroom sessions at Thinking Machines. It outlines various topics covered in the sessions, including event notification systems, interfaces, multithreading, socket programming, and more, with accompanying code examples. The document emphasizes the importance of attending theory sessions to fully understand the provided examples.

Uploaded by

shsbhajak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views120 pages

Java J2EE Classroom Reference Guide

This document serves as a reference guide for Java 1.8, specifically for participants of classroom sessions at Thinking Machines. It outlines various topics covered in the sessions, including event notification systems, interfaces, multithreading, socket programming, and more, with accompanying code examples. The document emphasizes the importance of attending theory sessions to fully understand the provided examples.

Uploaded by

shsbhajak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Thinking Machines – Java – J2EE – (Book Two Of Three) Page 1

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.

• Some examples won't compile. They have been written to


explain some rules.

• If you try to understand the examples without attending theory


sessions then may god help you.
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 2

[Link]. Topic Page


1 Designing an event notification system
2 Generalized event notification system & creating abstract class to impose
guidelines.
3 Problems associated with creating abstract class to impose guidelines
4 Interface
5 Generalized event notification system & creating interface class to impose
guidelines.
6 Keyboard input
7 Generalized Keyboard class
8 Predefined Scanner class
9 File Handling (CRUD Operations)
10 RDBMS (SQLite)
11 JDBC
12 MySql
13 MySql – Creating procedures/functions
14 JDBC – Invoking procedures/functions
15 Multithreading – The traditional way
16 Synchronization
17 Classic producer / consumer scenario and synchronization
18 Local inner classes
19 Inner classes
20 Anonymous classes
21 Lambda
22 Multi threading – Concurrency - The new technique.
23 Concurrency – ExecutorService
24 Concurrency – Callable interface & Future task
25 Concurrency – Thread Pools
26 Concurrency – Locks
27 Object Serialization / Deserialization
28 Socket programming – Introduction
29 Socket programming – Multi threaded server
30 Socket Programming – Sending serialized objects over the network
31 Socket Programming – The File Server / Client
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 3

[Link]. Topic Page


32 Remote method invocation (One way)
33 Remote method invocation (Two way)
34 AWT / Layout Managers,Components, Colors and Fonts
35 AWT Event Programming Model
36 Swing
37 JTable
38 JTable with Model as backbone
39 JTree
40 JTree with Model as backbone
41 JFileChooser (Open/Save) Dialog
42 MessageDialog & ConfirmDialog
43 JDialog
44 Creating our own custom components
45 Graphics
46 Introduction to layered programming
47 Creating packages & specifying classpath
48 Creating jar file
49 Creating jar file with [Link] (with entry point function class name)
50 Introduction to layered programming
51 Creating guidelines for the data layer
52 Creating implementation of the data layer (File Handling)
53 Creating test cases and testing the data layer
54 Creating guidelines for the business layer
55 Creating implementation of the business layer
56 Creating test cases and testing the business layer
57 Creating the model for the presentation layer
58 Creating the presentation layer
59 Creating test cases and testing the presentation layer
60 Creating Splash Screen
61 Bundling everything into a single jar file
62 Creating a C Program to generate an executable to launch the java application
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 4

[Link]. Topic Page


63 Introduction to logging system and creating our own logger.
64 Incorporating the logging system in our layered application.
65 Introduction to log4j
66 Changing the logging system from our logger to log4j in our layered
application.
67 Introduction to build tool – Gradle
68 Creating implementation of the data layer (JDBC – MySQL)
69 Creating test cases and testing the data layer
70 Building the previously created application by replacing he older data layer
(File handling) with new one (JDBC-MySql). Building using gradle.
71 Introduction to Maven (A build and dependency management tool)
72 Building the previously created application using Maven
73 Java Collection Classes (Set/Map/List)
74 Sorting collections
75 Iterating over collections
76 Applying lambdas over collections
77 Internal V/s External iteration
78 Sequential and Parallel operations on Collections
79 Reflection API
80 Creating Annotations
81 Analyzing folders and jars for classes with applied annotations and generating
a data structure
82 XML Parsing
83 Creating a data layer generation tool for Rapid Application Development
84 Creating the UI for data layer generation tool for Rapid Application
Development.
85 Java Generic Socket Server – To enable the user to create a network
application without socket programming.
86 An application to test the Generic Socket Server
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 5

Designing an event notification system


[Link] (will compile)
class Bulb
{
private int wattage;
private WattageChangedLogger wattageChangedLogger;
public void setWattageChangedLogger(WattageChangedLogger wattageChangedLogger)
{
[Link]=wattageChangedLogger;
}
public void setWattage(int wattage)
{
if(wattage!=[Link])
{
int oldWattage=[Link];
[Link]=wattage;
if([Link]!=null)
{
[Link](oldWattage,[Link]);
}
}
}
public int getWattage()
{
return [Link];
}
}
class WattageChangedLogger
{
public void wattageChanged(int oldWattage,int newWattage)
{
[Link]("Wattage change from %d to %d\n",oldWattage,newWattage);
}
}
class EG1App
{
public static void main(String kk[])
{
Bulb b1=new Bulb();
WattageChangedLogger wcl=new WattageChangedLogger();
[Link](wcl);
[Link](60);
[Link](120);
[Link](120);
[Link](0);
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 6

}
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.

Note : Interface is not an alternative to multiple inheritance. Interface in an alternative to an abstract


class with no properties and whose all methods are abstract. The sole purpose of creating interface in to
impose guidelines or provide declaration of a certain kind.
Interface
[Link] (will not compile)
interface aaaa
{
private void sam() // wrong
{
}
public void tom() // wrong
{
}
public void john(); // correct
}
[Link] (will not compile)
interface aaaa
{
public void john(); // correct
}
class bbb extends aaaa // incorrect
{

}
[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 jjjj implements aaaa extends pqr // incorrect

class jjjj implements aaaa,bbbb,ccccc,ddddd // correct


[Link] (will compile)
interface aaaa
{
void sam(); // correct, compiler will declare it as public
}
[Link] (will not compile)
interface aaaa
{
public int x;
}
[Link] (will not compile)
interface aaaa
{
public int x=10; // a variable declared in an interface will become final
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 12

}
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

}class bbb implements aaaa


{
public void sam()
{
[Link]("Super cool");
}
public void tom()
{
[Link]("Cool");
}
}
class EG4App
{
public static void main(String kk[])
{
aaaa a=new bbb();
[Link]();
}
}
Keyboard input
[Link] (will not compile)
import [Link].*;
class EG5App
{
public static void main(String kk[])
{
InputStreamReader isr;
isr=new InputStreamReader([Link]);
BufferedReader br;
br=new BufferedReader(isr);
char m;
[Link]("Enter a character : ");
m=(char)[Link]();
[Link](m);
}
}
[Link] (will compile)
import [Link].*;
class EG5App
{
public static void main(String kk[])
{
InputStreamReader isr;
isr=new InputStreamReader([Link]);
BufferedReader br;
br=new BufferedReader(isr);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 14

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

public static void main(String kk[])


{
Scanner scanner=new Scanner([Link]);
[Link]("Enter name : ");
String name=[Link]();
[Link](name);
[Link]("Enter age : ");
int age=[Link]();
[Link](age);
[Link]("Enter gender (M/F) : ");
char gender=(char)[Link]().charAt(0);
[Link](gender);
}
}
File Handling (CRUD Operations)
[Link] (will compile)
import [Link].*;
class AddEmployee
{
public static void main(String data[])
{
if([Link]!=3)
{
[Link]("Invalid use of module : AddEmployee");
[Link]("Usage : java AddEmployee code name salary");
return;
}
int code=[Link](data[0]);
String name=data[1];
int salary=[Link](data[2]);
try
{
File f;
f=new File("[Link]");
// because of the above code, don't assume that the file has been opened
RandomAccessFile raf;
/*
because of the following line, the constructor of the
RandomAccessFile class will open a file in RAM and some
internal pointer will point to the first byte of the file.
If the file doesn't exist, a new file will be opened, we can write/read
because of the mode (rw) another available mode is (r)
*/
raf=new RandomAccessFile(f,"rw");
/*
length() function returns the length of the file
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 19

getFilePointerFunction() returns the current position


of the pointer (First is looked upon as zero)
readLine() function returns a string(reads till \n is found)
writeBytes(String) will write the string from current position
*/
int vCode;
String vName;
int vSalary;
while([Link]()<[Link]())
{
vCode=[Link]([Link]());
vName=[Link]();
vSalary=[Link]([Link]());
if(vCode==code)
{
[Link]();
[Link]("That code alloted to : "+vName);
return;
}
}
// valueOf to convert anything to String
[Link]([Link](code));
[Link]("\n");
[Link](name);
[Link]("\n");
[Link]([Link](salary));
[Link]("\n");
[Link]();
[Link]("Employee added.......");
}catch(IOException ioException)
{
[Link]("Problem : "+[Link]());
}
}
}
[Link] (will compile)
import [Link].*;
class UpdateEmployee
{
public static void main(String data[])
{
if([Link]!=3)
{
[Link]("Invalid use of module : UpdateEmployee");
[Link]("Usage : java UpdateEmployee code name salary");
return;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 20

}
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

RandomAccessFile tmpraf=new RandomAccessFile(tmpFile,"rw");


while([Link]()<[Link]())
{
vCode=[Link]([Link]());
vName=[Link]();
vSalary=[Link]([Link]());
if(code!=vCode)
{
[Link](vCode+"\n"+vName+"\n"+vSalary+"\n");
}
else
{
[Link](code+"\n"+name+"\n"+salary+"\n");
}
}
[Link](0);
[Link](0);
while([Link]()<[Link]())
{
[Link]([Link]()+"\n");
}
[Link]([Link]());
[Link](0);
[Link]();
[Link]();
[Link]("Employee updated.....");
}catch(Exception exception)
{
[Link](exception);
}
}
}
[Link] (will compile)
import [Link].*;
class DeleteEmployee
{
public static void main(String data[])
{
if([Link]!=1)
{
[Link]("Invalid use of module : DeleteEmployee");
[Link]("Usage : java DeleteEmployee code");
return;
}
int code=[Link](data[0]);
try
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 22

{
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

Add c:\sqlite3 to PATH environment variable as you add c:\jdk1.8\bin etc.

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.

Create table item


(
code integer primary key,
name text,
unit_of_measurement
);

insert into item values(101,'Screw','Nos');


insert into item values(102,'Computer','NOS');
insert into item values(103,'Milk','Ltr');
insert into item values(102,'Printer','Nos')

select * from item

.headers on

select * from item

select code,name from item


select name,code from item
select name,code,name from item
select code,name as "Name" from item

update item set unit_of_measurement='Packet' where code=101


select * from item

update item set name='curd',unit_of_measurement='Kg' where code=103


select * from item
delete from item where code=102
select * from item
delete from item
select * from item

now type (.quit) to exit from sqlite


Thinking Machines – Java – J2EE – (Book Two Of Three) Page 26

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])

to run type (java -classpath c:\sqlite3\[Link];. Jdbc1)

You should see a message, record added.

Run again and now you should see an exception.

Now type (sqlite3 [Link])

type the following on sqlite prompt

select * from item;

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])

to run type (java -classpath c:\sqlite3\[Link];. Jdbc2

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

[Link] (will compile)


import [Link].*;
class jdbc3
{
public static void main(String gg[])
{
try
{
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:sqlite:[Link]");
Statement s=[Link]();
[Link]("delete from item where code=101");
[Link]();
[Link]();
[Link]("Record deleted");
}catch(Exception e)
{
[Link](e);
}
}
}
Compile and run the above program as done earlier and verify using sqlite3
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 30

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

add some more records.


Now let us write a code for updation that accepts data as command line arguments
[Link] (will compile)
import [Link].*;
class jdbc5
{
public static void main(String data[])
{
try
{
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:sqlite:[Link]");
Statement s=[Link]();
[Link]("update item set name='"+data[1]+"',unit_of_measurement='"+data[2]+"' where
code="+data[0]);
[Link]();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 31

[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)

create table country


(
code integer primary key,
name text unique
)

create table state


(
code integer primary key,
name text
country_code integer
)

create table city


(
code integer primary key,
name text,
state_code integer
)

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

Enter ".help" for instructions


Enter SQL statements terminated with a ";"
sqlite> create table country
...> (code integer primary key,name text unique);
sqlite> create table state
...> (code integer primary key,name text,country_code integer);
sqlite> create table city
...> (code integer primary key,name text,state_code integer);
sqlite> insert into country values(1,'India');
sqlite> insert into country values(2,'Pakistan');
sqlite> insert into state values(1,'M.P.',1);
sqlite> insert into state values(2,'U.P.',1);
sqlite> insert into state values(3,'Maharashtra',1);
sqlite> insert into state values(4,'Punjab',2);
sqlite> select * from country;
1|India
2|Pakistan
sqlite> select * from state;
1|M.P.|1
2|U.P.|1
3|Maharashtra|1
4|Punjab|2
sqlite> .headers on
sqlite> select * from state,country
...> ;
code|name|country_code|code|name
1|M.P.|1|1|India
2|U.P.|1|1|India
3|Maharashtra|1|1|India
4|Punjab|2|1|India
1|M.P.|1|2|Pakistan
2|U.P.|1|2|Pakistan
3|Maharashtra|1|2|Pakistan
4|Punjab|2|2|Pakistan
sqlite> select * from state,country where state.country_code=[Link];
code|name|country_code|code|name
1|M.P.|1|1|India
2|U.P.|1|1|India
3|Maharashtra|1|1|India
4|Punjab|2|2|Pakistan
sqlite> select code,name,code,name from state,country where state.country_code=c
[Link];
Error: ambiguous column name: code
sqlite> select [Link],[Link],[Link],[Link] from state,countr
y where state.country_code=[Link];
code|name|code|name
1|M.P.|1|India
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 34

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.

Now create a folder named as mysqleg on c:\

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)

Now move to c:\mysqleg folder and type

mysql -uroot -pkelkar

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.

This is where we will be typing our SQL Statements.

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.

First of all we will create a database named as ThinkingMachinesDB


for that type

create database ThinkingMachinesDB;

Now let us create a user account named as tmdbuser with password also as tmdbuser, for that type

create user 'tmdbuser'@'%' identified by 'tmdbuser';

Now let us grant all the rights of the ThinkingMachinesDB to tmdbuser, for that type

grant all privileges on ThinkingMachinesDB.* to 'tmdbuser'@'%' with grant option;

Now type quit to exit from MySQL

Now again login, but this time as tmdbuser, for that type

mysql -utmdbuser -ptmdbuser

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

you should see the message that says Database Changed.

Now create tables using the following sql statements

create table item


(code int primary key auto_increment,
name char(35) not null unique,
opening_stock int not null default 0 ,
total_purchases int not null default 0 ,
total_sales int not null default 0 ,
closing_stock int not null default 0 ) Engine=InnoDB;
create table customer
(code int primary key auto_increment,
name char(50) not null unique)Engine=InnoDB;
create table supplier
(code int primary key auto_increment,
name char(50) not null unique)Engine=InnoDB;
create table sale
(bill_number int primary key auto_increment,
bill_date date not null,
customer_code int not null references customer)Engine=InnoDB;
create table sale_item
(bill_number int not null references sale,
item_code int not null references item,
quantity int not null ,
rate double not null ,
primary key(bill_number,item_code))Engine=InnoDB;
create table purchase
(reference_number int primary key auto_increment,
bill_number char(25) not null,
bill_date date not null,
supplier_code int not null references supplier)Engine=InnoDB;
create table purchase_item
(reference_number int not null references purchase,
item_code int not null references item,
quantity int not null ,
rate double not null ,
primary key(reference_number,item_code))Engine=InnoDB;

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

To get details of each table, you can type


describe tablename;

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

Now login into mysql as tmdbuser and type the following


delimiter //
then
source [Link]
if no errors, then
delimiter ;
Refer the following UI

To get list of triggers type


show triggers\G
Now let us create sql files to insert sample data
item_data.sql
insert into item (name,opening_stock,closing_stock) values('Screw',1000,1000);
insert into item (name,opening_stock,closing_stock) values('Computer',1500,1500);
insert into item (name) values ('Printer');
insert into item (name) values ('Mouse pad');
insert into item (name) values ('Pencil');
insert into item (name,opening_stock,closing_stock) values ('Pencil Box',1800,1800);
Login into mysql using (tmdbuser) and type (source item_data.sql) to insert records
Now view the records from item table using (select * from item), note down the codes of the inserted
records, in my case it is (1 to 6)
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 42

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

The do the same for purchase and purchase_item table.

I am attaching screen shots from my end.


Thinking Machines – Java – J2EE – (Book Two Of Three) Page 44
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 45

Similarly perform more operations as per your requirement. I am pasting all the sql statements fired by
me as follows.

insert into sale (bill_date,customer_code) values ('2017/01/02',3);


insert into sale_item values(2,1,10,50);
insert into sale_item values(2,2,30,30000);
insert into sale_item values(2,6,100,30);
insert into purchase (bill_number,bill_date,supplier_code) values ('Jan 01/2017','2017/01/01',2);
insert into purchase_item values(1,3,400,40);
insert into purchase_item values(1,4,50,60);
insert into purchase_item values(1,5,20,30);
insert into purchase (bill_number,bill_date,supplier_code) values ('309','2017/01/01',4);
insert into purchase_item values(2,1,250,40);
insert into purchase_item values(2,2,450,60000);
insert into purchase (bill_number,bill_date,supplier_code) values ('504','2017/01/01',3);
insert into purchase_item values(3,1,250,40);
insert into purchase_item values(3,2,10,55000);
insert into purchase_item values(3,3,20,60);
insert into purchase_item values(3,4,30,7000);
insert into purchase_item values(3,5,40,85);
insert into purchase_item values(3,6,50,90);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 46

Finally these are the records at my end

Now lets verify that the calculations are correct

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.

First of all create a folder named as mysql on c:\


download [Link] and save it to c:\mysql

[Link] (will compile)


import [Link].*;
class jdbc8
{
public static void main(String kk[])
{
try
{
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:mysql://localhost:3306/ThinkingMachinesDB","tmdbuser","tm
dbuser");
Statement s=[Link]();
int billNumber;
Date billDate;
int customerCode;
String customerName;
int billAmount;
int itemCode;
String itemName;
int quantity;
int rate;
int amount;
int sno;
PreparedStatement ps;
ResultSet r2;
ResultSet r1;
r1=[Link]("select * from sale_view order by bill_number");
while([Link]())
{
billNumber=[Link]("bill_number");
billDate=[Link]("bill_date");
customerCode=[Link]("customer_code");
customerName=[Link]("name").trim();
billAmount=[Link]("bill_amount");
[Link]("Bill number : "+billNumber+"\t\tDate : "+([Link]()+"/"+
([Link]()+1)+"/"+([Link]()+1900)));
[Link]("Customer : %s (%d)\n",customerName,customerCode);
[Link]("-------------------------------------------------------------------------------");
[Link](" Item Qty. Rate Amount");
[Link]("-------------------------------------------------------------------------------");
ps=[Link]("select * from sale_bill_item_view where bill_number=?");
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 50

[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

MySQL – Creating procedures/functions


create a file named as add_customer.sql
add_customer.sql
create function add_customer(name char(50)) returns int
Begin
declare is_error int default 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION set is_error=-1;
insert into customer(name) values(name);
if is_error=0 then
return LAST_INSERT_ID();
else
return -1;
end if;
end; //
To create the function, login into mysql (tmdbuser) account
first of all type
delimiter //
then type
source add_customer.sql
then type
delimiter ;
Now let us create java code to call the function
[Link] (will compile)
import [Link].*;
class jdbc9
{
public static void main(String data[])
{
try
{
String name=data[0];
[Link]("[Link]");
Connection c;
c=[Link]("jdbc:mysql://localhost:3306/ThinkingMachinesDB","tmdbuser","tm
dbuser");
CallableStatement cs=[Link]("{? = call add_customer(?)}");
[Link](1,[Link]);
[Link](2,name);
[Link]();
Integer customerCode=[Link](1);
[Link]();
if(customerCode==-1)
{
[Link]("Customer not inserted");
}
else
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 52

{
[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]("insert into item (name) values('Slider')");


[Link]("insert into item (name) values('Duster')");
[Link]("insert into item (name) values('Marker')");
[Link]();
s=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet r=[Link]("select * from item");
[Link](4);
int rowNum = [Link]();
[Link]("rowNum should be 4 " + rowNum);
[Link](-2);
rowNum = [Link]();
[Link]("rowNum should be 2 " + rowNum);
[Link](1);
rowNum = [Link]();
[Link]("rowNum should be 3 " + rowNum);
[Link]();
[Link]("after last? " + [Link]() );
[Link]();
[Link]("after last? " + [Link]() );
int code;
String name;
if (![Link]())
{
code = [Link]("code");
name = [Link]("name").trim();
[Link]("Code : %d, Name %s\n",code,name);
}
[Link]("-------------------------------------------------");
[Link]();
while ([Link]())
{
code = [Link]("code");
name = [Link]("name").trim();
[Link]("Code : %d, Name %s\n",code,name);
}
[Link]();
[Link]();
[Link]("-------------------------------------------------");
s=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
r=[Link]("SELECT * from item");
while([Link]())
{
code=[Link]("code");
name=[Link]("name").trim();
if([Link]("Slider"))
{
[Link]("name","Set square");
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 58

[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

Multithreading – The traditional way


[Link] (will not compile)
class aaa
{
aaa()
{
Thread t;
t=new Thread(this);
}
}
class thread1
{
public static void main(String gg[])
{
aaa a;
a=new aaa();
int x;
x=1;
while(x<=200)
{
[Link](x+" ");
x++;
}
}
}
[Link] (will not compile)
class aaa implements Runnable
{
aaa()
{
Thread t;
t=new Thread(this);
}
}
class thread2
{
public static void main(String gg[])
{
aaa a;
a=new aaa();
int x;
x=1;
while(x<=200)
{
[Link](x+" ");
x++;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 63

}
}
}
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

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 thread4
{
public static void main(String gg[])
{
aaa a;
a=new aaa();
int x;
x=1;
while(x<=200)
{
[Link](x+" ");
x++;
}
}
}
Synchronization
Run the code many times as done earlier
[Link] (will compile)
// Problems associated with multi threading
//What will happen when multiple
// threads will work on a common object
class cmn
{
private String m;
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
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 65

{
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

private String ss;


worker(cmn c,String s)
{
cc=c;
ss=s;
start();
}
public void run()
{
[Link](ss);
}
}
class thread6
{
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)
class cmn
{
private String m;
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;
private String ss;
worker(cmn c,String s)
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 67

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

Thread t=new Thread(r);


[Link]();
for(int x=1;x<=50;x++)
{
[Link](x+" ");
}
}
}
Note : when you will run the following code, it will get stuck in end, press control C to end application.
Concurrency – ExecutorService
[Link] (will compile)
import [Link].*;
class concurr2
{
public static void main(String g[])
{
ExecutorService es=[Link]();
[Link](()->{
for(int x=1;x<=50;x++)
{
[Link](x+" ");
}
});
for(int y=201;y<=250;y++)
{
[Link](y+" ");
}
}
}
[Link] (will compile)
import [Link].*;
class concurr3
{
public static void main(String g[])
{
ExecutorService es=[Link]();
[Link](()->{
for(int x=1;x<=50;x++)
{
[Link](x+" ");
}
});
for(int y=201;y<=250;y++)
{
[Link](y+" ");
}
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 81

[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

public City getCity()


{
return [Link];
}
public Branch getBranch()
{
return [Link];
}
public Category getCategory()
{
return [Link];
}
public String [] getHobbies()
{
return [Link];
}
public int[] getMarks()
{
return [Link];
}
}
class serialize3
{
public static void main(String gg[])
{
Country country=new Country();
[Link](1);
[Link]("India");
State state=new State();
[Link](101);
[Link]("Madhya Pradesh");
[Link](country);
City city=new City();
[Link](1001);
[Link]("Ujjain");
[Link](state);
Branch branch=new Branch();
[Link](5001);
[Link]("Computer Science");
Category category=new Category();
[Link](6001);
[Link]("General");
Student student1=new Student();
[Link](10001);
[Link]("Sameer Gupta");
[Link](new String[]{"Reading fiction","Solving Crossword Puzzles","Robotics"});
[Link](new int[]{91,93,92,85,93});
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 90

[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

Socket Programming – Introduction


Create a folder named as socket1
in it create [Link]
[Link] (will compile)
import [Link].*;
import [Link].*;
class ChotaClient {
public static void main(String data[])
{
String serverName=data[0];
int portNumber=[Link](data[1]);
int rollNumber=[Link](data[2]);
String name=data[3];
String gender=data[4];
String request=rollNumber+","+name+","+gender+"#";
try
{
Socket socket=new Socket(serverName,portNumber);
OutputStream os;
OutputStreamWriter osw;
InputStream is;
InputStreamReader isr;
StringBuffer sb;
String response;
int x;
os=[Link]();
osw=new OutputStreamWriter(os);
[Link](request);
[Link](); // request sent
is=[Link]();
isr=new InputStreamReader(is);
sb=new StringBuffer();
while(true)
{
x=[Link]();
if(x=='#' || x==-1)
{
break;
}
[Link]((char)x);
}
response=[Link]();
[Link](response);
[Link]();
}catch(Exception e)
{
[Link](e);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 92

}
}

}
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 : if firewall prompts a message dialog (click the allow button)


Now the server will go in listening mode.
In the another window, type
java ChotaClient localhost 6000 101 Sameer M
The client code will complete after sending the request and receiving back the response. The server will
be still in listening mode for next request. You can press Control C to terminate the server application.
The server window screen shot

The Client window screen shot

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.

Henceforth to do the same to run server/client apps.


Socket programming – Multithreaded server
Create a folder named as socket2
in it create [Link]
[Link] (will compile)
import [Link].*;
import [Link].*;
class ChotaClient
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 95

public static void main(String data[])


{
String serverName=data[0];
int portNumber=[Link](data[1]);
int rollNumber=[Link](data[2]);
String name=data[3];
String gender=data[4];
String request=rollNumber+","+name+","+gender+"#";
try
{
Socket socket=new Socket(serverName,portNumber);
OutputStream os;
OutputStreamWriter osw;
InputStream is;
InputStreamReader isr;
StringBuffer sb;
String response;
int x;
os=[Link]();
osw=new OutputStreamWriter(os);
[Link](request);
[Link](); // request sent
is=[Link]();
isr=new InputStreamReader(is);
sb=new StringBuffer();
while(true)
{
x=[Link]();
if(x=='#' || x==-1)
{
break;
}
[Link]((char)x);
}
response=[Link]();
[Link](response);
[Link]();
}catch(Exception e)
{
[Link](e);
}
}

}
class ChotaServer
{
private ServerSocket serverSocket;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 96

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
{
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]);
ChotaServer cs=new ChotaServer(portNumber);
}
}
class RequestProcessor extends Thread
{
private Socket ck;
RequestProcessor(Socket socket)
{
[Link]=socket;
start();
}
public void run()
{
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 97

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

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]();
int size=[Link];
byte header[]=new byte[10];
int k=9;
int s=size;
while(k>=0)
{
header[k]=(byte)(s%10);
s=s/10;
k--;
}
[Link]("Size : "+s);
for(k=0;k<=9;k++)
{
[Link](header[k]+" ");
}
Socket socket=new Socket(server,portNumber);
OutputStream outputStream=[Link]();
int bufferSize=1024;
int numberOfBytesToWrite;
int i=0;
[Link]("Sending data....");
[Link](header,0,10);
[Link]();
while(i<[Link])
{
numberOfBytesToWrite=bufferSize;
if(i+bufferSize>[Link])
{
numberOfBytesToWrite=[Link]-i;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 104

}
[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

Socket Programming – The File Server / Client


Create a folder named as socket5
in socket5 create two folders FTServer and FTClient
Create [Link] in socket5\FTServer folder
Create [Link] in socket5\FTClient folder
Copy some files (video or whatever) to FTClient folder
For example my FTClient folder has a file named as 10004.mp4
[Link] (Will compile)
import [Link].*;
import [Link].*;
class FTServer
{
private ServerSocket serverSocket;
private int portNumber;
FTServer(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[])
{
int portNumber=[Link](data[0]);
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 108

FTServer cs=new FTServer(portNumber);


}
}
class RequestProcessor extends Thread
{
private Socket ck;
RequestProcessor(Socket socket)
{
[Link]=socket;
start();
}
public void run()
{
try
{
InputStream inputStream=[Link]();
int headerSize=20;
byte response[]={3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3};
byte header[]=new byte[headerSize];
[Link](header);
OutputStream outputStream=[Link]();
[Link](response,0,headerSize);
[Link]();
int lengthOfFileName;
int e,f;
lengthOfFileName=0;
e=headerSize-1;
f=1;
while(e>=0)
{
lengthOfFileName=lengthOfFileName+(header[e]*f);
e--;
f=f*10;
}
[Link](lengthOfFileName+"((((");
int bufferSize=1024;
byte bytes[]=new byte[bufferSize];
int byteRead=0;
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int byteCount;
while(true)
{
byteCount=[Link](bytes);
[Link](byteCount);
if(byteCount<0) break;
[Link](bytes,0,byteCount);
byteRead+=byteCount;
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 109

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

Try sending huge files and see what happens.


Note : Our FTServer / FTClient implementations are not yet final,
We need to optimize our code, we need to write our own protocol implementation and
we need to add events as discussed in the classroom session.
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 113

Remote Method Invocation (One Way)


Create a folder named as rmi1, in it create [Link]
[Link] (will compile)
import [Link].*;
import [Link].*;
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)
{
[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 114

}
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);

Country country=new Country();


[Link](1);
[Link]("India");
State state=new State();
[Link](101);
[Link]("Madhya Pradesh");
[Link](country);
City city=new City();
[Link](1001);
[Link]("Ujjain");
[Link](state);
Branch branch=new Branch();
[Link](5001);
[Link]("Computer Science");
Category category=new Category();
[Link](6001);
[Link]("General");
Student student=new Student();
Thinking Machines – Java – J2EE – (Book Two Of Three) Page 119

[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

After running the StudentClient, the ui of the StudentServer window

You can end (rmiregistry) and (StudentServer) by pressing Control C

You might also like