(ID: 5142 )
Brief Description
This is core java training program that gives you a good head start with Java as a programming language
Objectives
Pre-Requisites
6 months to 1 Year experience in programming (any language) is desirable.
Hardware Requirements
Each machine must have atleast 512 MB of RAM and 5 GB of free disk space
Software Requirements
Netbeans IDE will be installed by the participants during the course.Oracle 9i or above must be installed on each machine
Network Requirements
All the machines must be connected to the network including Trainers Machine
Object technology is a set of principles guiding software construction together with languages, databases and other tools that support these principles
Models more closely reflect the real world - More accurately describes corporate entities
Stability - A small change in requirements does not mean massive changes in the system under development
Why do we model ?
We build models of complex systems because we cannot apprehend a system in its entirety
Basic Principles of OO
Abstraction
Encapsulation
Modularity
Heirarchy
Abstraction
The essential characteristics of an entity that distinguish it from all other kinds of entities is an Abstraction.
Abstraction allows us to manage complexity by concentrating on the essential characteristics of an entity that distinguish it from other kind of entities
E.g. : A student is a person enrolled in the university, A professor is a person teaching classes at the university.
Encapsulation
Clients depend on interface or the abstract view of the services that are provided by the component
Encapsulation eliminates direct dependencies on the implementation (clients depend on/use interface).
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 2 of 61
It’s possible to change the implementation without adversely affecting the clients. As long as the interface remains unchanged, the clients are not affected.
Modularity
E.g. : Purchase System, Sales System, Accounts System are all different modules of one large ERP system
Heirarchy
Kinds: Aggregation hierarchy, specialization hierarchy, containment hierarchy, inheritance hierarchy, partition hierarchy.
The core objective is to break down complexity which will be manageable and changeable
What is an Object ?
What is an Object ?
Formally, an object is an entity with a well defined boundary and identity that encapsulates its state & behavior:
State: is represented by attributes and relationships
Behavior:is represented by operations, methods, and state machines.
The state of an object is one of the possible conditions in which an object may exist
E.g. Kanetkar is an object of class Professor. The Kanetkar object has state:
Name=Kanetkar
Employee Id=2001
Hire date=02/02/1995
Status=Tenured
Max Load=3
The visible behavior of an object is modeled by the set of messages it can respond to (operations the object can perform
Each object has a unique identity, even if the state is identical to that of another object.
E.g. Professor Kanetkar is from Nagpur. Even if there is a professor with the same name – Kanetkar in Pune teaching C++, they both are distinct objects
What is a Class ?
What is a Class ?
A class is a description of a set of objects that share the same attributes, operations, relationships and semantics. - An object is an instance of class
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 3 of 61
Recognizing the commonalities among the objects and defining classes help us deal with the potential complexity
Attributes of a Class
An attribute is a named property of a class that describes a range of values that instances of the property may hold
Typically attributes are integer, boolean, varchar etc. These are called primitive types.
Operations of a Class
An operation is the implementation of a service that can be requested from any object of the class to affect behavior
The operation is described with a return-type, name, zero and more parameters. This is know as signature of an operation
Often, but not always, invoking an operation on an object changes the object’s data or state
Polymorphism
What is Polymorphism ?
The ability to hide many different implementations behind single interface is polymorphism.
Overloading of member functions & Overriding member functions is static polymorphism - i.e. at compile time you can say, which implementation of the behaviour will be
executed
The Object created of superclass but instantiated to any one of the subclasses based on some condition (run-time) is dynamic or run-time polymorphism For e.g.:
Now this code snippet will execute processSalary of either SalariedEmployee class or ContractEmployee class depending on the value of type. Note that emp is the reference of
type Employee class which is super class of ContractEmployee and SalariedEmployee
Benefits of Polymorphism
Dynamic Polymorphism helps to extend the functionality without changing the existing code.
The contract of the client-class will be with the abstract class and not with the implementation class.
Infact with the help of pattern like Factory Pattern, you can totally shield the implementation classes from the client class.
The client will not know - which is the implementation class providing the required behaviour
What is an Interface ?
It does not have any default behaviour (as opposed to abstract classes - abstract classes can have default behaviour).
The interface serves as a contract between the client and the services that will be offered by the component implementing the interface
Interfaces support “plug-and-play” architectures: You can replace the existing component with a new one which implements the same interface. The client will not have to relearn
how to use the component - i.e. because it has service-contract with the interface and not the component.
When you use the Television Set through a remote-control, you are getting services of your television set through remote -control. You remote control acts as an interface
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 4 of 61
Chapter: 2 - Implementing OO
Identifying Classes
Identify attributes
Identify methods
Writing Classes
Note the attributes and methods defined. These attribites are known as instance variables or member data or field variables of the class
Write a class called CustomerManager.java which will instantiate Customer and invoke methods on it as follows:
Understanding Objects
The CustomerManager class that you have just written instantiates 2 Customers - i.e. creates two objects of class Customer.
Note how the state of the objects are constructed. See how each attribute which constitues the state has a data type.
Note how the behaviour is invoked on the object which changes is state (setter Methods). Also see the return data types of each of the methods
Note that the state can be same of two objects but still it has unique identity
Note the significance of private and public elements in the class, We will discuss protected later.
Let us revisit the same case-study (Sales Management System). There are two types of order - 1) The Local Order and 2) The Export Order. The way taxes are calculated for each
type of order is quite different. Hence it is decided that there will be one Super Class called SalesOrder which will have all the generalized behaviour and 2 Sub Classes of
SalesOrder viz. LocalOrder and ExportOrder which will have specialized behaviour
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 5 of 61
import java.util.Date;
// Please write setter getter methods for all of these instance variables
public abstract void calculateTax();
Abstract methods are those methods which are simply declaration of the services. The other class which will inherit from this class will provide the implementation
Abstract classes are those classes which cannot be instantiated. If there is even a single method in a class which is abstract, the class must be abstract. However, not all methods
in the abstract class must be abstract. There can be some concrete methods as well. Note that calculateTax is the abstract method and setOrderId and getOrderId are concrete
methods.
Now write the OrderManager class which uses the SalesOrder class structure as follows:
if ("L".equalsIgnoreCase(userInput)) {
order = new LocalOrder();
} else {
order = new ExportOrder();
}
order.setOrderId(105);
order.calculateTax();
}
}
See the two techiniques used for using the class structure. The second technique is the example of dynamic polymorphism
In dynamic polymorphism, the ref object declared is of type super class but instantiated to subclass depending on the value of userInput.
Now Let me explain how super and sub-classes in memory and how the ClassLoader uses inheritance structure while instantiating the classes
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 6 of 61
Overriding
In the SalesOrder class written in previous topic-discussion, we have created one abstract method called calculateTax. Writing calculate tax in subclass is NOT overriding. It is
implementing because there is not default behaviour in the super class.
Now note that there is a method called setOrderId in super class which has generalized / default behaviour. Let us write the same method again with exactly same signature in the
ExportOrder class. The business rule says that when ever orderId is set for Export Order, it must immediately set the order date as today's date.
Now execute this method from OrderManager class on expOrder object. Notice that it is this method (overridden) method that gets executed. If you comment this method and re-
compile and run the OrderManager then the method of the super-class is executed. This is Polymorphism - Static Polymorphism
Note the use of super pro-noun here. You may totally override the method by not calling super or invoke the behaviour in the super class and add extra functionality in the sub-
class.
Overloading
Add two methods in the LocalOrder class with same name but two different signatures as follows:
Execute both of these methods from OrderManager on locOrder object and see the results.
Write the public getter (accessor) and setter (mutator) methods for each of the attributes defined above
public Invoice() {
customer = new Customer();
customer.setName("IBM");
}
public void saveInvoice() {
Now create a class called InvoiceManager.java - Create a public static void main method in it and add the following code:
When the new object of Invoice is created, the constructor of Invoice is executed. From the constructor of invoice you have instantiated the customer object which is declared as
instance variable in Invoice. You have set the name of the customer in the constructor. Now when you call saveInvoice method in InvoiceManager class, the saveInvoice method
prints the name of the same customer.
This proves that there is structural relationship between the Client class - Invoice and Supplier class - Customer. The state of the Invoice object includes the state of Customer
object.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 7 of 61
Assignment(s)
Assignment 1
Write a class - Product.java with following attributes: id, name, sellingRate, purchaseRate, discount, quantityOnHand. Write the setter & getter methods for each one of these
attributes. Identify the appropriate data types for each attribute your self. The methods must be properly named for e.g. if id is the attribute, the getter method must be getId and
setter method must be setId
Write a class called ProductManager with main method. In main method, instantiate Product, set values , then get values that you have set and print them using SOP.
Assignment 2
There is a payroll application you need to develop. Employee is one of the abtractions you have identified, but then there are two types of employees - salaried and contract.
Calculating salary is one business method expected to be offered by Employee Abstraction. The methodology of calculating salary for salaried employee is different from the way it
is calculated for contract employee. We want polymorphic behaviour from employee. Write a small application to demonstrate the this. Identify the abstract class, abstract
methods in the abstract class , concrete classes and methods to implement in concrete classes. Also Identify the Generalization Structure - i.e. which classes will extend which
other classes. One of the business methods expected from Employee is that it must allow setting of name of Employee.
Hints: The classes are: Employee, SalariedEmployee, ContractEmployee, SalaryManager (with main method). Now you have to identify which of these classes are abstract and
which one of these are concrete classes.
Assignment 3
In sales application a customer may raise n number of orders. An order is created for a particular customer and then invoice is created for partly or fully for the pending orders.
Identify classes, relationships (associations) and cardinality between them. Create a class diagram to show your classes, relationships and cardinality. Write a small application to
demonstrate the classes, relationships and cardinality.
Hints:
If X is a class having an association with Y, then in X you will create an instance variable for Y.
If one instance of X is related many instance of Y then in X class you will create an an array instance of Y (Y[] instanceOfY = null)
Only creating the right classes is required. A class with main method executing the application is not required
Java
Chapter: 1 - Introduction
With most programming languages, you either compile or interpret a program so that you can run it on your computer.
The Java programming language is unusual in that a program is both compiled and interpreted.
With the compiler, first you translate a program into an intermediate language called Java bytecodes —the platform-independent codes interpreted by the interpreter on the Java platform.
The interpreter parses and runs each Java bytecode instruction on the computer.
Compilation happens just once; interpretation occurs each time the program is executed. The following figure illustrates how this works.
You can think of Java bytecodes as the machine code instructions for the Java Virtual Machine (Java VM).
Every Java interpreter, whether it's a development tool or a Web browser that can run applets, is an implementation of the Java VM.
You can compile your program into bytecodes on any platform that has a Java compiler.
The bytecodes can then be run on any implementation of the Java VM. That means that as long as a computer has a Java VM, the same program written in the Java programming
language can run on Windows 2000, a Solaris workstation, or on an iMac.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 8 of 61
Some of the most popular platforms like Windows 2000, Linux, Solaris, and MacOS.
Most platforms can be described as a combination of the operating system and hardware.
The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
Java VM is the base for the Java platform and is ported onto various hardware-based platforms.
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets
The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.
The following figure depicts a program that's running on the Java platform. As the figure shows, the Java API and the virtual machine insulate the program from the hardware
The Java 2 SDK, Standard Edition v. 1.3. The Java 2 Runtime Environment (JRE) consists of the virtual machine, the Java platform core classes, and supporting files. The Java 2
SDK includes the JRE and development tools such as compilers and debuggers
Understanding Classpath
Path is an enviornmental variable which is used by the operating system and not your java virtual machine
When a folder is included in the "path" environmental variable, the exe(s) that are there in that folder now can be executed from any where in the entire application. So in order to
work with java.exe (the java interpreter) and javac.exe (the java compiler) you must have bin folder of your java installation in the path
After writing your java classes, you would like to execute them using java.exe. Now it is the classpath variable which will be used by java to find the classes you want to execute.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 9 of 61
Both - the Path and Classpath are environmental variables. They must be set using Control Panel >> System >> Advanced >> Environmental Variables- Option
Set the path (or add to existing path) the jdk (which ever version)/bin folder. This will make javac.exe and java.exe available for execution from any folder
Now set the classpath to (or add to existing classpath) . - The dot indicates that the current folder in which your focus is, while executing your application will be considered to be
in the classpath
Now write a simple class (the name of the file must be MyFirstJavaClass.java) using notepad as follows:
Compile the program using the following command on the dos prompt:
javac MyFirstJavaClass.java
java MyFirstJavaClass
Now add this folder in the classpath - you know from where and how
Go to any folder other than c:\working\learningclasspath. Execute the class as using java.exe as follows:
java MySecondJavaClass
Note that the class will execute. This is because the folder in which MySecondJavaClass.class file is created is in the classpath
Repeat this exercise with some MyThirdJavaClass in some other folder and see the results
Please Note: When the you append a ; to the end of your classpath, the current folder is automatically considered to be in classpath. It is as good as appending a . the end of
classpath
The Jar files are simply zip files that contain the .class files
All the classes that you have used till now for e.g. String, System class etc. are all in rt.jar file
Create a folder called c:\working\c1\sales and create a class called SalesManager.java in it. Write a simple method addInvoice in the same with simple SOP - printing "Adding
Invoice in c1". Not create a folder called c:\working\c2\sales and create a class called SalesManager.java in it. Write a simple method addInvoice in the same with simple SOP -
printing "Adding Invoice in c2". Compile both of these classes in their respective folders.
Now create a folder called c:\working\java and create SalesApp.java in this folder with main method. import sales.* in this SalesApp class. In the main method write :
Compile, execute and see the results : JVM will by default take the SalesManager of the folder that is mentioned in the classpath.
This is However, bad design because now the behavior is dependent on the classpath and not your application.
Also note one more important point: The java compiler (javac.exe) reads the classpath - not for the .java file which you ask it to compile. Once it gets the file you want it to
start compilation, it then checks for the availability of other classes used, thereafter, in the classpath.
This point will be very clear to you only after you do assignment 1 and assignment 2 in "ClassPath Assignments"
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 10 of 61
Primitive Data types are those data types which are not classes and are the basic and fundamental data types offered by the programming language. The structure of these data
types may be different in different operating systems. For e.g. an int may be 2 bytes in DOS where as it may be 4 bytes in Unix.
Using Literals:
‘c’ – char
178 – int
8864 – long
37.266D – double
38.99F – float
true - boolean
false - boolean
byte, short, int, float and double are all numeric - primitive data types.
byte, short and int are the ones which does not hold decimal values. Where as float and double can hold decimal values
A given double should always be able to handle any mathemetical operation a given float could.
A float can be type casted to double but a double cannot be type casted to float
If at all you try to convert a double into a float using Wrapper classes (float f = objectOfTypeDouble.floatValue()) then it will convert the value and put it in float if the value is
lesser than or equal to max value of float or else it will put infinity as the value in variable: f
The above metioned type-casting can be done using bracket methods also i.e. float f = (float) d where d is a variable of primitive data type. The end results will also be as same
as discussed above
Please create a new java class called DataTypes.java and add the following code in its main method :
int i = 5;
System.out.println("The value of i is : " + i);
float f = 2.5f;
float result = f + 1.3f;
double d = 2.22;
System.out.println("The value of d is : " + d);
d = f;
// below given is not possible - un comment - you will get compilation error
//f = d;
byte b = 3;
short s = 2;
s++;
f++;
d++;
l++;
Very important: Please note that when you assign a constant to double type variable, even if you do not suffix d at the end of the constant, java implicity considers to be a double.
Where as if you want a constant to be a float you have explicity suffix f to it.
In the same DataTypes.java add the following code for char and boolean and see the results:
char c = 'a';
System.out.println("The value of a is : " + c);
boolean isMarried = true;
boolean orderDispatched = true;
System.out.println("The value of isMarried is : " + isMarried + " And orderDispatched : " + orderDispatched);
You can create objects of these classes to hold its respective primitive value.
The wrapper classes are very useful to exchange values with other primitive data types.
Write the following code in the DataTypes.java, compile and execute and see the results :
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 11 of 61
As such, typecasting is auto. You just have to assign the value of one to the other.
However, you can assign the higher capacity variable with the value of lower capacity of variable. Vice-a-versa is not true.
Write the following code again in same DataTypes.java and see the results:
byte bb = 4;
short ss = 23;
int ii = 3;
long ll = 56;
float ff = 4;
double dd = 9.4;
Still type-casting is possible without bringing the Wrapper classes in picture as follows:
byte b = 27;
int i = 129;
b = (byte) i;
System.out.println("The value of b : " + b);
Note that it prints -127 because 129 exceeds the MAX_VALUE of byte.
Local Variables
When you declare variables in a method its scope is limited to the scope of the method.
Local variables are automatically garbage collected after the method is over and its value is no longer available
Within the method if you declare a variable within a block - it will considered as private to the block and will not be available to the code out of the block. The block can be a plain
block, a if block, try catch block or any other type of block. Try the following code:
{
int empId = 505;
}
/* Following line will throw a compilation error
* This is because, empId is declared above is in a block
* It will not be available out of the block
*/
System.out.println("The value of empId is : " + empId);
Instance variables
The class you declare have instance variables (object variables). These are nothing but the attributes / fields of the class.
When the object is created of a class, the state of the object is constructed with the help of these instance / object variables.
The instance variable is definitely available to all the methods of the class in which is defined.
You can specify any of the following modifiers for the instance variables: public, private and protected
The private variables can be accessed from within the class in which they are defined
The protected variables can be accessed from within the class, its subclasses and from any class which is within the same package
The public instance variables can be accessed from any where in the entire application
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 12 of 61
Instantiate this class from the main method of class called : CustomerManager.java. Try to access all of these variables against the object of Customer class. Compile and study
the compilation errors you get
Class variables
Their value remains the same for each instance of the class - in fact each instance refers to the same copy of the static variable
Static variables can be accessed by the name of the class and also by the object name (Instance Variables can be accessed only through instance/object name)
totalSalesMen ++;
}
public void setName(String aname) {
this.name = aname;
}
Now write SalesManManager.java (with a main method) to instantiate 3 SalesMan objects. obtain the value of totalSalesMen using getTotalSalesMen method. Invoke this method
using any one of the objects declared and also directly by using Class name for e.g. SalesMan.getTotalSalesMen(). See the results.
Note that the static variable - totalSalesMen value remains the same and can be accessed through the name of the class and also through the object. Where as the instance
variable - name values are all different for each instance
Final variables
Final variables are those whose values do not change - once initialized
When a class / instance variable is created as final, you must initialize the value at the time of creating the variable
If a local variable in a method is defined as final, the value can be assigned later, but once assigned, the value cannot be changed
The final variables are nothing but constants in java. As per naming convention in java the final variables are defined in all caps. Re-Collect the Byte.MAX_VALUE,
Double.MAX_VALUE etc.
Method Scope
The scope rules applicable to methods are same as those applicable to instance variables
Methods either return a value of a particular data type (primitive or object) or returns void i.e. no return value
Abstract methods are those which simply declared - no implementation of method is provided
Operators
Arithmetic Operators
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 13 of 61
Write your own class to test each one of these. Develop your own mini-sample classes for the same.
Conditional Operators
Ternary Operator
Op1 ? Op2 : Op3 - If the expression is true, then the second argument is returned or else the third
Write the following code in main method of TernaryOperator.java and see the results:
boolean isSalAcceptable = theSal >= 10000 && department.equalsIgnoreCase("Information Technology") ? true : false;
Extending Classes
Inheritance is the feature where one class inherits its features from the super class.
The super class defines the generalized behavior and subclass defines the specialized behaviour
Also note that all the features (whether public private or protected) are inherited not just the public. The only point is that the private features are accessible only from the class in
which they are defined
Please develop the examples based on following specs: Create a class as follows: public final class Employee..... (complete the rest of the class with some attributes and methods)
and now try to create another class called SalariedEmployee which will extend from Employee class - try to compile - you will get a compilation error
Now declare method a final method as follows: public final void processSalary() ... in Employee class. Remove the final keyword from the declaration of Employee class so that it
can be inherited. Now create a SalariedEmployee class that extends from Employee class - override processSalary method - You will get a compilation error.
Abstract Classes
Create an abstract class called Employee and try to instantiate this class from some other class. You will get a compilation error.
Abstract classes serve as contract between the client classes and the components that subclass the Abstract Classes
Constructors are the methods that are executed as soon as memory is grepped for a particular object - in other words when the object is created in Random-Access-Memory, the
constructor is executed
The constructors may take argument or may not take any argument
If no constructor is defined for a class then a default constructor without any parameter is considered implicitly
But if there is any constructor defined, then only those that are defined is considered to be valid constructors.
Overloading Constructors
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 14 of 61
public Employee() {
System.out.println("The Constructor of Employee");
}
}
}
In the inherited class what ever constructor you write, by default i.e. implicity java makes a call to the default constructor of the super class.
public SalariedEmployee() {
System.out.println("The SalariedEmployee Constructor is executed");
}
}
}
Add the following lines in EmployeeManager class and execute the same and see the results:
If there is no default constructor (the one without any parameters) in the super class, then java will compel you to make an explicit call to non-default constructor from the
constructor of sub-class. Remove the default constructor (the with no parameters) from Employee class and compile it. Now try to re-compile SalariedEmployee - you will get
compilation errors
Now from the sub-class SalariedEmployee, from each constructor make a call to the constructor of the super class as follows:
super(345);
Package in Java
It helps you to group the functionally related classes and interfaces. We will discuss interfaces a bit later.
As said earlier - its determines the namespace. i.e. if a class is defined in a package as public, it will be visible to all classes within the package as well as all classes out of the
package - Whereas - if the class in package is declared with no modifier class Employee { then it will be visible to only those classes which are in the same package and not to the
classes which are out of the package.
package sales;
When a package statement is used in a class, it is a must for the class to be in the folder the name of which as same as the name of the package used in the class. Remember the
names- here are case-sensitive.
Importing Classes
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 15 of 61
If you have a class in sales package and you want to instantiate and use a class which is in accounts package, you must import the class you want to use from accounts package.
Consider the following:
package sales;
import accounts.CreditAccount
public class OrderManager {
// attributes
// methods
}
}
You have a class called CreditAccount which is in accounts package. You want to use it in OrderManager class in sales package. Note the how the package statement is declared
and also the import statement
* does not mean recursive import. For e.g. if you give import accounts.* - it will tell the compiler that : "ALL THE CLASSES FROM ACCOUNTS PACKAGE MUST BE IMPORTED". It
does NOT mean that all the packages and classes within recurssive packages are to be imported
import sales.SalesOrder;
import accounts.Account;
package sales;
package accounts;
public Account() {
System.out.println("Account Object successfully created");
}
}
Writing Interface
Now write a class called Invoice which implements this interface as follows :
Compile Invoice without implementing methods of TaxCalculator - You will get compilation errors.
You must implement all the method of the interface that a class implements or else declare the class abstract. What you must do is dependent on how you design your application.
You have a Date class in java.util package. You also have Date class in java.sql package. If you write import statements in SalesManager.java as follows:
import java.util.*;
import java.sql.*;
Java will force you to qualify Date with its package name in all the methods of the class which you are writing.
Now consider that the import statements in your SalaryManager.java are written as follows:
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 16 of 61
import java.util.Date;
import java.sql.*;
Now if you do not qualify Date with the package any where in SalaryManager.java, java will not complaint. Since you explicity specified the exact class to be imported from util
package, it will consider that you intend to you java.util.Date
Assignment(s)
ClassPath Assignments
Assignment 1
Please create some a class in c:\working\assignments\sales\SalesManager.java. Write a simple main method in the class having one single SOP statement. Set the classpath in
such a way that you must be able to compile this class from c:\working\assignments\purchase folder.
Assignment 2
Create a class in c:\working\assignments\accounts\Account.java. Write a method called debitAccount - write a simple SOP in this method. Now go to SalesManager.java class in
c:\working\assignments\sales and instantiate Account class from main method of SalesManager. Set the classpath in such a way that keeping the focus in
c:\working\assignments\sales folder, you must be able to compile your SalesManager.
Assignment 3
Write classes : ClassA, ClassB, ClassC in 3 different folders in c:\. Compile all these classes. Write a class called ClientClass in c:\working\assignments\sales. Instantiate all the 3
classes. Set the classpath in such a way that you must be able to compile ClientClass being in c:\working\assignments\sales folder.
Assignment 1
In Sales application there is a class called Invoice which has a method called calculateInvoiceAmount. Write this class and method. In this method demonstrate the calculation of
invoice amount as follows:
Calculate list amount as 50 units of quantity multiplied by Rs 300 and 25 paise as rate
Then deduct discount of 4.5 %
Then add Octroi of Rs 200 and 50 paise
Then add Handling Charges of Rs 200
Add Sales Tax of 5.2 %
This gives you the final amount. Print this final amount after all the calculations and see the results.
Assignment 2
Create a program that reads an unspecified number of integer arguments from the command line and adds them together. For example, suppose that you enter the following:
java Adder 1 3 2 10
The program should display 16 and then exit. The program should display an error message if the user enters only one argument.
Assignment 3
Create a program that is similar to the previous one but has the following differences:
Instead of reading integer arguments, it reads floating-point arguments.
It displays the sum of the arguments, using exactly two digits to the right of the decimal point.
You can use the following code to format your answer to 2 digits right to the decimal point
Assignment 4
We have already written code to view the max values of byte, short, int, long, double and float. Now write a program to display the min values of each one of these data types
Assignment 5
Write a program that calculates the number of Indian Rs equivalent to a given number of US Dollars. Assume an exchange rate of 44.85062 Rs per dollar.
Assignment 1
Write a class TaxValueObject with attributes as private and methods as public. Attributes are : id, name, taxRate. Write public setter getter methods for all of these attributes.
Create another class called TaxManager.java with a main method. In main method instantiate TaxValueObject and try to put values in id and name of the instance directly without
using the method. Compile and note the error messages you get. Now make each one of those variables as protected in TaxValueObject and re-compile it. Now Re-Compile
TaxManager - now see the results.
Constructor Assignments
Create a Class called Tax.java. There is an instance variable in this class called taxRate. Write a public getter method for this instance variable - only getter. Write a overloaded
constructor with 1 parameter to initialize the value of taxRate in this constructor.
Create a class called LocalTax - sub class of Tax. Create two constructor here as well. 1 - with no parameter and the other with 1 parameter - Do not write any thing in any
constructor. Now instantiate LocalTax using the constructor with 1 parameter in main method of TaxManager.java . Execute getter method to get the value of taxRate and print
the same. What value gets printed ?. Now make appropriate changes in the constructor in LocalTax with 1 parameter so that now when you execute TaxManager.java - you get
the value that you passed while creating LocalTax object.
Package Assignments
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 17 of 61
Redo all the examples specified in "Classpath Assignments" page. This time each class must contain the package statement right on the top. The package name must be as same
as the folder in which the classes are. The classpaths must now be set accordingly and also the import statements in each class so that it is accessible.
This is very important assignment as you will finally make your understanding of packages, import statements, classpaths crystal clear
Chapter: 2 - Arrays
What is an Array
An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created (at runtime). After creation, an array is a fixed-
length structure.
An array element is one of the values within an array and is accessed by its position within the array
Array of Primitive-Types
Array of primitive-types
The array once declared, by itself is an object (which may contain primitive or objects as elements)
Once array is declared of a particular type, you can put only those elements in the array which are of that type
Working Examples
// arrayOfDeptType[4] = 'X';
Create the arrays of other primitive data types in the above class and see the results
The way you create array of primitive data types, you can also create array of objects.
Once an array of a particular object is created you can put only that type of object in the array
Create a class called StringArray.java and write the following in main method :
departmentNames[0] = "Accounts";
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 18 of 61
departmentNames[1] = "H.R.";
departmentNames[2] = "I.T";
departmentNames[3] = "P.R.";
departmentNames[4] = "Sales";
Also write 3 more java classes : IntegerArray.java, DoubleArray.java & FloatArray.java and write the code of your own (the way I have demonstrated in StringArray.java) in main
method and see the results
You can also create array of objects which belongs to classes defined by you in your application
Now create CustomerManager.java and write the following in main method, compile and see the results:
Customer myCustomers[] = new Customer[] {new Customer(), new Customer(), new Customer()};
myCustomers[0].setId(101);
myCustomers[0].setName("IBM");
myCustomers[1].setId(102);
myCustomers[1].setName("3I-Infotech");
myCustomers[2].setId(103);
myCustomers[2].setName("Info Sys");
myCustomers[3].setId(104);
// please note that we are not setting the values for 5th element
// Also note that we have given i < 4 and not i < 5 - I ll explain Why.
for (int i = 0; i < 4; i++) {
System.out.println("The id of " + i + " Customer is :" + customers[i].getId() + " and name is : " + customers[i].getName());
//customers[4].setId(205);
In double dimension arrays each element will be an array itself. So you can say - it is an array of arrays
Write the following code in main method of a class - DoubleDimensionArray.java and see the results
int doubleDimension[][] = new int[][] {{1, 2}, {3, 4}, {5, 6}};
System.out.println("The length is : " + doubleDimension.length + " And of Col : " + doubleDimension[0].length);
for (int i = 0; i < doubleDimension.length; i++) {
Please write your own example with float as the data type for double dimension array and see the results.
One more exercise: Write a new class that will create two dimensional array for Customer objects.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 19 of 61
Assignment(s)
Array Assignments
The following program, WhatHappens, contains a bug. Find it and fix it.
//
// This program compiles but won't run successfully.
//
public class WhatHappens {
public static void main(String[] args) {
StringBuffer[] stringBuffers = new StringBuffer[10];
String[] skiResorts = {
"Whistler Blackcomb", "Squaw Valley", "Brighton",
"Snowmass", "Sun Valley", "Taos"
};
Ammend above program to print only 2nd and the last element of the array. Increase the number of elements in the array and still your program must print exactly 2nd and which
ever is the last element of the array.
Create array of TaxValueObject (You know the structure of this class) having 5 elements in it. Initialize the state of each object in the array and print the same using a for loop.
Print
Create a class called InvoiceValueObject containing following fields : id, customerId, amount. Create a constructor accepting 3 parameters to initialize the value of all the instance
variables. You know the data-types of each one of these attributes and also include the getter methods for them - only getter methods. Now create InvoiceMISManager.java class
which will create 5 objects of class InvoiceValueObject in an array. The array must and must be initialized on the same line in which it created for e.g. String[] names = new
String[] {new String("Delhi"), new String("Mumbai"), new String("Bangalore")}. This code snippet has created array of String objects having 3 elements. This technique must be
used to create 5 objects of class InvoiceValueObject in array. Calculate the total of all the invoice amount and display the same.
What is an Exception
What is an Exception
The Java language uses exceptions to provide error-handling capabilities for its programs
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system.
The exception object contains information about the exception, including its type and the state of the program when the error occurred.
The runtime system is then responsible for finding some code to handle the error.
In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the
set of methods in the call stack of the method where the error occurred.
The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate
exception handler.
An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler.
Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception.
Advatages of Exception
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 20 of 61
Errors
When a dynamic linking failure or some other "hard" failure in the virtual machine occurs, the virtual machine throws an Error
In addition, it's unlikely that typical Java programs will ever throw Errors either
Exception class
Most programs throw and catch objects that derive from the Exception class.
Exceptions indicate that a problem occurred but that the problem is not a serious systemic problem.
The Exception class has many descendants defined in the Java packages.
One Exception subclass has special meaning in the Java language: RuntimeException
Runtime Exceptions
The RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime).
An example of a runtime exception is NullPointerException, which occurs when a method tries to access a member of an object through a null reference.
do {
// try {
c = in.read();
// } catch (IOException ex) {
// System.out.println("The IOException is : " + ex.getMessage());
// }
if (Character.isWhitespace((char)c))
return buf.toString();
else
buf.append((char)c);
} while (c != -1);
return buf.toString();
}
Try to compile this class - and note that you will get compilation error
Now uncomment the try catch block and compile. Yes - it will compile successfully now.
When you read a file into FileReader object, it is quite possible that the file you are trying to read does not exist. An in such a case the FileReader constructor throws a
FileNotFoundException
You must catch this exception or else your .java file will fail to compile.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 21 of 61
Write a new class called FileManager.java and write the following code in its main method:
Create text file in c:\working\learningexceptions called TheTextFile.txt and write a statement :"Java is the best programming language" - Execute FileManager and see the results.
In FileManager.java change the name of the file to Yabadabadoo instead of TheTextFile.txt and then re-compile and execute it - see the results. Specially note that the catch part
now gets executed.
The catch block is executed when the exception specified in the catch clause occurs.
There can be more than one catch blocks for a single try
Modiy the InputFile written earlier to accomodate the following lines in the constructor just after the line where you have written: in = new FileReader(filename);
Class.forName("learningexceptions.InputFile");
Now add one more catch to the existing try in the constructor as follows:
There can be as many catch blocks as it would take to successfully write all the code that throws exception.
Catch
Java requires that a method either catch or specify all checked exceptions that can be thrown within the scope of the method. This requirement has several components that need
further description: "catch", "specify," "checked exceptions," and "exceptions that can be thrown within the scope of the method."
A method can catch an exception by providing an exception handler for that type of exception.
The page, Dealing with Exceptions, introduces an example program, talks about catching exceptions, and shows you how to write an exception handler for the example program.
Specify
If a method chooses not to catch an exception, the method must specify that it can throw that exception.
Why did the Java designers make this requirement? Because any exception that can be thrown by a method is really part of the method's public programming interface:
callers of a method must know about the exceptions that a method can throw in order to intelligently and consciously decide what to do about those exceptions.
In the method signature you specify the exceptions that the method can throw.
The next page, Dealing with Exceptions, talks about specifying exceptions that a method throws and shows you how to do it.
Checked Exceptions
Java has different types of exceptions, including I/O Exceptions, runtime exceptions, and exceptions of your own creation, to name a few. Of interest to us in this discussion are
runtime exceptions.
Runtime exceptions are those exceptions that occur within the Java runtime system. This includes arithmetic exceptions (such as when dividing by zero), pointer exceptions (such
as trying to access an object through a null reference), and indexing exceptions (such as attempting to access an array element through an index that is too large or too small).
Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. The cost of checking for runtime exceptions often exceeds the benefit of
catching or specifying them.
Thus the compiler does not require that you catch or specify runtime exceptions, although you can. Checked exceptions are exceptions that are not runtime exceptions
and are checked by the compiler; the compiler checks that these exceptions are caught or specified.
Some consider this a loophole in Java's exception handling mechanism, and programmers are tempted to make all exceptions runtime exceptions. In general,
this is not recommended. Runtime Exceptions--The Controversy contains a thorough discussion about when and how to use runtime exceptions.
The statement "exceptions that can be thrown within the scope of the method" may seem obvious at first: just look for the throw statement.
However, this statement includes more than just the exceptions that can be thrown directly by the method: the key is in the phrase within the scope of. This phrase includes any
exception that can be thrown while the flow of control remains within the method. This statement includes both
Exceptions that are thrown directly by the method with Java's throw statement.
Exceptions that are thrown indirectly by the method through calls to other methods
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 22 of 61
The following example defines and implements a class named ListOfNumbers. The ListOfNumbers class calls two methods from classes in the Java packages that can throw
exceptions.
import java.io.*;
import java.util.Vector;
public ListOfNumbers () {
victor = new Vector(size);
for (int i = 0; i < size; i++)
victor.addElement(new Integer(i));
}
public void writeList() {
PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
out.close();
}
}
Upon construction, ListOfNumbers creates a Vector that contains ten Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named
writeList that writes the list of numbers into a text file called OutFile.txt.
The writeList method calls two methods that can throw exceptions. First, the following line invokes the constructor for FileWriter, which throws an IOException if the file cannot be
opened for any reason:
Second, the Vector class's elementAt method throws an ArrayIndexOutOfBoundsException if you pass in an index whose value is too small (a negative number) or too large (larger
than the number of elements currently contained by the Vector). Here's how ListOfNumbers invokes elementAt:
If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor, but does not display an error
message about the exception thrown by elementAt.
This is because the exception thrown by the FileWriter constructor, IOException, is a checked exception and the exception thrown by the elementAt method,
ArrayIndexOutOfBoundsException, is a runtime exception.
Now that you've familiarized yourself with the ListOfNumbers class and where the exceptions can be thrown within it, you can learn how to write exception handlers to catch and
handle those exceptions.
The three pages that follow cover the three components of an exception handler -- the try, catch, and finally blocks.
They show you how to write an exception handler for the ListOfNumbers class's writeList method, described in The ListOfNumbers Example.
The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. In general, a try block looks like this:
try {
Java statements
}
The segment of code labelled Java statements is composed of one or more legal Java statements that could throw an exception.
To construct an exception handler for the writeList method from the ListOfNumbers class, you need to enclose the exception-throwing statements of the writeList method within a
try block.
There is more than one way to accomplish this task. You could put each statement that might potentially throw an exception within its own try statement, and provide separate exception handlers for each try. Or you could
put all of the writeList statements within a single try statement and associate multiple handlers with it. The following listing uses one try statement for the entire method because the code tends to be easier to read.
try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));
The try statement governs the statements enclosed within it and defines the scope of any exception handlers associated with it. In other words, if an exception occurs within the
try statement, that exception is handled by the appropriate exception handler associated with this try statement.
A try statement must be accompanied by at least one catch block or one finally block.
As you learned on the previous page, the try statement defines the scope of its associated exception handlers. You associate exception handlers with a try statement by providing
one or more catch blocks directly after the try block:
try {
...
} catch ( . . . ) {
...
} catch ( . . . ) {
...
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 23 of 61
}...
There can be no intervening code between the end of the try statement and the beginning of the first catch statement. The general form of Java's catch statement is:
The catch statement requires a single formal argument. The argument to the catch statement looks like an argument declaration for a method. The argument type,
SomeThrowableObject, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class defined in the java.lang
package.
You access the instance variables and methods of exceptions in the same manner that you access the instance variables and methods of other objects. getMessage is a method
provided by the Throwable class that prints additional information about the error that occurred.
The writeList method from the ListOfNumbers class uses two exception handlers for its try statement, with one handler for each of the two types of exceptions that can be thrown
within the try block -- ArrayIndexOutOfBoundsException and IOException.
try {
...
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " +
e.getMessage());
}
The two exception handlers used by the writeList method are very specialized. Each handles only one type of exception. The Java language allows you to write general exception
handlers that handle multiple types of exceptions.
Java exceptions are Throwable objects; they are instances of Throwable or a subclass of Throwable. The Java packages contain numerous classes that derive from Throwable and
thus, build a hierarchy of Throwable classes.
Your exception handler can be written to handle any class that inherits from Throwable. If you write a handler for a "leaf" class (a class with no subclasses), you've written a
specialized handler: it will only handle exceptions of that specific type.
If you write a handler for a "node" class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its
subclasses.
Let's modify the writeList method once again. Only this time, let's write it so that it handles both IOExceptions and ArrayIndexOutOfBoundsExceptions. The closest common
ancester of IOException and ArrayIndexOutOfBoundsException is the Exception class. An exception handler that handles both types of exceptions looks like this:
try {
...
} catch (Exception e) {
System.err.println("Exception caught: " + e.getMessage());
}
The Exception class is pretty high in the Throwable class hierarchy. So in addition to the IOException and ArrayIndexOutOfBoundsException types that this exception handler is
intended to catch, it will catch numerous other types.
Generally speaking, your exception handlers should be more specialized. Handlers that can catch most or all exceptions are typically useless for error recovery
because the handler has to determine what type of exception occurred anyway to determine the best recovery strategy. Also, exception handlers that are too
general can make code more error prone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not
intended
The final step in setting up an exception handler is providing a mechanism for cleaning up the state of the method before (possibly) allowing control to be passed to a different
part of the program. You do this by enclosing the cleanup code within a finally block.
The try block of the writeList method that you've been working with opens a PrintWriter. The program should close that stream before allowing control to pass out of the writeList
method. This poses a somewhat complicated problem because writeList's try block has three different exit possibilities:
1. The new FileWriter statement failed and threw an IOException.
2. The victor.elementAt(i) statement failed and threw an ArrayIndexOutOfBoundsException.
3. Everything succeeded and the try block exited normally.
The runtime system always executes the statements within the finally block regardless of what happens within the try block. Regardless of whether control exits the writeList
method's try block due to one of the three scenarios listed previously, the code within the finally block will be executed.
This is the finally block for the writeList method. It cleans up and closes the PrintWriter.
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 24 of 61
try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));
This try block in this method has three different exit possibilities:
1. The new FileWriter statement fails and throws an IOException.
2. The victor.elementAt(i) statement fails and throws an ArrayIndexOutOfBoundsException.
3. Everything succeeds and the try statement exits normally.
Create situation (Change the name of the file to invalid name - make the filename start with '?') or any thing else to run your program through each one of the situations
mentioned above
Before you can catch an exception, some Java code somewhere must throw one.
Any Java code can throw an exception: your code, code from a package written by someone else (such as the packages that come with the Java development environment), or
the Java runtime system.
Regardless of who (or what) throws the exception, it's always thrown with the Java throw statement.
All Java methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. In the Java system, throwable objects are
instances of any subclass of the Throwable class. Here's an example of a throw statement:
throw someThrowableObject;
If you attempt to throw an object that is not throwable, the compiler refuses to compile your program and displays an error message similar to the following:
Let's look at the throw statement in context. The following method is taken from a class that implements a common stack object. The pop method removes the top element from
the stack and returns it:
if (size == 0)
throw new EmptyStackException();
public InvalidBalanceException() {
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 25 of 61
}
}
Note that you can also extend one of your own exceptions from any of your own (some other exception) or from any exception already defined in java api(s).
What is JRE
It is JavaTM runtime environment.
A subset of the Java Development Kit (JDK) for users and developers who want to redistribute the runtime environment.
The Java runtime environment consists of the Java virtual machine (JVM), the Java core classes, and supporting files.
The JRE does not contain any of the development tools (such as appletviewer or javac) or classes that pertain only to a development environment.
The JRE for Win 32 platforms is bundled with its own installer program.
The availability of an easily installable JRE adds flexibility to the ways in which software suppliers can deliver software to their customers.
Vendors of applications have the option of not bundling a copy of the JRE with their software.
Once a user has installed the JRE, it can be used to run any number of applications written in the Java programming language.
(JVM)—A component of the Java runtime environment that JIT-compiles Java bytecodes, manages memory, schedules threads, and interacts with the host operating environment
(e.g., a Web browser running the Java program).
Java Virtual Machine (JVM) is a Java interpreter and runtime environment. Java source code is compiled into a format called bytecode (files with a .class extension), which can
then be executed by a Java interpreter. Web browsers are often equipped with Java virtual machines.
You first run "javac", the Java Compiler, which turns the Java code into what is known as "bytecodes" and puts them into the "hello.class" file.
This class file can then be interpreted on any machine which has a Java Virtual Machine on it. The key word here is "interpreted".
The Java Virtual Machine processes each of the bytecodes in the .class file and executes them. This is similar to what other interpreted languages do, such as Basic, LISP, and
Smalltalk.
When a JIT is present, after reading in the .class file for interpretation, it hands the .class file to the JIT.
The JIT will take the bytecodes and compile them into native code for the machine that you are running on.
It can actually be faster to grab the bytecodes, compile them, and run the resulting executable than it is to just interpret them. The JIT is an integral part of the Java Virtual Machine
Although Java compiler ensures that the source code doesn’t violate the safety rules, what if the runtime environment receives a .class file which is compiled by a hostile compiler.
The answer is simple: the Java run-time system does not trust the incoming code, but subjects it to bytecode verification.
The tests range from the simple verification of the code that the format of the code fragment is correct, to passing each code fragment through a simple theorem prover to
establish that it plays by the rule:
It doesn’t forge (fake) pointers.
It doesn’t violate access restrictions
It accesses objects as what they are (for e.g. Thread objects are used as thread objects and not anything else)
Object field accesses are known to be legal – private public or protected.
Java is a language that is safe, plus run-time verification of generated code, establishes a base set of guarantees that interfaces cannot be violated
The Byte Code verifier traverses the bytecodes, constructs the type state information, and verifies the type of parameters to all the bytecode instructions
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 26 of 61
Assignment(s)
Write a class Invoice which will have a method called saveInvoice. It must throw InsufficientInventoryException, InsufficientCustomerCreditLimitException and
InvalidOrderException.
Write a class InvoiceManager with a main method and invoke saveInvoice method on Invoice from it. Catch the appropriate exceptions and compile the class
Chapter: 4 - Threads
What is a Thread ?
What is a Thread ?
We write lot of programs where each has a beginning, an execution sequence, and an end.
A single thread also has a beginning, a sequence, and an end and at any given time during the runtime of the thread, there is a single point of execution.
However, a thread itself is not a program; it cannot run on its own. Rather, it runs within a program. The following figure shows this relationship.
Definition of Thread
The real hoopla surrounding threads is not about a single sequential thread.
Rather, it's about the use of multiple threads in a single program, running at the same time and performing different tasks.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 27 of 61
A thread is similar to a real process in that a thread and a running program are both a single sequential flow of control.
A thread is considered lightweight because it runs within the context of a full-blown program and takes advantage of the resources allocated for that program and the program's
environment.
As a sequential flow of control, a thread must carve out some of its own resources within a running program.
The code running within the thread works only within the context of the program (process). Thus, some other texts use execution context as a synonym for thread.
In version 1.3, support for timers was added to the java.util package. The Timer class in that package schedules instances of a class called TimerTask . See: Remider.java
import java.util.Timer;
import java.util.TimerTask;
/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/
Task scheduled.
Time's up!
This simple program illustrates the basic parts of implementing and scheduling a task to be executed by a timer thread.
Implement a custom subclass of TimerTask. The run method contains the code that performs the task. In this example, the subclass is named RemindTask.
Create a thread by instantiating the Timer class.
Instantiate the timer task object (new RemindTask()).
Schedule the timer task for execution. The example uses the schedule method, with the timer task as the first argument and the delay in milliseconds (5000) as the second
argument.
Another way of scheduling a task is to specify the time when the task should execute. For example, the following code schedules a task for execution at 11:01 p.m.:
By default, a program keeps running as long as its timer threads are running. You can terminate a timer thread in more than 1 ways:
Invoke cancel on the timer. You can do this from anywhere in the program, such as from a timer task’s run method.
Invoke the System.exit method, which makes the entire program (and all its threads) exit. The Reminder example uses the first scheme, invoking the cancel method from
the timer task’s run method.
Sometimes, timer threads aren’t the only threads that can prevent a program from exiting when expected. For example, if you use the AWT at all—even if only to make
beeps—the AWT automatically creates a nondaemon thread that keeps the program alive.
The following modification of Reminder adds beeping, which requires us to also add a call to the System.exit method to make the program exit. Significant changes are in
boldface:
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 28 of 61
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;
/**
* Simple demo that uses java.util.Timer to schedule a task to execute
* once 5 seconds have passed.
*/
Write the following AnnoyingBeep.java to repeat the task after evey 1 second:
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Toolkit;
/**
* Schedule a task that executes once every second.
*/
public AnnoyingBeep() {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(),
0, //initial delay
1 * 1000); //subsequent rate
}
class RemindTask
extends TimerTask {
int numWarningBeeps = 3;
The run method gives a thread something to do. Its code implements the thread's running behavior.
It can do anything that can be encoded in Java statements: compute a list of prime's, sort some data, perform some animation.
The Thread class implements a generic thread that, by default, does nothing. That is, the implementation of its run method is empty. This is not particularly useful, so the Thread
class defines API that lets a Runnable object provide a more interesting run method for a thread.
You can provide a run method for a thread by Subclassing Thread and Overriding run
The first way to customize what a thread does when it is running is to subclass Thread (itself a Runnable object) and override its empty run method so that it does something.
Let's look at the SimpleThread class (we will write a class to use this class later), the first of two classes in this example, which does just that:
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 29 of 61
}
System.out.println("DONE! " + getName());
}
}
The first method in the SimpleThread class is a constructor that takes a String as its only argument. This constructor is implemented by calling a superclass constructor and is
interesting to us only because it sets the Thread's name, which is used later in the program.
The next method in the SimpleThread class is the run method. The run method is the heart of any Thread and where the action of the Thread takes place.
The run method of the SimpleThread class contains a for loop that iterates ten times. In each iteration the method displays the iteration number and the name of the Thread, then
sleeps for a random interval of up to 1 second.
After the loop has finished, the run method prints DONE! along with the name of the thread. That's it for the SimpleThread class.
The TwoThreadsDemo class provides a main method that creates two SimpleThread threads: one is named "Jamaica" and the other is named "Fiji". (If you can't decide on where
to go for vacation you can use this program to help you decide--go to the island whose thread prints "DONE!" first.)
The main method also starts each thread immediately following its construction by calling the start method.
Assignment(s)
Thread Assignments
Convert AnnoyingBeep.java (that we have already written) so that the initial delay is 5 seconds, instead of 0.
Write a class called TraningNomination.java which help you decide which subject you must nominate for training - J2EE or .NET. Hint: Use the same concept we have used in
TwoThreadsDemo class.
Collection Framework
A Collection (sometimes called as container) is simple an object that groups multiple objects in single element
Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another
The core collection interfaces are the interfaces used to manipulate collections, and to pass them from one method to another.
The basic purpose of these interfaces is to allow collections to be manipulated independently of the details of their representation.
The core collection interfaces are the heart and soul of the collections framework.
When you understand how to use these interfaces, you know most of what there is to know about the framework.
The core collection interfaces form a hierarchy includes A Set is a special kind of Collection, and a SortedSet is a special kind of Set, and so forth.
Note also that the hierarchy consists of two distinct trees: a Map
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 30 of 61
Collection is used to pass collections around and manipulate them when maximum generality is desired.
It is used to represent sets like the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine
The user of a List generally has precise control over where in the List each element is inserted.
If you've used Vector , you're already familiar with the general flavor of List
Maps cannot contain duplicate keys: Each key can map to at most one value.
If you've used Hashtable , you're already familiar with the general flavor of Map
This interface, given that a Collection represents a group of objects, it has methods to tell you how many elements are in the collection (size, isEmpty), to check if a given object is
in the collection (contains), to add and remove an element from the collection (add, remove), and to provide an iterator over the collection (iterator).
The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't.
The add method guarantees that the Collection will contain the specified element after the call completes, and returns true if the Collection changes as a result of the call.
Similarly, the remove method is defined to remove a single instance of the specified element from the Collection, assuming the Collection contains the element, and to return true
if the Collection was modified as a result
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
myCustomers.add("IBM");
myCustomers.add("ATOS Origin");
myCustomers.add("3I - Infotech");
Iterator i = myCustomers.iterator();
while (i.hasNext()) {
String customer = (String) i.next();
System.out.println("The Customer Name is : " + customer);
}
Also Note the use of Iterator which provides standard mechanism of iterating through the
Array Operations
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 31 of 61
The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input.
They allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller
to provide an array or to choose the runtime type of the output array.
Use a for loop and display the contents of the Object array.
Suppose myCustomers is known to contain only strings. The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the
number of elements in myCustomers.
Bulk Operations
The bulk operations perform some operation on an entire Collection in a single shot. They are shorthands in the sense that each of them can be simulated, perhaps less efficiently,
using the operations described above.
containsAll: Returns true if the target Collection contains all of the elements in the specified Collection (c).
addAll: Adds all of the elements in the specified Collection to the target Collection.
removeAll: Removes from the target Collection all of its elements that are also contained in the specified Collection.
retainAll: Removes from the target Collection all of its elements that are not also contained in the specified Collection. That is to say, it retains only those elements in the
target Collection that are also contained in the specified Collection.
clear: Removes all elements from the Collection.
The addAll, removeAll, and retainAll methods all return true if the target Collection was modified in the process of executing the operation.
As a simple example of the power of the bulk operations, consider following idiom to remove all instances of a specified element, e from a Collection, c.:
c.removeAll(Collections.singleton(e));
More specifically, suppose that you want to remove all of the null elements from a Collection:
c.removeAll(Collections.singleton(null));
This idiom uses Collections.singleton, which is a static factory method that returns an immutable Set containing only the specified element.
Use these methods in the program specified on previous slide and see the results.
The Set
The Set interface extends Collection and contains no methods other than those inherited from Collection.
One of the general-purpose implementation of Set interface is : HashSet which stores its elements in Hashtable and the other implementation is TreeSet
// Bulk Operations
boolean containsAll(Collection c);
boolean addAll(Collection c); // Optional
boolean removeAll(Collection c); // Optional
boolean retainAll(Collection c); // Optional
void clear(); // Optional
// Array Operations
Object[] toArray();
Object[] toArray(Object a[]);
}
Here's a simple but useful Set idiom. Suppose you have a Collection, c, and you want to create another Collection containing the same elements, but with all duplicates eliminated.
The following one-liner does the trick:
It works by creating a Set (which, by definition, cannot contain duplicates) initially containing all the elements in c.
Try the above in your program written earlier. Create a collection which will have duplicates, loop through it and then create another collection as shown above and then again
loop through it so that only unique values are displayed
Basic Operations
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 32 of 61
The size operation returns the number of elements in the Set (its cardinality).
The add method adds the specified element to the Set if it's not already present, and returns a boolean indicating whether the element was added.
Similarly, the remove method removes the specified element from the Set if it's present, and returns a boolean indicating whether the element was present.
Here's a little program that takes the words in its argument list and prints out any duplicate words, the number of distinct words, and a list of the words with duplicates
eliminated:
import java.util.*;
Now let's run the program and pass the following command line arguments:
Duplicate detected: i
Duplicate detected: i
4 distinct words detected: [came, left, saw, i]
The implementation type of the Set in the example above is HashSet, which makes no guarantees as to the order of the elements in the Set.
If you want the program to print the word list in alphabetical order, all you have to do is to change the set's implementation type from HashSet to TreeSet.
Making this trivial one-line change causes the command line in the previous example to generate the following output:
Note that the example code always refers to the collection by its interface type (Set), rather than by its implementation type (HashSet). This is a strongly
recommended programming practice, as it gives you the flexibility to change implementations merely by changing the constructor. If the variables used to
store a collection, or the parameters used to pass it around, are declared to be of the collection's implementation type rather than its interface type, then all
such variables and parameters must be changed to change the collection's implementation type. Furthermore, there's no guarantee that the resulting program
will work; if the program uses any non-standard operations that are present in the original implementation type but not the new one, the program will fail.
Referring to collections only by their interface keeps you honest, in the sense that it prevents you from using any non-standard operations.
Bulk Operations
The bulk operations are particularly well suited to Sets: they perform standard set-algebraic operations. Suppose s1 and s2 are Sets.
s1.containsAll(s2): Returns true if s2 is a subset of s1. (For example, set s1 is a subset of s2 if set s2 contains all the elements in s1.)
s1.addAll(s2): Transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all the elements contained in either set.)
s1.retainAll(s2): Transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements that are common in both sets.)
s1.removeAll(s2): Transforms s1 into the (asymmetric) set difference of s1 and s2. (For example, the set difference of s1 - s2 is the set containing all the elements found in s1 but
not in s2.)
The array operations don't do anything special for Sets beyond what they do for any other Collection.
A Listis an ordered Collection(sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface
includes operations for:
Positional Access: manipulate elements based on their numerical position in the list.
Search: search for a specified object in the list and return its numerical position.
List Iteration: extend Iterator semantics to take advantage of the list's sequential nature.
Range-view: perform arbitrary range operations on the list.
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator listIterator();
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 33 of 61
// Range-view
List subList(int from, int to);
}
The JDK contains two general-purpose List implementations. ArrayList, which is generally the best-performing implementation, and LinkedListwhich offers better performance
under certain circumstances. Also, Vector has been retrofitted to implement List.
Collection Operations
The remove operation always removes the first occurrence of the specified element from the list.
The add and addAll operations always append the new element(s) to the end of the list. Thus, the following idiom concatenates one list to another:
list1.addAll(list2);
Here's a non-destructive form of this idiom, which produces a third List consisting of the second list appended to the first:
Two List objects are equal if they contain the same elements in the same order
Positional Access
Create a list object in the new class called MySimpleList.java and write the following as follows:
Now create a list using: Arrays.asList(args) - which helps you to create a list out of an array and see the results
ListIterator
As you'd expect, the Iterator returned by List's iterator operation returns the elements of the list in proper sequence.
Additionally, List provides a richer iterator, called a ListIterator, that allows you to traverse the list in either direction, modify the list during iteration, and obtain the current
position of the iterator.
The ListIterator interface is summarized below (including the three methods it inherits from Iterator):
boolean hasPrevious();
Object previous();
int nextIndex();
int previousIndex();
The three methods that ListIterator inherits from Iterator (hasNext, next, and remove) are intended to do exactly the same thing in both interfaces.
The hasPrevious and previous operations are exact analogues of hasNext and next. The former operations refer to the element before the (implicit) cursor, whereas the latter refer
to the element after the cursor
ListIterator (Contd.)
Try out this code snippet in your program. And also write code to traverse forward and see the results.
Range-View Operations
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 34 of 61
The range-view operation, subList(int fromIndex, int toIndex), returns a List view of the portion of this list whose indices range from fromIndex, inclusive, to toIndex, exclusive.
This half-open range mirrors the typical for-loop:
As the term view implies, the returned List is backed by the List on which subList was called, so changes in the former List are reflected in the latter.
This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a List can be used as a range operation by
passing a subList view instead of a whole List. For example, the following idiom removes a range of elements from a list:
list.subList(fromIndex, toIndex).clear();
Note that the above idioms return the index of the found element in the subList, not the index in the backing List.
Try out each one of the above given code snippets in your prorgam and see the results.
Algorithms
Most of the polymorphic algorithms in the Collections class apply specifically to List. Having all of these algorithms at your disposal makes it very easy to manipulate lists.
Here's a summary of these algorithms, which are described in more detail in the Algorithms lesson.
sort(List): Sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.)
shuffle(List): Randomly permutes the elements in a List. (Shown above.)
reverse(List): Reverses the order of the elements in a List.
fill(List, Object): Overwrites every element in a List with the specified value.
copy(List dest, List src): Copies the source List into the destination List.
binarySearch(List, Object): Searches for an element in an ordered List using the binary search algorithm. Returns positive integer if found and negative if not found
Try out each one of these in your program and see the results
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. The Map interface is shown below:
// Bulk Operations
void putAll(Map t);
void clear();
// Collection Views
public Set keySet();
public Collection values();
public Set entrySet();
The JDK contains two new general-purpose Map implementations. HashMap, which stores its entries in a hash table, is the best-performing implementation. TreeMap, which stores
its entries in a red-black tree, guarantees the order of iteration.
The basic operations (put, get, remove, containsKey, containsValue, size, and isEmpty)
Here's a simple program to generate a frequency table of the words found in its argument list. The frequency table maps each word to the number of times it occurs in the
argument list.
import java.util.*;
public class Freq {
private static final Integer ONE = new Integer(1);
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 35 of 61
The only thing even slightly tricky about this program is the second argument of the put statement. It's a conditional expression that has the effect of setting the frequency to one
if the word has never been seen before, or one more than its current value if the word has already been seen.
Suppose you'd prefer to see the frequency table in alphabetical order. All you have to do is change the implementation type of the Map from HashMap to TreeMap. Make this
change and execute your program and see the results.
Bulk Operations
The clear operation does exactly what you think it does: it removes all of the mappings from the Map.
The putAll operation is the Map analogue of the Collection interface's addAll operation.
The following one-liner creates a new HashMap initially containing all of the same key-value mappings as m:
Collection Views
The Collection-views provide the only means to iterate over a Map. Here's an example illustrating the standard idiom for iterating over the keys in a Map:
The idiom for iterating over values is analogous. Here's the idiom for iterating over key-value pairs:
With all three Collection-views, calling an Iterator's remove operation removes the associated entry from the backing Map
With the entrySet view, it is also possible to change the value associated with a key, by calling a Map.Entry's setValue method during iteration
Try out each of above code snippets and see the results
Assignment(s)
Write a class to demonstrate the adding and reading employee names using Collection Interface
Write a class to demonstrate the adding and reading department names in your company using List Interface
Write a program which will initialize one Collection with some names and then copy the same to another List.
Write a class which will demonstrate a Set which will accept only unique values. Try putting duplicate values, still it must contain only unique values.
Create a Map which will hold id and names of Customers. Put the values, read them and then display the same.
Getting Started
What is JDBC
It involves: Loading the appropriate database driver, Establishing Connection and then Executing the SQL statements as per your business logic
In the following sub-topics and pages we are going to discuss all of these.
We are going to use JDBC-ODBC Bridge driver to get connected to Oracle / MS-SQL server database.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 36 of 61
Click on Add button to add a new DSN (Data Source Name). This will provide you with the list of ODBC Drivers installed on your machine. Select Oracle or MS SQL Server. If it is
Oralce, enter the name for your datasource, enter the username, password and servicename (put service name only if the database is not on your machine - The service name is
as same as service name given in tnsnames.ora file).
Test your DSN settings by clicking on Test Connection and then save the Data Source
Now you are goiing always going to use the DSN name just given to the data-source each time you get connection after loading the driver. - We will come to this very soon. - For
now please remember the DSN name
Create Tables
Customer (id number (5), name varchar (25), address varchar(25), cityId number (5))
Product (id number (5), name varchar (25), rate number (7) )
Put some meaningful data in to the tables created (please put meaningful data - do not put something like: yabadabadoo). Use Sql-Plus (If Oracle) or SQL Query Manager (If MS
Sql Server) to insert at least 7 to 10 rows in each table.
Loading Driver
The first thing you need to do is establish a connection with the DBMS you want to use. This involves two steps: (1) loading the driver and (2) making the connection.
Loading Drivers
Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code
will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the DriverManager because calling Class.forName will do that for you automatically. If you were to create
your own instance, you would be creating an unnecessary duplicate, but it would do no harm.
When you have loaded a driver, it is available for making a connection with a DBMS.
Establishing Connection
The second step in establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:
This step is also simple, with the hardest thing being what to supply for url . If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: . The rest of
the URL is generally your data source name or database system. So, if you are using ODBC to access an ODBC data source called "Sales" for example, your JDBC URL could be
jdbc:odbc:Sales. In place of "myLogin" you put the name you use to log in to the DBMS; in place of "myPassword" you put your password for the DBMS.
If you are using a JDBC driver developed by a third party, the documentation will tell you what subprotocol to use, that is, what to put after jdbc: in the JDBC URL. For example, if
the driver developer has registered the name acme as the subprotocol, the first and second parts of the JDBC URL will be jdbc:acme: . The driver documentation will also give you
guidelines for the rest of the JDBC URL. This last part of the JDBC URL supplies information for identifying the data source.
If one of the drivers you loaded recognizes the JDBC URL supplied to the method DriverManager.getConnection , that driver will establish a connection to the DBMS specified in the
JDBC URL.
The connection returned by the method DriverManager.getConnection is an open connection you can use to create JDBC statements that pass your SQL statements to the DBMS.
In the previous example, con is an open connection, and we will use it in the examples that follow.
The SELECT statements can be executed from a program written in the Java programming language and we get the results we showed.
JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results.
The following code demonstrates declaring the ResultSet object rs and assigning the results of our earlier query to it:
Surround all the code you write in try catch block catching SQLException.
The variable rs , which is an instance of ResultSet , contains the rows of Customers shown in the result set example above.
In order to access the id, name, address and cityId, we will go to each row and retrieve the values according to their types.
The method next moves what is called a cursor to the next row and makes that row (called the current row) the one upon which we can operate.
The cursor is initially positioned just above the first row of a ResultSet object, the first call to the method next moves the cursor to the first row and makes it the current row.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 37 of 61
Successive invocations of the method next move the cursor down one row at a time from top to bottom.
Note that with the JDBC 2.0 API, covered in the next section, you can move the cursor backwards, to specific positions, and to positions relative to the current row in addition to moving the curs or forward.
We use the getXXX method of the appropriate type to retrieve the value in each column.
For example, the first column in each row of rs is id , which stores a value of SQL type NUMBER . The method for retrieving a value of SQL type NUMBER is getInt.
The second column in each row stores a value of SQL type VARCHAR , and the method for retrieving values of that type is getString.
The following code accesses the values stored in the current row of rs and prints a line with the id followed by name. Each time the method next is invoked, the next row becomes
the current row, and the loop continues until there are no more rows in rs:
So if you wanted to retrieve a float value then you will use getFloat, for date - getDate and so on. Also, you can get the values from ResultSet using getter methods passing
number as parameter specifying the number of the column, the value of which you want to retrieve
You can retrieve any data type column with getSring method. Java wll implicitly convert the data retrieved to String
Updating Values
Write a new class called UpdateData.java. Load the drivers, get the connection and create statement the same way you did in earlier program.
Compile and execute your program. Re-Run the program written earlier to print values, and see that the address is changed (Only do not forget to change the previous program to
get address and include it in SOP)
Now try Deleting. You figure out what you need to write in DeleteData.java
Sometimes it is more convenient or more efficient to use a PreparedStatement object for sending SQL statements to the database. This special type of statement is derived from
the more general interface, Statement, that you already know.
The PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed,
the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.
Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters.
The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. You will see an
example of this in the following sections.
Write a new class called MyPreparedStatement.java with the following code in it (Load Drivers, and Establish Connection as done earlier)
if (args.length == 0) {
System.out.println("Invalid Parameter");
}
String sql = "Select name, address, cityId from Customer where id = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setInt(1, new Integer(args[0]).intValue());
ResultSet rs = stmt.executeQuery();
Note that this program expects a command line argument. The data retrieved will be based on the id passed as argument. Write while loop to traverse through the ResultSet as
done earlier.
executeUpdate method returns int value - which indicates the total number of rows that were affected.
Using Joins
Create a one more table called City (id number (5), name varchar(5)). Put atleast 7-to-10 rows in it. Now update the Customer table to set the value of cityId of each row to any
one of the id specified in City table. For e.g. If there is a city with id: 101 and name Mumbai in city table then make atleast 1 row in Customer table where value of cityId = 101. -
Do this using Sql-Plus (If Oracle) or Query Analyzer (If MS-Sql Server)
Now write a program to retrieve all Customers joining it with City table and display id, name, address from customer table and corresponding city name from City table.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 38 of 61
Using Transactions
There are times when you do not want one statement to take effect unless another one also succeeds.
Consider: you have some business logic to execute which involves inserting rows in few tables, delete rows from some other tables and also updating a row or a two in some
tables. You say this is one single unit of work
As per your business logic - either everything must be successful or everything must be undone.
In order to make this happen, you will have to make all your inserts, updates and deletes a part of transaction and either commit or rollback the transaction as per your
exception-handling mechanism.
Before you start inserting, updating or deleting, invoke con.setAutoCommit(false). Then after everything was successful, you use con.commit() or else invoke con.rollback().
Write this prorgam and execute it and see the results. Deliberately keep addressline1 null for one of the addresses and see that everything gets rolled back.
try {
try {
con.commit();
} catch (SQLException ex) {
Stored Procedures
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to
execute on a database server.
For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code.
Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.
Stored procedures are supported by most DBMSs, but there is a fair amount of variation in their syntax and capabilities.
Lets now see how Stored Procedures can be executed from java.
Executing a Procedures
Create a procedure which returns a result set returning list of all Customers
Assignment(s)
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 39 of 61
JDBC Assignments
Consider a Payroll application. The tables identified for the same are as follows
Employee (id number(5), firstname varchar(20), lastname varchar(20), address varchar(30), cityId number(5))
SalarySlip (id number(10), dateOfSlip date, employeeId number(5), amount number(8,2))
Department (id number(5), name varchar(20))
employeeId in SalarySlip is the foreign key of Employee.id.
Write 1 program to write, 1 to read, 1 to delete and 1 to update each of the tables mentioned above. When you insert rows in SalarySlip see to it that the employee id is any one
of the id(s) in Employee table. Use prepared statement in each program
Write a program to display SalarySlips with Employee names from Employee table.
Write a program called SearchEmployee with main method that will accept command line argument as employee id. Your program must search an employee based on the id
passed as command line argument and display firstname, lastname and address. If not found, it must display error message: "Employee with specified id does not exist".
Write another program called CreateEmployee to accept 5 arguments from command line. Insert a row in Employee table with exactly the values specified.First argument must be
considered as id, second as firstname and so on. Remember that the command line argument are all strings - so convert it to appropriate type as per the requirement of your
program.
Create program called DeleteEmployee as same as SearchEmployee written earlier, but instead of retrieving, delete the employee.
The JSP
It contains two types of text: static template data, which can be expressed in any text-based format, such as HTML, WML, and XML; and JSP elements
The JSP elements also includes java code in scriplets (We will see scriplets in detail a bit later)
The java code is executed server side and if java code writes some contents to the response obect, the contents written to response object is rendered to the client
The response object is an implicit object (instantiated by the server). What ever contents are written to response object are rendered to the client. This is the
standard concept of Web-Apps and not just specific to JSP.
JSP simply puts Java inside HTML pages. You can take any existing HTML page and change its extension to ".jsp" instead of ".html". In fact, this is the perfect exercise for your
first JSP.
Create a html file which prints "Hello, world". Change its extension from ".html" to ".jsp". Now load the new file, with the ".jsp" extension, in your browser.
You will see the same output, but it will take longer! But only the first time. If you reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file, compiled and loaded. This compilation only happens once, so after the first load, the file
doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-compiled again.)
You create static content in a JSP page by simply writing it as if you were creating a page that consisted only of that content.
Static content can be expressed in any text-based format, such as HTML, WML, and XML. The default format is HTML
If you want to use a format other than HTML, you include a page directive with the contentType attribute set to the format type at the beginning of your JSP page. For example, if
you want a page to contain data expressed in the wireless markup language (WML), you need to include the following directive:
What makes JSP useful is the ability to embed Java. Put the following text in a file with .jsp extension (let us call it hello.jsp), place it in your JSP directory, and view it in a
browser:
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Notice that each time you reload the page in the browser, it comes up with the current time.
The character sequences enclose Java expressions, which are evaluated at run time
This is what makes it possible to use JSP to generate dyamic HTML pages that change in response to user actions or vary from user to user.
Exercise:
Write a JSP to output the values returned by System.getProperty for various system properties such as java.version, java.home, os.name, user.name, user.home, user.dir
jsp:include
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 40 of 61
The jsp:include element is processed when a JSP page is executed. The include action allows you to include either a static or dynamic resource in a JSP file
The results of including static and dynamic resources are quite different.
If the resource is static, its content is inserted into the calling JSP file. If the resource is dynamic, the request is sent to the included resource, the included page is executed, and
then the result is included in the response from the calling JSP page.
The mechanism for transferring control to another Web component from a JSP page uses the functionality provided by the Java Servlet API
You access this functionality from a JSP page with the jsp:forward element:
Param Element
When an include or forward element is invoked, the original request object is provided to the target page.
If you wish to provide additional data to that page, you can append parameters to the request object with the jsp:param element:
A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet
technology.
When a request is mapped to a JSP page, it is handled by a special servlet that first checks whether the JSP page's servlet is older than the JSP page.
If it is, it translates the JSP page into a servlet class and compiles the class.
During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically
During the translation phase, template data is transformed into code that will emit the data into the stream that returns data to the client.
Both the translation and compilation phases can yield errors that are only observed when the page is requested for the first time. However, some ide(s) can compile jsp(s) for
you so that you can rectify the errors before you deploy
If an error occurs while the page is being translated (for example, if the translator encounters a malformed JSP element), the server will return a ParseException, and the servlet
class source file will be empty or incomplete
The last incomplete line will give a pointer to the incorrect JSP element.
If an error occurs while the JSP page is being compiled (for example, there is a syntax error in a scriptlet), the server will return a JasperException and a message that includes
the name of the JSP page's servlet and the line where the error occurred
Once the page has been translated and compiled, the JSP page's servlet for the most part follows the servlet life cycle
1. If an instance of the JSP page's servlet does not exist, the container:
a. Loads the JSP page's servlet class
b. Instantiates an instance of the servlet class
c. Initializes the servlet instance by calling the jspInit method
2. Invokes the _jspService method, passing a request and response object.
Scriplets
Adding Scriplets
JSP allows you to write blocks of Java code inside the JSP. You do this by placing your Java code between characters (just like expressions, but without the = sign at the start of
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 41 of 61
the sequence.)
This block of code is known as a "scriptlet". By itself, a scriptlet doesn't contribute any HTML (though it can, as we will see down below.) A scriptlet contains Java code that is
executed every time the JSP is invoked.
<HTML>
<BODY>
<%
// This is a scriptlet. Notice that the "date"
// variable we declare here is available in the
// embedded expression later on.
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now <%= date %>
</BODY>
</HTML>
By itself a scriptlet does not generate HTML. If a scriptlet wants to generate HTML, it can use a variable called "out". The following example shows how the scriptlet can generate
HTML output.
<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
// This scriptlet generates HTML output
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>
We have already seen how to use the "out" variable to generate HTML output from within a scriptlet. For more complicated HTML, using the out variable all the time loses some of
the advantages of JSP programming. It is simpler to mix scriptlets and HTML.
Suppose you have to generate a table in HTML. This is a common operation, and you may want to generate a table from a SQL table, or from the lines of a file. But to keep our
example simple, we will generate a table containing the numbers from 1 to N. Not very useful, but it will show you the technique.
<TABLE BORDER=2>
<%
for ( int i = 0; i < n; i++ ) {
%>
<TR>
<TD>Number</TD>
<TD><%= i+1 %></TD>
</TR>
<%
}
%>
</TABLE>
The important things to notice are how the %> and directive applies to an entire JSP file and any of its static include files, which together are called a translation unit.
You can use the <%@ page %> directive more than once in a translation unit, but you can only use each attribute, except import, once. Because the import attribute is similar to
the import statement in the Java programming language, you can use a <%@ page %> directive with import more than once in a JSP file or translation unit.
No matter where you position the <%@ page %> directive in a JSP file or included files, it applies to the entire translation unit. However, it is often good programming style to place
it at the top of the JSP file.
If you need to include a long list of packages or classes in more than one JSP file, you can create a separate JSP file with a <%@ page %> directive that contains
the import list and include that file in the main JSP file.
JSP Declarations
Declarations in JSP
The JSP you write turns into a class definition. All the scriptlets you write are placed inside a single method of this class.
You can also add variable and method declarations to this class. You can then use these variables and methods from your scriptlets and expressions.
To add a declaration, you must use the <%! and %> sequences to enclose your declarations, as shown below.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 42 of 61
%>
Hello! The time is now <%= getDate() %>
</BODY>
</HTML>
The example has been created a little contrived, to show variable and method declarations.
Please NoteThe date will be the same, no matter how often you reload the page.
You might have noted that the example given on previous page displays the same date each time it is executed
This is because these are declarations, and will only be evaluated once when the page is loaded! (Just as if you were creating a class and had variable initialization declared in it.)
It is in general not a good idea to use variables as shown here. The JSP usually will run as multiple threads of one single instance. Different threads would
interfere with variable access, because it will be the same variable for all of them. If you do have to use variables in JSP, you should use synchronized access,
but that hurts the performance. In general, any data you need should go either in the session objet or the request objectc (these are introduced a little later) if
passing data between different JSP pages
Assignment(s)
Create a Banner.jsp which will display today's date. Create an index.jsp and provide anchor on it to Customer.jsp, Product.jsp, Tax.jsp and Invoice.jsp. On each of these jsp(s)
include Banner.jsp on the top. Use both the methods (include directive and jsp:include)
Write a scriplet in Customer.jsp to retrieve (use jdbc) all the data from Customer table (if Customer table is not created, create one). Use out.println("....."); to display the data
retrieved
Implicit objects are created by the Web container and contain information related to a particular request, page, or application.
Many of the objects are defined by the Java Servlet technology underlying JSP technology and are discussed at length later while discussing Servlets
What is a request
When the end-user submits a request to the server (usually through a browser), the Servlet Engine at the server side receives it and creates a request object and makes it
available to your JSP.
This request object contains data that is submitted by the client. So you see, if you want to catch hold of data which was sent by the client to the server, it is this request object in
which this data is available
Note one very important point: The request object is alive only till the time the response (we will discuss more on response later) is sent back to the client.
Once the client gets his response, the data that was available in the previous request he had sent is all gone. Now when he comes back to the server, he will be coming back with
a new request. To put it in plain simple language : Each time you hit a link or a submit button on a web page, a new request is created server side for that client
<html>
<head>
<title>
Customer
</title>
</head>
<body bgcolor="#ffffff">
<h1>
Add a New Customer</h1>
<form method="post" action="AddCustomer.jsp">
<table>
<tr>
<td>
Id:
</td>
<td>
<input type="text" name="id" value=""/>
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 43 of 61
</td>
</tr>
<tr>
<td>
Name:
</td>
<td>
<input type="text" name="name" value=""/>
</td>
</tr>
<tr>
<td>
Address
</td>
<td>
<input type="text" name="address" value=""/>
</td>
</tr>
<tr>
<td>
City:
</td>
<td>
<input type="text" name="cityId" value=""/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Add Customer"/>
</td>
</tr>
</table>
</form>
</body>
</html>
Deploy this JSP and ensure that you get the JSP displayed on the browser as per expectations. Well, there is not JSPness in this JSP. All that you have written here could be
written in Html and still make it work. But the real work goes in next JSP.
Note the action attribute in the Form tag. This means that when the user clicks on the submit button, the request will be sent to AddCustomer.jsp on the server - needless to say
that this request is sent by the browser.
<html>
<head>
<title>
AddCustomer
</title>
</head>
<body bgcolor="#ffffff">
<h1>
Adding Customer
</h1>
<%
%>
<a href="Customer.jsp">Go Back</a>
</body>
</html>
Now once again run the Customer.jsp, enter data and click on submit button.
Note that the data you have entered on Customer.jsp is made available to you on AddCustomer.jsp
The response object is also constructed by the server. All that is put in response object is rendered to the client.
You can write to the response object using the PrintWriter object of response object as follows:
The above technique is of no use in JSP because we already have implicit object called out which is nothing but an object of type PrintWriter pointing to response writer.
Still, try the above code snippet in your AddCustomer.jsp and print the the data entered by the user on Customer.jsp - What I mean is, use myWriter after initializing it to
response.getWriter() instead of out.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 44 of 61
To specify that the Web container should forward control to an error page if an exception occurs, include the following page directive at the beginning of your JSP page:
If there is any exception thrown while the jsp (which includes above oage directive) is executing, the server will automatically forward the request to the page specified in
errorPage="file_name"
In AddCustomer.jsp, deliberately throw an SQLException as follows (do not forget to import the java.sql.SQLException)
Create a new JSP called Error.jsp. The following directive is important in Error.jsp :
This directive makes the exception object (of type javax.servlet.jsp.JspException) available to the error page, so that you can retrieve, interpret, and possibly display information
about the cause of the exception in the error page.
<%
out.println("The Error Occurred is : <b>" + exception.getMessage() + "</>");
%>
Execute Customer.jsp, put some data and hit submit. Since you deliberately throwing an exception from AddCustomer.jsp the server forwards the request to Error.jsp
Assignment(s)
Create an index.jsp with anchors to Customer, Tax, Invoice and Product. When the user clicks on any one of these options, display him/her the form with all the fields that are
there in the tables Customer, Tax, Invoice & Product respectively.
Now implement the following: When the user clicks on Submit on the Customer.jsp (or any other jsp mentioned above) your browser must submit the request to AddCustomer.jsp
or AddTax.jsp or AddInvoice.jsp or AddProduct.jsp - depending on which form the user has clicked on submit. Using jdbc, add data entered by the user in the respective tables.
i.e. AddCustomer.jsp must use jdbc to add to Customer table, AddTax to tax table and so on.
Continue with the above application to provide search facility. Display Customer, Tax etc based on id provided by the user.
Continue with the above application to provide delete facility. Delete Customer, Tax etc based on id provided by the user
jsp:UseBean
With the JavaBeans API you can create reuseable, platform-independent components.
Using JavaBeans-compliant application builder tools, you can combine these components into applets, applications, or composite components. JavaBean components are known as
Beans.
Any java class that has private attribute(s) and public get and set methods in it can be called a java bean. For e.g a CustomerValueObject java bean can created as follows:
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 45 of 61
You will need to create such hundreds of java beans in real-life application, so that you can instantiate it one component, put data in it and pass it over to the other component so
that it can use it.
Create a new package in your application called valueobjects and then create a class called CustomerValueObject.java as follows:
package valueobjects;
Go to AddCustomer.jsp and add the following jsp code after the closing of java scriplet you have already written :
Now we would like to forward our request to the other jsp called CustomerAddress.jsp. Write the following line just before </body>
<jsp:forward page="CustomerAddress.jsp"/>
The jsp:useBean tag will look for the the object called "customerVO" - specified as id in request object (why in request ? because the scope="request" in
jsp:useBean tag). If found, it will use it or else it will create one and put it on request object.
jsp:setProperty
The above statements will add the values to the object created called customerVO of class valueobjects.CustomerValueObject. Note that this object is created and put in request
using jsp:useBean tag explained in earlier tag.
Using the jsp:setProperty to write value to name using <jsp:setProperty name="customerVO" property="name" value="yabadabadoo" /> is as good as writing <%
customerVO.setName("yabadabadoo"); />
jsp:getProperty
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 46 of 61
Address Line 1
Address Line 2
Address Line 3
Submit
Note the usage of jsp:useBean tag here - right on the top. The rule is same: JSP-Servlet engine will check whether there is bean called customerVO in request, if yes it will use it
or else it will create it. Since the control has been forwarded from AddCustomer.jsp (which creates customerVO and puts in request) to this page, servlet engine will not recreate it
- instead use it.
See the usage of jsp:getProperty tag to get the value of attributes of the bean and set it to text boxes.
Editing a Form
A form used to accept values from the user and put it in the database can be also be used to display the values retrieved from the database so that it can be ammended by the
user
Write a index.jsp which will have anchor to EditCustomer.jsp. The text of the anchor must display : "Edit Customer".
The EditCustomer.jsp must accept customer Id from the user. When the user clicks on submit, submit the request to RetrieveCustomer.jsp. RetrieveCustomer.jsp must contain
scriptlet which will load database driver, establish connnection, retrieve data and create a javabean called customerVO of class CustomerValueObject and put the same in request
object. The customer row retrieved must be exactly the one the id of which is entered by the user on EditCustomer.jsp
RetrieveCustomer.jsp will finally forward the request to Customer.jsp which will display the data in text boxes using jsp:getProperty. Needless to say, you will have to use
jsp:useBean also on the top of Customer.jsp.
Assignment(s)
Extend the application you have written in "Assignments for Implicit Objects " to use Form Beans to edit Customer, Tax etc.
Retrieve the customer the way you have done earlier and forward to Customer.jsp. Use jsp:useBean, jsp:getProperty to display the values retrieved in the text boxes. Write
EditCustomer.jsp EditTax.jsp etc to update the edited values back to database
Chapter: 5 - Servlets
Introducing Servlets
What is a Servlet
A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model.
Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology
defines HTTP-specific servlet classes.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle
methods.
When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API.
The HttpServlet class provides methods, such as doGet and doPost, for handling HTTP-specific services.
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
When a request is mapped to a servlet, the container performs the following steps.
If an instance of the servlet does not exist, the Web container
a. Loads the servlet class.
b. Creates an instance of the servlet class.
c. Initializes the servlet instance by calling the init method.
Invokes the service method, passing a request and response object.
If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.
Service Methods
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 47 of 61
The service provided by a servlet is implemented in the service method of a GenericServlet, the doMethod methods (where Method can take the value Get, Delete, Options, Post,
Put, Trace) of an HttpServlet, or any other protocol-specific methods defined by a class that implements the Servlet interface.
In the rest of this chapter, the term service method will be used for any method in a servlet class that provides a service to a client.
The general pattern for a service method is to extract information from the request, access external resources, and then populate the response based on that information.
For HTTP servlets, the correct procedure for populating the response is to first fill in the response headers, then retrieve an output stream from the response, and finally write any
body content to the output stream.
Response headers must always be set before a PrintWriter or ServletOutputStream is retrieved because the HTTP protocol expects to receive all headers before body content.
The doGet method is one of the service methods that is executed by the container when the requested is submitted to the server and the method of submission os get
The doPost method is no different then doGet method - the only difference is that it is executed by the container when the method of request submitted by the client is post
All that we did in AddCustomer.jsp and RetrieveCustomer.jsp should have been actually done in Servlet.
The JSP(s) are for managing presentation logic and servlets are the ones that must be used for processing requests and managing control logic of web-navigation.
Creating a Servlet
Create a servlet called CustomerServlet which will do all that you have written in AddCustomer.jsp
Please note that when you create a servlet, the servlet is requested from client-side with a URL patterns and not the name of the servlet.
Now instead of action="AddCustomer.jsp" in Customer.jsp - change it to "customerservlet" - the url pattern for CustomerServlet
Note the RequestDispatcher object used here to forward the request to CustomerAddress.jsp. Also note how customerVO object is created and put in request.
This is not a JSP hence we have to do it without a tag
Accessing a Session
Many applications require a series of requests from a client to be associated with one another. For example, the user logs on to your system and you would like to maintain his
user info such as first name and lastname across multiple request infact throughout out his interaction with the application.
Web-based applications are responsible for maintaining such state, called a session, because the HTTP protocol is stateless.
To support applications that need to maintain state, Java Servlet technology provides an API for managing sessions and allows several mechanisms for implementing sessions.
This method returns the current session associated with this request, or, if the request does not have a session, it creates one
Create a Login.jsp with a form on it accepting username and password from the user
You must create all servlets in some package - here you create LoginServlet in servlets package
In valueobjects package create a class called UserValueObject.java as a java bean with attributes such as: userName, firstName, lastName. (You know what is a java bean - it
must have getter & setter methods for each one of these attributes)
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 48 of 61
Execute Login.jsp and now switch to any jsp (without closing the browser) typing the jsp name on the address bar. See that you will get Welcome info on all the jsps
Assignment(s)
Servlet Assignment(s)
Re-Design the entire application written earlier, to use servlets instead of all the JSP(s) which were doing the request processing and not managing the presentation logic for e.g.
AddCustomer.jsp, RetrieveCustomer.jsp, DeleteCustomer.jsp etc. Now no jdbc code must be there in any JSP - All the jdbc code must be in Servlets.
Consider that each Customer has one or more Addresses. Create a Customer Data Entry Application which will accept Customer Details like name, address etc and also one ore
more Addresses which will have line1, line2 and line3 of address. Save the entire Customer along with Address only after user confirms. Till the time user finishes entering all the
Addresses you must keep Customer Details like name and address in Session Object. Use value objects, form beans, request and session objects. This must be a complete
master-detail application with add, modidy, delete and view options.
Struts
Chapter: 1 - Introduction to MVC
What is MVC ?
The early JSP specifications advocated two philosophical approaches for building applications using JSP technology: MVC Model-1 & MVC Model-2
Model 1 and 2 differ essentially in the location at which the bulk of the request processing was performed
In the Model 1 architecture, the JSP page alone is responsible for processing the incoming request and replying back to the client.
There is still separation of presentation from content, because all data access is performed using beans
MVC Model 2
The Model 2 architecture, is a hybrid approach for serving dynamic content, since it combines the use of both servlets and JSP.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 49 of 61
Note particularly that there is no processing logic within the JSP page itself
JSP is simply responsible for retrieving any objects or beans that may have been previously created by the servlet, and extracting the dynamic content from that servlet for
insertion within static templates
Struts Architecture
Struts is comprised of a controller servlet, beans and other Java classes, configuration files, and tag libraries.
A controller for your application (the Struts servlet acts as a common controller for the whole application)
A collection of Java beans and other helper classes that you use in the "Model" part of your application
To glue these things together Struts uses a set of configuration files. Together this gives you the skeleton that you can use to "strut" your application
The Flow
Consider, that the request sent from the client (browser) is toCreateCustomer.do - The *.do url pattern is mapped to ActionServlet in web.xml file and hence ActionServlet service
method is executed
The ActionServlet reads struts-config.xml file and searches for <action> element with path="/toCreateCustomer" and detects the Action class name configured with this path
The ActionServlet now instantiates the Action class and executes the execute method of it
Please note: Before executing the execute method, the ActionServlet instantiates the formbean object (if configured) and populates it with the data entered by the end-user,
executes the validate method and then passes it as the parameter to the execute() method.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 50 of 61
Struts has been designed to give you modularity and loose couplings in your application.
If you're building a simple, small application you might find it complicated to have to create and handle so many files.
You might even be tempted to put all your code in a single jsp-file
My advice to you is: don't do it! I'm sure you can build a single-page application faster using only one jsp-page, but if we're talking about more complex applications, the extra
effort put in by using a modular framework will soon be rewarded
There is one single servlet in the entire application i.e. ActionServlet. This servlet is provided by Struts-Framework API
All the requests coming to the application server (which requires dynamic contents / need to access the model) is received by this ActionServlet.
The ActionServlet reads Struts-Config.xml file and identifies the Action class to be instantiated.
The ActionServlet instantiates the Action Class and executes the execute() method
It is this execute() method, in the Action Class where you write your use case logic.
Note that the ActionClass you write is extended from Action class provided by Struts-Framework API. The execute() method has 4 parameters (ActionMapping
mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response).
The ActionForm
If the form is to be processed the programmer-defined class of type ActionForm can be configured in Struts-Config.xml file
It is the responsibility of Struts-Framework to instantiate this class, read the contents entered by the end-user and copy the same to this FormBean class.
The best thing is that (as explained in notes of previous slide) one of the parameters passed to the execute method of Action Class is this instantiated and populated FormBean
object
You can execute accessor (getter) methods on this form object to get the data entered by the end-user in the execute method
The Struts-Framework after instatiating and populating the ActionForm object, executes the validate method.
You can write validations in this validate method and return object of type ActionErrors containing the list of Errors (if there are any as per the business rule)
The Struts-Framework will automatically forward to the input page (forcing user to re-enter the data)
With the help of simple error tags, (provided by Struts) you can display the error messages on the input page
Setting up Struts
There are n number of jar files provided by Struts-Framework which togethger provides all the Struts-Functionality. The architecturally-significant among these is Struts.jar
All the architecturally-significant components like: ActionServlet, Action, ActionForm, ActionError, ActionErrors etc. are in this jar file.
This and all the other jar files must be copied to your WEB-INF/lib folder
Please download the following zip file, Unzip it and copy all the jar files in the location mentioned above:
Download Jar Files
Any jar file put in the lib folder need not be explicity specified in the classpath of your web application. They are implicity included in the classpath
As mentioned earlier, Struts offers collection of rich tags which tremendously eases the development of presentation logic.
All the tag classes are in struts.jar file and all the descriptors of tags are in the .tld files copied on WEB-INF folder
Please download the following zip file and copy it to the location mentioned above:
Download TLDs
Struts-Config.xml
This is the architecturally siginificant component of Struts-Framework. If not present, the framework will cease to work.
Please download the following sample Struts-Config.xml file and copy it to the location mentioned above:
Download Struts-Config
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 51 of 61
Create a Servlet Component in web-xml file with the name action. This servlet component must be mapped to the servlet class : ActionServlet. The fully qualified path of the this
servlet is: org.apache.struts.action.ActionServlet
Also set the initialization parameter called "config" for this servlet. Set the value of this parameter to: /WEB-INF/struts-config.xml. The xml code is given below
<servlet>
<servlet-name>action</servlet-name>
<display-name>ActionServlet</display-name>
<description>Struts Controller</description>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
<description>No Description</description>
</init-param>
</servlet>
Now add a servlet mapping in your web.xml file for the ActionServlet as follows:
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
You will have to redeploy your application to bring all the changes in effect
The Application
Let us develop a small sample application which will have the option of creating a new Customer. Each customer that is recorded belong to a particular city and and we need to
provide the list of cities to the user. Also, we need to perform basic validation like customer name cannot be left blank. If this validation fails, the system must re-present the
customer form displaying the error message(s) - or else save the Customer
Create a new package (folder) called presentationtier and then class within it called ToCreateCustomerAction.java Extend this class from Action
Now override execute method, the signature of which is: public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
It is assumed that you already have created a web application and tested the same.
When the request comes from the browser as "toCreateCustomer.do", the ActionServlet will look for action element in the struts-config.xml file with path attribute as
"toCreateCustomer",
Note that the execute method of the action class gets executed printing the SOP : Retrieving cities. Also note that owing to the forward tag of the action, the ActionServlet
forwards the request to customer.jsp.
Create a CityVO class in model.vo package with id and name as attributes and accessor and mutator methods.
Create 3 objects of this class in execute method of ToCreateCustomerAction.java and put it in the collection. Put the collection object in the request using request.setAttribute
Retrieve this collection object from the request object in jsp and construct a dropdown list box to display the list of customers. Please note: the display column must be name and
data column must be id.
Use the Following code in customer.jsp to display all the cities in dropdown:
<Select name="city">
<%
Collection cities = (Collection) request.getAttribute("cities");
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 52 of 61
Now that we have presented the customer.jsp to the end-user, the end-user enters customer details and hits the submit button
In customer.jsp, specify the action attribute for html form as: "toSaveCustomer.do".
Create a new class in presentationtier package called "CustomerForm.java" and extend it from ActionForm. The ActionForm is a class provided by Struts-Framework and is
available in org.apache.struts.action package - Compile the class
Now go to struts-config.xml file and make an entry for "toSaveCustomer" action. Create a new action element as follows:
Please note the value of name attribute in the above xml code. This name is actually the name of FormBean - again declared in struts-config.xml file. Once a form bean is
declared, it can be used in n-number of actions (More on the next slide...)
Please note that this entry must be made within <form-beans> and </form-beans> tags
All the form-beans must be configured within <form-beans> and </form-beans> tags
The name in the tag specifies the name of the formbean and the type specifies the class of the formbean
Note that it is this name of the formbean which is used as value of name attribute in the action mapping for "toSaveCustomer"
Create a new Class called "SaveCustomerAction.java" in presentationtier pacakage and extend the same from Action class of struts. (By now you know, in which package this class
is).
Note that, it is this class which has been specified in type attribute in the toSaveCustomer mapping
Override the execute method. In the execute method write the following:
The framework instantiates the FormBean, populates the bean with the contents entered by end-user and passes the formbean instance as parameter to the executed method.
Instead of you writing n-number of request.getParameter statements to get the values, entered by the user, the framework gives you a bean with all the values Is'nt this great
}
if (this.getId() == null || this.getId().length() == 0 ) {
ActionError error = new ActionError("error.global.message", "Idiot! How can code be blank");
errors.add(ActionErrors.GLOBAL_ERROR, error);
}
return errors;
}
Now open struts-config.xml file and go to action mapping for toSaveCustomer. Ensure that the input="/customer.jsp" and validate="true"
This tells the framework to execute the validate method of the form after populating it with the data entered by end-user.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 53 of 61
Also, if validate method returns an object of class ActionErrors (it is actually a collection) with size > 0, then the framework re-presents customer.jsp (as mentioned in input
attribute) for the end-user to rectify the errors
Run the Application and See the results. Do not worry about the ActionError and displaying the errors on customer.jsp - we will address this shortly
The ActionError
As explained on the previous slide, we create an object of ActionError if there is any violation of business rule, and add it to the object of type ActionErrors.
In the code that we hae written, there are two examples 1 - with one parameter and 2 with 2 parameters.
If you create ActionError object with 1 parameter, you provide the property name the value of which is set in "ApplicationResources.properties" file. Create a file with this name
and put it under WEB-INF/classes folder
Now also check out the creation of ActionError with 2 arguments. The first argument specifies the property name in ApplicationResources.properties file and the second parameter,
the value that will be substituted with the {0} parameter in the property.
Now how does the framework understand that the error messages are in ApplicationResource.properties ?
It understands after adding the following after action-mappings element in struts-config.xml file:
Now that we have written all our code to validate and manage errors. How do we display the errors that are set in ApplicationResources.properties
Open customer.jsp - Before you start the html form, write the following:
<html:errors/>
In order to use this tag you will have to give a taglib directive on your jsp page as follows:
Run the application and deliberately leave name empty, hit submit and see the results. The framework will forward the request to customer.jsp and will display the error messages
In order to get the values in the other text boxes displayed, which were entered by the user before submit, use the <jsp:useBean id="CustomerForm"
class="presentationtier.CustomerForm" scope="request"/> and then jsp:getProperty to get the original value. Use this value to set the value of the text box
Assignment(s)
Struts Assignment
Write the entire application which you have written earlier using Struts framework. Re-developing JSP(s) write from scratch is not required. Where ever you used Servlets, now
use Action Classes. Use ActionForms for each input type jsp. Use validate method and ActionErrors and ActionError to validate daya input and display the error messages.
EJB 2.0
Chapter: 1 - Enterprise Beans
Written in the Java programming language, an enterprise bean is a server-side component that encapsulates the business logic of an application.
The business logic is the code that fulfills the purpose of the application
In an inventory control application, for example, the enterprise beans might implement the business logic in methods called checkInventoryLevel and orderProduct
By invoking these methods, remote clients can access the inventory services provided by the application
Because the EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 54 of 61
The EJB container--not the bean developer--is responsible for system-level services such as transaction management and security authorization
Because the beans--and not the clients--contain the application's business logic, the client developer can focus on the presentation of the client
The client developer does not have to code the routines that implement business rules or access databases
The clients are thinner, a benefit that is particularly important for clients that run on small devices.
Consider using Enterprise beans if your application has any one of the following requuirements:
Message-Driven: Acts as listener for Java Message Service API, processing messages asynchronously
A Session Bean represents a single client inside the J2EE server & is similar to an interactive session
To access an application that is deployed on the server, the client invokes the session bean's methods.
The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server
A session bean is not shared--it may have just one client, in the same way that an interactive session may have just one user & is not persistent
When the client terminates, its session bean appears to terminate and is no longer associated with the client.
In a stateful session bean, the instance variables represent the state of a unique client-bean session
Because the client interacts ("talks") with its bean, this state is called the conversational state
If the client removes the bean or terminates, the session ends and the state disappears
A stateless session bean does not maintain a conversational state for a particular client
When a client invokes the method of a stateless bean, the bean's instance variables may contain a state, but only for the duration of the invocation
Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 55 of 61
An application requires fewer stateless session beans than stateful session beans to support the same number of clients
Stateless beans may offer better performance than stateful beans
The bean’s state represent the interaction between the bean and specific client
The bean needs to hold information about the client across method invocations
The bean mediates between the client and the other components of the application providing a simplified view to the client
Behind the scenes the bean manages the workflow for several enterprise beans
In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an email that confirms the online order
The bean fetches from a database a set of read-only data that is often used by clients
Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table
Entity beans differ from session beans in several ways as given below:
Persistence means that the entity bean's state exists beyond the lifetime of the application or the J2EE server process
With bean-managed persistence, the entity bean code that you write contains the calls that access the database
With container-managed persistence, the EJB container automatically generates the necessary database access calls
The unique identifier, or primary key, enables the client to locate a particular entity bean
Like a table in a relational database, an entity bean may be related to other entity beans
For example, in a college enrollment application, StudentEJB and CourseEJB would be related because students enroll in courses
With bean-managed persistence, the code that you write implements the relationships
With container-managed persistence, the EJB container takes care of the relationships for you
For this reason, relationships in entity beans with container-managed persistence are often referred to as container-managed relationships.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 56 of 61
Container Managed Relationships is the excellent way of automating the relationships among business objects in the your business object model.
The term container-managed persistence means that the EJB container handles all database access required by the entity bean
The bean's code is not tied to a specific persistent storage mechanism (database).
Because of this flexibility, even if you redeploy the same entity bean on different J2EE servers that use different databases, you won't need to modify or recompile the bean's code
You should probably use an entity bean when: The bean represents a business entity, not a procedure. For example, CreditCardEJB would be an entity bean, but
CreditCardVerifierEJB would be a session bean
Also when: The bean's state must be persistent. If the bean instance terminates or if the J2EE server is shut down, the bean's state still exists in persistent storage (a database).
The Java Message Service is a Java API that allows applications to create, send, receive, and read messages
Designed by Sun and several partner companies, the JMS API defines a common set of interfaces and associated semantics that allow programs written in the Java programming
language to communicate with other messaging implementations
The JMS API minimizes the set of concepts a programmer must learn to use messaging products but provides enough features to support sophisticated messaging applications
It also strives to maximize the portability of JMS applications across JMS providers in the same messaging domain
The JMS Specification was first published in August 1998 and the latest JMS API version is 1.1 which is the part of J2EE 1.4
A message-driven bean is an enterprise bean the allows J2EE applications to process messages asynchronously.
Message Driven-beans currently process only JMS messages, but in future they may be used to process other kind of messages
When a message arrives, the container calls the message-driven bean's onMessage method to process the message
The onMessage method may call helper methods, or it may invoke a session or entity bean to process the information in the message or to store it in a database
A message may be delivered to a message-driven bean within a transaction context, so that all operations within the onMessage method are part of a single transaction
The most visible difference between message-driven beans and session and entity beans is that clients do not access message-driven beans through interfaces
A message-driven bean has only a bean class and A message-driven bean's instances retain no data or conversational state for a specific client
All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any message-driven bean instance
The container can pool these instances to allow streams of messages to be processed concurrently.
Session beans and entity beans allow you to send JMS messages and to receive them synchronously, but not asynchronously
To avoid tying up server resources, you may prefer not to use blocking synchronous receives in a server-side component
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 57 of 61
A client may access a session or an entity bean only through the methods defined in the bean's interfaces
Client are dependent on Abstracton and not on Implementation
All other aspects of the bean--method implementations, deployment descriptor settings, abstract schemas, and database access calls--are hidden from the client
They also allow the beans to change internally without affecting the clients.
To isolate your clients from possible changes in the beans, it is important that you design the interfaces carefully.
Remote Access
When you design a J2EE application, one of the first decisions you make is the type of client access allowed by the enterprise beans:
remote or
local
A remote client of an enterprise bean may run on a different machine and a different Java virtual machine (JVM) than the enterprise bean it accesses. (It is not required to run on
a different JVM.)
A remote client of an enterprise bean can be a Web component, a J2EE application client, or another enterprise bean.
To create an enterprise bean with remote access, you must code a remote interface and a home interface
The remote interface defines the business methods that are specific to the bean (e.g debitAccount(), creditAccount())
The home interface defines the bean's life cycle methods--create and remove
For entity beans, the home interface also defines finder methods and home methods. Finder methods are used to locate entity beans
Local Access
A local client must run in the same JVM as the enterprise bean it accesses.
A local client may be a Web component or another enterprise bean and To the local client, the location of the enterprise bean it accesses is not transparent
It is often an entity bean that has a container-managed relationship with another entity bean and hence must have local interfaces
To build an enterprise bean that allows local access, you must code the local interface and the local home interface
The local interface defines the bean's business methods, and the local home interface defines its life cycle and finder methods
The decision regarding whether to allow local or remote access depends on the factors explained in following points:
Container-managed relationships: If an entity bean is the target of a container-managed relationship, it must use local access
Tight or loose coupling of related beans: Tightly coupled beans depend on one another. Since they fit together as a logical unit, they probably call each other often and would
benefit from the increased performance that is possible with local access.
Types of client: If an enterprise bean is accessed by J2EE application clients, then it should allow remote access.
If an enterprise bean's clients are Web components or other enterprise beans, then the type of access depends on how you want to distribute your components.
Component distribution: J2EE applications are scalable because their server-side components can be distributed across multiple machines. In a distributed application, for
example, the Web components may run on a different server than the enterprise beans they access. In this distributed scenario, the enterprise beans should allow remote access
If you aren't sure which type of access an enterprise bean should have, then choose remote access. This decision gives you more flexibility--in the future you can distribute your
components to accommodate growing demands on your application
Although uncommon, it is possible for an enterprise bean to allow both remote and local access. Such a bean would require both remote and local interfaces
On the other hand, if you distribute components among different servers, you might improve the application's overall performance
Both of the above statements are generalizations; actual performance can vary in different operational environments
Nevertheless, you should keep in mind how your application design might affect performance
Method Parameters
The type of access affects the parameters of the bean methods that are called by clients. The following points apply not only to method parameters, but also to method return
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 58 of 61
values
An argument in a remote call is passed by value; it is a copy of an object WHERE-AS An argument in a local call is passed by reference, just like a normal method call in the Java
programming language
The parameters of remote calls are more isolated than those of local calls
With remote calls, the client and bean operate on different copies of a parameter object
If the client changes the value of the object, the value of the copy in the bean does not change
Deployment descriptor: An XML file that specifies information about the bean such as its persistence type and transaction attributes. The deploytool utility creates the deployment
descriptor when you step through the New Enterprise Bean wizard.
Enterprise bean class: Implements the methods defined in the following interfaces.
Interfaces: The remote and home interfaces are required for remote access. For local access, the local and local home interfaces are required.(Please note that these interfaces
are not used by message-driven beans.)
Helper classes: Other classes needed by the enterprise bean class, such as exception and utility classes
You package all of these files into an EJB JAR file, the module that stores the enterprise bean
Portability
An EJB JAR file is portable and may be used for different applications
To assemble a J2EE application, you package one or more modules--such as EJB JAR files--into an EAR file, the archive file that holds the application
When you deploy the EAR file that contains the bean's EJB JAR file, you also deploy the enterprise bean onto the J2EE server
Premier Auto Electric is a company doing trading business in Auto-Spare parts. They have 34 locations all over India. The core business processes includes Purchase and Sales.
Your teams is tasked with the development of Sales Module.
The Salesmen bring orders from the Customers (Stockists of PAE). These orders are to be recorder in the system by the Sales Officer or Salesman who brings the orders. Note
that the customer cannot record the orders online.
The Sales Manager then prepares the invoices based on the sales order that are recorded.
The system keeps track of the inventory and depletes the same when invoices are prepared. Also the Customer can logon and record the Automobiles - the spare parts of which
he deals in. This will help PAE to identify its own stocking needs.
The use-cases identified are: Manage Sales Order which includes: creating, updating and deleting the order AND Manage Invoice which also includes: creating, updating and
deleting the invoice. Also a use-case: Record Automobile is required in the system
Please note that the objective is not to develop the entire application here. We will only use this case-study to help us learn topics of the subject meaningfully.
Such real-life examples adds more flavour to learning process.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 59 of 61
Premier Auto Electric is a trading company involved in buying and selling of Automobile spare parts. There are around 28 manufactures who are suppliers to PAE. PAE buys spare
parts from these manufacturers in bulk quantities and sells it to various stockists and dealers all over India on 10% of profit margin. PAE has 34 sales-locations all over India.
The sales of spare parts is done to only those dealers who are registered with PAE. Dealers can submit their registration through the system. While registering, dealer can affiliate
to any one sales-depot out of all the depots of PAE which is spread all over India. The Depot-Manager will evaluate the credibility of the dealers who have submitted fresh
registrations, before the goods are sold to them and approve or disapprove his registration. While approving the registration, Depot-Manager sets the credit-days of the dealer
which is 45 by default.Each dealer is given the dealer ship of spare parts of 1 or more automobiles. Dealers can order and buy only those products for which dealer ship is given to
them. This is to maintain no-competition between PAE dealers from the same area.
The dealers can place orders online. The orders can have one or more than 1 products under the category (automobile) for which they have been given dealership. The order can be modified or cancelled only before it is
invoiced. Once PAE invoices/dispatches the order, the dealer cannot modiy or cancel the order.
The Sales Manager at the sales depot has a very important responsibility. He has to scan through all the orders placed by the dealers affiliated to his branch and generate invoices and dispatch documents. There are high
expectations from the system here. There can be many order from various dealers ordering for one ore more products. The rationing of inventory among the dealers is important. Hence system must provide the list of
product wise orders placed by various dealers. The sales manager can then decide, as to which product of which order must be serviced. The sales manager takes this decision based on the credit-limit available of the
customer and his receivable status. The system must provide this status to the Sales-Manager. After Sales-Manager enters the quantity of against each product ordered, system must auto-generate the customer-wise
invoices i.e. 1 invoice per customer for the all orders against which the sales-quantity ordered by the Sales-Manager is entered as greated than 0
The system must deplete the inventory of the product that are invoiced, update the receivable status of the dealer and close the order against which the invoice is created. Note
that the order is considered as closed only after all the products in the orders are invoiced. There is one more way in which the order on the whole can be closed i.e. the Sales-
Manager "marks" a particular order of dealer as closed.
The dealer is supposed to make the payment within the credit-days set for him by the Depot-Manager. The cheques are recorded by the A/Cs officer along with chq date, amount
and the invoices against which the chq(s) are received. This closes the invoices and updates the dealer receivable status of dealer.
Organize the Actors and Use Cases in appropriate packages in the Use Case View
Create a Supplementary Specificaton Document illustrating the Usability, Reliability, Scalability and other non-functional requirements. Also create a Glossary Document defining
the terms (nouns of interest) in the system.
Detail all the use cases identified in the use case model to illustrate the flow of events of the use case. The detailing must be done in word document as per the use case template
given by unified process.
Create activity diagrams for each use case to illustrate the flow of events of the use cases.
Please note: In real-life it is not necessary to do both - writing use cases in word document & creating activity diagram for it. Any one can suffice.
Please refer to the problem statement of Course Registration System and do the following:
Create the first draft of Deployment Diagram
Define the High-Level Organization of Subsystem (Identify Layers)
Establish Relationship between layers
Identify Key Abstractions
Show the identified Key Abstractions on a class diagram called "Key Abstractions"
Briefly describe each key abstraction identified
Establish relationship among these key abstractions
Identify the cardinality (multiplicity) on relationships identified
Create Use Case Realizations package and realize each use case you have identified.
Create Sequence Diagrams to illustrate the dynamic behaviour. Identify boundary and controller classes while doing so.
Create a VOPC class diagram to present the static structure of the use case.
Identify the dependencies among these packages. Also describe Architectural Mechanisms (Data Transfer Object Mechanism, MVC Mechanism)
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 60 of 61
Design Components
Perform Use Case Design - Take each use can do the use case design (low level design) for each use case under the umbrella of Architecture (high level design).
Design Subsystems
Update VOPC of each use case. Create class diagrams to present significant - static view of each use case (Hint: 1 class diagram showing only the participating entity classes, the
class diagram showing only boundary and controller classes etc.)
Design the classes further: Identify the oportunity of re-use. Refactor classes that are identified. Refine classes to such an extent that you can start writing code.
Premier Auto Electric is a trading company involved in buying and selling of Automobile spare parts. There are around 28 manufactures who are suppliers to PAE. PAE buys spare
parts from these manufacturers in bulk quantities and sells it to various stockists and dealers all over India on 10% of profit margin. PAE has 34 sales-locations all over India.
The purchases are centralized and controlled by head office of PAE. The Depot-Manager constantly keeps a check on the stock levels of various products. Specially of those which
are very fast moving products (heavly sold). He identifies those products which needs to be ordered so that inventory is maintained. The system must provide a facility to Depot-
Manager to view stock status of only his depot. He then, identifies the product the inventory which has reached re-order level and raises a purchase-request for such products. The
Depo-Manager sends the purchase request to H.O. The system maintains the information of the sales-depot who has sent the purchase request.
There is one Purchase-Controller at the H.O. who receives and acts upon all the purchase requests that were sent by various sales-depots. He has a very important job to do. He
will view the purchase requests and study the same of each product. He will then see whether the same product is available at some other sales-depot or not. He will also make
note of the age of the inventory of selected product and only if it is more than 6 months, he will raise the transfer advice to the sales-depot having the product to transfer it to
sales-depot that needs it. The transfer quantity will be equal to purchase-request quantity or quantity available with transfering depot which ever is lesser. If the product is not
available in any of the sales-deport with age more than or equal to 6 months, then the Purchase-Controller will mark the product for "ordering".
The suppliers of PAE are manufacturers. They manufacture specific products belonging to specific automobile. For e.g. Mico Bausch manufactures clutch plates of Maruti and break
pads of Tata-Indica. This product information along with its rate is maintained in the system for each supplier. The Purchase-Controller can generate the Purchase Orders based on
all the products that were marked for "ordering". The system must auto-detect the supplier of the product and create 1 purchase order for each supplier containing all the
products that were marked for "ordering". System must auto-set the "dispatch to:" on the purchase order to the address of sales-depot who had initially requested the purchase of
product. Please note that 1 - Purchase Order will contain aggregate quantity of products requested by various sales-depot. Hence the bifurcation of "despatch-to" must be
specified on the purchase order. The orders once generated, are printed and couriered to the Supplier. The status of the Purchase-Request is made available to the Depot-
Manager. If the product has been asked to transfer from one depot to the other - the transfer advice details are shown against the product requested, if the product was ordered
to the supplier - the purchase order details will be shown against the product requested or else "No-Action-Yet" must be displayed against the product requested
The Supplier ships the ordered goods to the location specified against "dispatch to:". The Stores keeper at the respective location will accept the goods and prepare a "Goods
Receipt Note". The GRN will be recorded against either a transfer advice or a purchase order. The system must advice the Stores Keeper that he must accept the GRN based on
transfer advice or purchase order using the status of purchase request. This will add up the inventory of the product accepted in the stores.
The Purchase Accounting is done by the Purchase Officer at H.O. centrally. The purchase officer views all the Supplier Wise - GRN(s) received by various sales-depots and books
the purchase. Purchase Booking involves crediting the Supplier A/C and Debiting the Purchase A/C. This updates Payable Info of the supplier. The Purchase Officer issues cheques
to the Suppliers against the purchases booked. This again the updates the payable info (reduces the total payable) of the Supplier. One single cheque can be issued for 1 or more
than 1 purchases booked.
Identify the layers in the system. Establish relationship between these layers.
Identify Key Abstractions and identify the relationships among them. Identify the cardinality (multiplicity) among these classes
Create Use Case Realizations package and realize each use case you have identified.
Create Sequence Diagrams to illustrate the dynamic behaviour. Identify boundary and controller classes while doing so.
Create a VOPC class diagram to present the static structure of the use case.
Identify the dependencies among these packages. Also describe Architectural Mechanisms (Data Transfer Object Mechanism, MVC Mechanism)
Design Components
Perform Use Case Design - Take each use can do the use case design (low level design) for each use case under the umbrella of Architecture (high level design).
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006
ITServicesOne.com - A Dream Project of Muhammed Shakir Page 61 of 61
Design Subsystems
Update VOPC of each use case. Create class diagrams to present significant - static view of each use case (Hint: 1 class diagram showing only the participating entity classes, the
class diagram showing only boundary and controller classes etc.)
Design the classes further: Identify the oportunity of re-use. Refactor classes that are identified. Refine classes to such an extent that you can start writing code.
Problem Statement
As the head of information systems for Wylie College you are tasked with developing a new student registration system. The college would like a new client-server system to replace its much older system developed around
mainframe technology. The new system will allow students to register for courses and view report cards from personal computers attached to the campus LAN. Professors will be able to access the system to sign up to teach
courses as well as record grades.
Due to a decrease in federal funding the college cannot afford to replace the entire system at once. The college will keep the existing course catalog database where all course information is maintained. This database is an
Ingress relational database running on a DEC VAX. Fortunately the college has invested in an open SQL interface that allows access to this database from college’s Unix servers. The legacy system performance is rather
poor, so the new system must insure that access to the data on the legacy system occurs in a timely manner. The new system will access course information from the legacy database but will not update it. The registrar’s
office will continue to maintain course information through another system.
At the beginning of each semester students may request a course catalogue containing a list of course offerings for the semester. Information about each course, such as professor, department, and prerequisites will be
included to help students make informed decisions.
The new system will allow students to select four course offerings for the coming semester. In addition, each student will indicate two alternative choices in case the student cannot be assigned to a primary selection.
Course offerings will have a maximum of ten students and a minimum of three students. A course offering with fewer than three students will be canceled. For each semester, there is a period of time that students can
change their schedule. Students must be able to access the system during this time to add or drop courses. Once the registration process is completed for a student, the registration system sends information to the billing
system so the student can be billed for the semester. If a course fills up during the actual registration process, the student must be notified of the change before submitting the schedule for processing.
At the end of the semester, the student will be able to access the system to view an electronic report card. Since student grades are sensitive information, the system must employ extra security measures to prevent
unauthorized access.
Professors must be able to access the on-line system to indicate which courses they will be teaching. They will also need to see which students signed up for their course offerings. In addition, the professors will be able to
record the grades for the students in each class.
http://10.1.68.128/portlets/etraining/surfprogram/toDisplayAllProgramCont... 12/06/2006