CoreJava_JSP_Servlet_Struts_EJB

Share Embed Donate


Short Description

Download CoreJava_JSP_Servlet_Struts_EJB...

Description

Amit Kr. Balyan

INDEX 1.

Introduction of Java

2.

JSP/Servlet

3.

Struts 1.2

4.

EJB 1.2/3.0

5.

Problem Statement Welcome to the Training Program: Core Java, JSP & Servlets

(ID: 5142)

Brief Description This is core java training program that gives you a good head start with Java as a programming language

Objectives ● ● ● ● ● ●

To get overview of Object Oriented Analysis & Design To understand java as a programming language Get aquainted with Object Oriented features in Java Learning basic packages in java for writing database applications To understand use of java in web-technologies To learn how to write Java Server Pages and Servlets

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 file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (1 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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

System Requirements & OO Modeling Chapter: 1 - Basic Concepts of OO Defining Object Technology What is Object Technology ?



Object technology is a set of principles guiding software construction together with languages, databases and other tools that support these principles

Strengths of Object Technology

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (2 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



A Single paradigm - A single language used by analysts, designers and implementors



Facilitates architectural and code reuse



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 Resilient / Adaptive to change

Why do we model ?







We build models to better understand the system we are developing Modeling achieves four aims. Modeling: ❍ Helps us to visualize a system as we want it to be. ❍ Permits us to specify the structure or behavior of a system ❍ Gives us a template that guides us in constructing a system ❍ Documents the decisions we have made We build models of complex systems because we cannot apprehend a system in its entirety

Basic Principles of OO The Four Basic Principles

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (3 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Abstraction



Encapsulation



Modularity



Heirarchy

Abstraction









The essential characteristics of an entity that distinguish it from all other kinds of entities is an Abstraction. Defines boundary relative to the perspective of the viewer. 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (4 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Hiding implementation form client - components is encapsulation.



Abstraction & Encapsulation both goes hand in hand



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



Modularity is the breaking up of something complex into manageable pieces.



Modularity helps people understand complex systems.



E.g. : Purchase System, Sales System, Accounts System are all different modules of one large ERP system

Heirarchy

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (5 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





Any ranking or ordering of abstractions into a tree-like structure. Kinds: Aggregation hierarchy, specialization hierarchy, containment hierarchy, inheritance hierarchy, partition hierarchy.



Hierarchy is not a organizational chart nor a functional decomposition



The core objective is to break down complexity which will be manageable and changeable

What is an Object ? What is an Object ?





Informally, an object represents an entity, either physical, conceptual or software. ❍ Physical – Truck or a Person ❍ Conceptual – Chemical Process ❍ Software – Invoice 101, Sales Order SO01 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.

Object Has State

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (6 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



The state of an object is one of the possible conditions in which an object may exist



The state of an object normally changes over time





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 Give me some more examples of Object

Object has Behaviour









Behavior determines how an object acts and reacts The visible behavior of an object is modeled by the set of messages it can respond to (operations the object can perform Professor Kanetkar’s Behavior : ❍ Submit Final Grades() ❍ Accept Course Offerings() ❍ Take a vacation() The behavior may change the state of an object - (Setter methods)

Object has Identity file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (7 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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 A class is an abstraction in that it ❍ Emphasizes relevant characteristics ❍ Suppresses other characteristics There are many objects identified for any domain Recognizing the commonalities among the objects and defining classes help us deal with the potential complexity

A Relationship Between Classes & Objects

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (8 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



A class is an abstract definition of an object.



It defines the structure & behavior of each object in the class



It serves as a template / blue print for creating objects

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



A class may have any number of attributes or no attributes at all.



An attribute has a type, which tells us what kind of attribute it is.



Typically attributes are integer, boolean, varchar etc. These are called primitive types.



Primitive types can be specific for a certain programming language.

Operations of a Class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (9 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



An operation is the implementation of a service that can be requested from any object of the class to affect behavior



A class may have any number of operations or none at all



The operations in a class describe what class can do





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.



Polymorphism is of two types: Dynamic and Static.





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

Employee emp = null; if (type.equalsIgnoreCase("S")) { emp = new SalariedEmployee(); } else { emp = new ContractEmployee(); } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (10 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

emp.processSalary(); 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 ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (11 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









Interface has declaration of services. 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



Interfaces formalizes polymorphism Without interfaces there was no way to enforce polymorphism

Chapter: 2 - Implementing OO Working with Classes & Objects Identifying Classes

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (12 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Read the following and identify (abstractions) classes: The Salesman brings orders from customers and records these orders in the software system. The invoices are generated based on orders that are recorded. Once the invoice is created against an order, the order is considered as closed. The Stores Keeper then packs the goods into cartons and gives it to the transporter. The transporter delivers the goods to the customer. The customer makes payment within 45 days and it is recorded by the A/Cs officer. The customer always send payment against a particular invoice. Once the pmt is recieved against an invoice, the invoice is considered as closed



Identify the abstractions by identifying nouns of interest to your Sales Application.



Identify attributes



Identify methods



Give possible objects of the classes you have identified.

Writing Classes



Write a class with the name : Customer.java as follows: public class Customer { private int id; private String name; private String address;

public int getId() { return this.id; file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (13 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

} public void setId(int aid) { this.id = aid; } public String getName() { return this.name; }

public void setName(String aname) { this.name = aname; } public String getAddress() { return this.address; } public void setAddress(String aaddress) { this.address = aaddress; } }



Note the attributes and methods defined. These attribites are known as instance variables or member data or field variables of the class



Attributes will help establish state of the object this class



Methods will help establishing behaviour of this class



Write a class called CustomerManager.java which will instantiate Customer and invoke methods on it as follows:

public class CustomerManager { public static void main(String args[]) { file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (14 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Customer customer1 = new Customer(); customer1.setId(101); customer1.setName("IBM"); customer1.setAddress("Pune"); Customer customer2 = new Customer(); customer2.setId(102); customer2.setName("3 I Infotech"); customer2.setAddress("Mumbai"); System.out.println("The name of customer 1 is : " + customer1.getName()); System.out.println("The name of customer 2 is : " + customer2.getName()); } } Run this class file and see the results. Let me now explain how the classes are loaded and objects are represented in Randaom Access Memory

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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (15 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Working with Inheritance / Generalization Writing a Super Class





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 Write SalesOrder Super Class as follows:

import java.util.Date; public abstract class { private private private private private

SalesOrder

int orderId; Date orderDate; int customerId; int quantity; float taxAmount;

public void setOrderDate(Date d) { System.out.println("setOrderDate method getting executed in SalesOrder - the Super-Class"); this.orderDate = d; } public int getOrderId() { System.out.println("getOrderId method getting executed in SalesOrder - the Super-Class"); return this.orderId; } public void setOrderId(int aorderId) { file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (16 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

System.out.println("setOrderId method getting executed in SalesOrder - the Super-Class"); this.orderId = aorderId; }

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

Writing Sub Classes



Write a ExportOrder class which is Sub Class of SalesOrder class as follows:

public class ExportOrder extends SalesOrder { public void calculateTax() { System.out.println("The tax is being processed by Class"); } } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (17 of 258)12/6/2010 2:00:24 AM

ExportOrder - the Sub-

Amit Kr. Balyan



Now write a LocalOrder sub class as follows:

public class LocalOrder extends SalesOrder { public void calculateTax() { System.out.println("The tax is being processed by Class"); }

LocalOrder - the Sub-

}

Using Inheritance Class-Structure



Now write the OrderManager class which uses the SalesOrder class structure as follows:

public class OrderManager { public static void main(String args[]) { ExportOrder expOrder = new ExportOrder(); expOrder.setOrderId(101); expOrder.calculateTax(); LocalOrder locOrder = new LocalOrder(); locOrder.setOrderId(102); locOrder.calculateTax(); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (18 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

// See the following technique of working with inheritence // (Example of Dynamic Polymorphsim) String userInput = null; SalesOrder order = null; if (args.length > 0 ) { userInput = args[0]; } else { userInput = "L"; } 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

Working with Polymorphism file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (19 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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. So please write a method in ExportOrder as follows:

public void setOrderId(int aorderId) { System.out.println("setOrderDate of ExportOrder the Sub-Class"); super.setOrderId(aorderId); this.setOrderDate(new Date()); // import java.util.Date // Also I hope you have written setter getter methods for // order date in the SalesOrder class }





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 file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (20 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



This is pretty simple



Add two methods in the LocalOrder class with same name but two different signatures as follows:

public void calculateAmount() { System.out.println("The calculateAmount with no param"); } public void calculateAmount(boolean withTaxes) { System.out.println("The calculateAmount with 1 param"); }



Execute both of these methods from OrderManager on locOrder object and see the results.



This is also Static - Polymorphism

Working with Associations Creating the Supplier Class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (21 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan







Create a new class called : Customer.java and define 4 attributes as follows: ❍ private int id ❍ private String name ❍ private int cityId ❍ private String address Write the public getter (accessor) and setter (mutator) methods for each of the attributes defined above Compile the class

Creating the client class





Create a class called Invoice.java. Create the following instance variables: ❍ private int id ❍ provate float amount ❍ private int productId and ❍ private Customer customer Create a constructor and a method called saveInvoice as follows:

public Invoice() { customer = new Customer(); customer.setName("IBM"); } public void saveInvoice() { String name = customer.getName(); System.out.println("The name is : " + name); } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (22 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Now create a class called InvoiceManager.java - Create a public static void main method in it and add the following code:

Invoice inv = new Invoice(); inv.saveInvoice(); Run InvoiceManager class and see the results. ●



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.

Assignment(s) Classes & Objects

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (23 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (24 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan ❍





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

Override setName method in SalariedEmployee and demonstrate the same.

Java Chapter: 1 - Introduction The JAVA Technology About Java Technology







The Java programming language is a high-level language 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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (25 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

About Java Technology (Contd.)





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.



Java bytecodes help make "write once, run anywhere" possible.



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.

The Java Platform

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (26 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



A platform is the hardware or software environment in which a program runs.



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. The Java platform has two components: ❍ The Java Virtual Machine (Java VM) ❍ The Java Application Programming Interface (Java API) Java VM is the base for the Java platform and is ported onto various hardware-based platforms.

The Java Platform (Contd.)









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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (27 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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 & the ClassPath









Path is an enviornmental variable which is used by the operating system and not your java virtual machine Where as ClassPath is used by Java - (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.

Setting the Path & Classpath

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (28 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









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:

public class MyFirstJavaClass { public static void main(String args[]) { System.out.println("My First Program In java"); } }



Compile the program using the following command on the dos prompt:

javac MyFirstJavaClass.java Now run the program using the following command:

java MyFirstJavaClass

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (29 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Creating a class in other folder



Now create a class called :MySecondJavaClass.java in c:\working\learningclasspath as follows:

public class MySecondJavaClass { public static void main(String agrs[]) { System.out.println("My Second Java Class"); } } Compile the class ●



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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (30 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



The Jar files are simply zip files that contain the .class files



See the rt.jar file



All the classes that you have used till now for e.g. String, System class etc. are all in rt.jar file



Note that the classes are organized in appropriate folders

The Classpath Trick(s)





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 :

SalesManager manager = new SalesManager(); manager.AddInvoice(); Save the file. Now set the classpath to c:\working\c1;c:\working\c2;. 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. NEVER DESIGN AN APPLICATION LIKE THIS

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (31 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan ●

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"

Data Types in Java Primitive Data Types







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. Following are the primitive data types in java: ❍ byte ❍ short ❍ int ❍ long ❍ float ❍ double ❍ char ❍ boolean Using Literals: ❍ ‘c’ – char ❍ 178 – int ❍ 8864 – long ❍ 37.266D – double ❍ 38.99F – float ❍ true - boolean ❍ false - boolean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (32 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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

More on float and double



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



This is because a double can hold value greater than 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

Working with Primitive Data-Types

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (33 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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;

System.out.println("The value of f is : " + f); System.out.println("The value of result is : " + result); 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; /* Below given line gives an error - because L is not added at the end indicating its a long */ // long l = 122222222222; long l = 1222222222222L; System.out.println("The value of l is : " + l); byte b = 3; short s = 2; s++; f++; d++; l++; System.out.println("The value of s is : " + s); // Use SOP to print the value of all the variables incremented above file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (34 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

System.out.println("Max System.out.println("Max System.out.println("Max System.out.println("Max System.out.println("Max System.out.println("Max





of of of of of of

byte : " + Byte.MAX_VALUE); short : " + Short.MAX_VALUE ); int : " + Integer.MAX_VALUE ); Long : " + Long.MAX_VALUE); float : " + Float.MAX_VALUE); double is : " + Double.MAX_VALUE);

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 orderDispatched : " + orderDispatched);

The Wrapper Classes

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (35 of 258)12/6/2010 2:00:24 AM

+ " And

Amit Kr. Balyan



All the number - primitive data types has wrapper classes.



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 :

int age = 25; Integer theAge = new Integer(age); double dAge = theAge.doubleValue(); double ddd = 10200.20222; System.out.println("ddd : " + ddd); Double salary = new Double(10200.20); int intPartOfSalary = salary.intValue(); System.out.println("The intPartofSalary is : " + intPartOfSalary); Double taxAmount = new Double(300000.25); float fTax = taxAmount.floatValue(); System.out.println("Byte value of taxAmount : " + fTax);

Type Casting of primitive data types

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (36 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan







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; //bb = ss; // not possible ss = bb; // possible //ss = ii; // not possible ii = ss; // possible // ii = ll; not possible ll = ii; // possible // ll = ff; // not possible ff = ll; // possible //ff = dd; // not possible dd = ff ; //possible 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); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (37 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Note that it prints -127 because 129 exceeds the MAX_VALUE of byte.

Variables and their scope Local Variables



When you declare variables in a method its scope is limited to the scope of the method.



Such variables are known as local variables





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 file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (38 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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.



Each object has its own copy of instance variable



The instance variable is definitely available to all the methods of the class in which is defined.

Scope of instance variables







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



Write a Customer class and define the variables in it as follows:

private int id; public int cityId; protected int stateId; 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 file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (39 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Class variables









Class variables are defined as static variables in the class. 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) Write SalesMan.java class as follows:

public class SalesMan { private String name; private static int totalSalesMen = 0; public SalesMan() { totalSalesMen ++; } public void setName(String aname) { this.name = aname; } public String getName() { return this.name; } public int getTotalSalesMen() { return this.totalSalesMen; } } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (40 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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



Local, instance , class - any of these variables can be 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.

Methods and their Scope Method Scope

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (41 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



The methods in a class can be private, public or protected



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 Methods can have arguments of any data type (primitive or object).

Final Methods and Abstract methods



Final Methods are those which cannot be overriden



Abstract methods are those which simply declared - no implementation of method is provided

Operators Arithmetic Operators

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (42 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





Arithmetic Operators in Java are as follows: ❍ + (add), - (subtract), * (multiply), / (divide), % (remainder) ❍ ++, -- (pre and post increments) ❍ += ❍ -=, ❍ *= ❍ /= Relational Operators: ❍ >, =, = 10000 && department.equalsIgnoreCase ("Information Technology") ? true : false; System.out.println("isSalAcceptable : " + isSalAcceptable);

Inheritance & Abstract Classes 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



The generalized behaviour can be overriden by the specialized class





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 refer to Basic OOAD UML Tutorial for working examples

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (44 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Final Classes & Methods



Final Classes are those classes that cannot be specialized or inherited



Final methods are those methods that cannot be overriden





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









Abstract classes are those classes that cannot be instantiated. 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 Clients depend on abstraction and not implementation

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (45 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Constructors and Overloading them What are constructors



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 constructor method has name as same as class name.



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



You can overload constructors



The overloaded constructors will all have different signatures



Wrtie a class called Employee.java as follows:

public class Employee { public Employee() { System.out.println("The Constructor of Employee"); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (46 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

}

public Employee(int id) { System.out.println("The Constructor in Employee with 1 parameter"); } }



Now also write EmployeeManager class as follows:

public class EmployeeManager { public static void main(String args[]) { Employee emp1 = new Employee(); Employee emp2 = new Employee(301); } } Execute EmployeeManager and see the results

Constructors in inherited classes

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (47 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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. Write a new SalariedEmployee.java class as follows:

public class SalariedEmployee extends Employee { public SalariedEmployee() { System.out.println("The SalariedEmployee Constructor is executed"); }

public SalariedEmployee(int id) { System.out.println("The SalariedEmployee Constructor with 1 parameter is executed"); } public SalariedEmployee(int id, String name) { super(2); System.out.println("The SalariedEmployee Constructor with 2 parameters is executed"); } }



Add the following lines in EmployeeManager class and execute the same and see the results:

SalariedEmployee s1 = new SalariedEmployee(); SalariedEmployee s2 = new SalariedEmployee(2); SalariedEmployee s3 = new SalariedEmployee(2, "Mr. Menon"); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (48 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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); Now compile SalariedEmployee - it will get compiled successfully.

Packages & Importing Classes & Interfaces Package in Java









A package in java is like namespace in C++. 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. The package statement must be included right-on-top in the class as follows:

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (49 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

which as same as the name of the package used in the class. Remember the names- here are casesensitive.

Importing Classes



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 public void saveOrder() { CreditAccount account = new CreditAccount(); } } 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 ●





You can use * in order to import all classes of a particular package. * 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 Do the following to learn packages in java practically: ❍ Create a new folder structure is your c drive as c:\working\learningpackages ❍ Set class path to . using the command: set Classpath=. ❍ Now create two folders in c:\working\learningpackages - sales and accounts.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (50 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan ❍

❍ ❍ ❍



Create a class called OrderManager.java in c:\working\learningpackages (the source code is given below) Create SalesOrder.java in sales folder (source code is given below) Create Account.java in accounts folder (source code is given below) Compile all classes keeping your command prompt at c:\working\learningpackages using javac *.java

Following lines for OrderManager.java:

import sales.SalesOrder; import accounts.Account; public class OrderManager { public static void main(String args[]) { // Note that following will be successfully executed SalesOrder order = new SalesOrder(); Account account = new Account(); // Now comment the above two import statements and recompile // It will give you compilation error. } } Following lines for SalesOrder.java (in sales folder) :

package sales; public class SalesOrder { public SalesOrder() { System.out.println("SalesOrder Object successfully created"); } }

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (51 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Following lines for Account.java (in accounts folder):

package accounts; public class Account {

public Account() { System.out.println("Account Object successfully created"); } }

Writing Interface



Write an interface called TaxCalculator as follows:

public interface TaxCalculator { public void calculateTax(); public float getTax() ; }



Now write a class called Invoice which implements this interface as follows :

public class Invoice implements TaxCalculator { // you will have to implement all the methods in TaxCalcualtor file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (52 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

}





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.

Java Behaviour to Resolve Ambiguity



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:

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 ●

Test this out and see the results.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (53 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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.

Data Type Assignments

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (54 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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

//format the sum, do not forget to import java.text.DecimalFormat DecimalFormat myFormatter = new DecimalFormat("###,###.##"); String output = myFormatter.format(sum);

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (55 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan ●

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.

Variable & Method Scope Assignments



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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (56 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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



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 are Arrays What is an Array

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (57 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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



You can create arrays of primitive types.



You can access array elements by its subscript



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 The .length gives you the total number of elements in an array

Working Examples

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (58 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Write the following code in main method of PrimitiveTypeArrays.java

int arrayOfInt[] = new int[] {2, 3, 5}; for (int i = 0; i < arrayOfInt.length; i++) { System.out.println("The " + i + " element has value }

: " + arrayOfInt[i]);

int arrayOfSalaries[] = null; arrayOfSalaries = new int[5]; arrayOfSalaries[0] = 50000; arrayOfSalaries[1] = 20000; arrayOfSalaries[2] = 30000; for (int i = 0; i < arrayOfSalaries.length; i++) { System.out.println("The " + i + " salary has value

: " + arrayOfSalaries

[i]); } char arrayOfChars[] = new char[] {'c', 'r', '1'}; // Use for loop to print the values char arrayOfDeptType[] = null; arrayOfDeptType = new char[3]; arrayOfDeptType[0] = 'A'; arrayOfDeptType[1] = 'I'; arrayOfDeptType[2] = 'H'; // Use for loop to print the values /* Uncomment the below given line and run the class * You will get ArrayIndexOutOfBoundsException - runtime exception. */ // arrayOfDeptType[4] = 'X'; double arrayOfIncrements[] = new double[] {23.4, 45.44, 12.33}; // Use for loop to print the values file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (59 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Create the arrays of other primitive data types in the above class and see the results

Array of Wrapper Classes Array of Wrapper Classes



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 :

String names[] = new String[] {"Shakir", "Priyanka", "Sumeet"}; for (int i = 0; i < names.length; i++) { System.out.println("The " + i + " name is : " + names[i]); } String departmentNames[] = new String[5]; departmentNames[0] departmentNames[1] departmentNames[2] departmentNames[3] departmentNames[4]

= = = = =

"Accounts"; "H.R."; "I.T"; "P.R."; "Sales";

// Use for loop to display all the values



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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (60 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Array of User-Defined Objects Array of User-Defined Objects



You can also create array of objects which belongs to classes defined by you in your application



Write a new class called Customer.java as follows:

public class Customer { private int id; private String name; public void setName(String aname) { this.name = aname; } public String getName() { return this.name; } public void setId(int aid) { this.id = aid; } public int getId() { return this.id; } }



Now create CustomerManager.java and write the following in main method, compile and see the results:

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (61 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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"); // Following line will throw ArrayIndexOutOfBoundsException myCustomers[3].setId(104); Customer customers[] = new Customer[5]; customers[0] = new Customer(); customers[0].setId(201); customers[0].setName("CapGemini"); customers[1] = new Customer(); customers[1].setId(202); customers[1].setName("i-flex"); customers[2] = new Customer(); customers[2].setId(203); customers[2].setName("GTL"); customers[3] = new Customer(); customers[3].setId(204); customers[3].setName("Wipro"); // 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++) { file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (62 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

System.out.println("The id of " + i + " Customer is :" + customers[i].getId () + " and name is : " + customers[i].getName()); } /* Uncomment the following line and execute this class. It will throw NullPointerException runtime exception */ //customers[4].setId(205);

Double Dimension Arrays Double Dimension Array of int



You can also create double dimension arrays in java.



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++) { for (int j = 0; j < doubleDimension[i].length; j++) { System.out.println("The " + i + " row and " + j + " column has value : " + doubleDimension[i][j]); } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (63 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

}

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.

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]; for (int i = 0; i < stringBuffers.length; i ++) { stringBuffers[i].append("StringBuffer at index " + i); } } } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (64 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Write a program which will have the following array declared:

String[] skiResorts = { "Whistler Blackcomb", "Squaw Valley", "Brighton", "Snowmass", "Sun Valley", "Taos" }; Print the index of "Brighton" ●





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.

Chapter: 3 - Exception Handling What is an Exception What is an Exception

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (65 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











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.

Who Handles the 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. The exception handler chosen is said to catch the exception.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (66 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Advatages of Exception



Advantage 1: Separating Error Handling Code from "Regular" Code



Advantage 2: Propagating Errors Up the Call Stack



Advantage 3: Grouping Error Types and Error Differentiation

Throwable class & its sub-classes

Errors



When a dynamic linking failure or some other "hard" failure in the virtual machine occurs, the virtual machine throws an Error



Typical Java programs should not catch Errors



In addition, it's unlikely that typical Java programs will ever throw Errors either

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (67 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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.



These descendants indicate various types of exceptions that can occur. For example, IllegalAccessException signals that a particular method could not be found, and NegativeArraySizeException indicates that a program attempted to create an array with a negative size.



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. A NullPointerException can occur anywhere a program tries to dereference a reference to an object. The cost of checking for the exception often outweighs the benefit of catching it. Because runtime exceptions are so ubiquitous and attempting to catch or specify all of them all the time would be a fruitless exercise (and a fruitful source of unreadable and unmaintainable code), the compiler allows runtime exceptions to go uncaught and unspecified.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (68 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Working with try - catch The try - catch block



Write a class called InputFile.java as follows:

private FileReader in; public InputFile(String filename) { //try { in = new FileReader(filename); //} catch (FileNotFoundException ex) { // System.out.println("The FileNotFoundException has occurred: " + ex. getMessage()); //}

} // following function returns the first word in the text file public String getWord() { int c = 0; StringBuffer buf = new StringBuffer(); do { // try { c = in.read(); // } catch (IOException ex) { // System.out.println("The IOException is : " + ex.getMessage()); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (69 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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

The try - catch block (Contd.)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (70 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Write a new class called FileManager.java and write the following code in its main method:

InputFile f = new InputFile("c:/working/learningexceptions/TheTextFile.txt"); System.out.println(f.getWord());





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

Adding more than one catch



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



You will again get the compilation error.



Now add one more catch to the existing try in the constructor as follows:

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (71 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

catch (ClassNotFoundException ex) { System.out.println("The ClassNotFoundException : " + ex.getMessage()); } Now the class will compile successfully. ●

There can be as many catch blocks as it would take to successfully write all the code that throws exception.

Java's Catch or Specify Requirement 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (72 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (73 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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. Exceptions throws withing the scope of method





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

Dealing with Exceptions The List Number Example



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 class ListOfNumbers { private Vector victor; private static final int size = 10; public ListOfNumbers () { file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (74 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); 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: out = new PrintWriter(new FileWriter("OutFile.txt")); 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: out.println("Value at: " + i + " = " + victor.elementAt(i));







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. Java requires that you catch or specify only checked exceptions

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (75 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Catching & Handling Exceptions







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.

Catching & Handling Exceptions (try block)



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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (76 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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.

PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); }





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.

Catching & Handling Exceptions (catch block)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (77 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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

. ( . . . ) { . ( . . . ) { .

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:

catch (SomeThrowableObject variableName) { Java statements }







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 { file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (78 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

. . . } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }

Catching & Handling Exceptions (catch block) - Contd.











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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (79 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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 Catching & Handling Exceptions (finally block)







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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (80 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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

Putting it all together



The is how the writeList method is finally written:

public void writeList() { PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (81 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } }





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

How to Throw Exceptions The Throw Statement

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (82 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









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:

testing.java:10: Cannot throw class java.lang.Integer; it must be a subclass of class java.lang.Throwable. throw new Integer(4);



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:

public Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException();

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (83 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

obj = objectAt(size - 1); setObjectAt(size - 1, null); size--; return obj; } Make note of the statements in bold.

Creating Your Own Exceptions



Create your own exception called InvalidBalanceException as follows:

public class InvalidBalanceException {

extends Exception

public InvalidBalanceException() { } public InvalidBalanceException(String msg) { super(msg); } }



Now write Account.java as follows:

public class Account { file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (84 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

public void creditAccount() throws InvalidBalanceException {

if (true) { // balance is not sufficient then throw new InvalidBalanceException("Insufficient Balance"); } } }



Write AccountsApp.java as follows:

public class AccountsApp { public static void main(String args[]) {

Account acc = new Account(); /* please note that following method invocation must * be in try catch block. Surround it with try catch block * and print the error message in the catch block. */ acc.creditAccount();

} }



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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (85 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

More on Java Architecture Java Virtual Machine











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.

Java Virtual Machine (Contd.)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (86 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











End-users can download and install the Windows JRE themselves. 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). The JVM is the Java equivalent of the .NET Framework's CLR. 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.

JIT (Just-In-Time) Compilers











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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (87 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Some environments allow you to choose whether or not to JIT code. The Byte Code Verification Process









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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (88 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



The Byte Code verifier traverses the bytecodes, constructs the type state information, and verifies the type of parameters to all the bytecode instructions

Assignment(s) Exception Handling Assignment





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 ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (89 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



We write lot of programs where each has a beginning, an execution sequence, and an end.



A thread is similar to the sequential programs.





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



A thread is a single sequential flow of control within a program (Process)



There is nothing new in the concept of a single 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. This is illustrated by the following figure:

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (90 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Definition of Thread (Contd.)











Some texts use the name lightweight process instead of thread. 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.

Using Timer & Timer Task Using Timer & Timer Task

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (91 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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. */ public class Reminder { Timer timer; public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); timer.cancel(); //Terminate the timer thread } } public static void main(String args[]) { System.out.println("About to schedule task."); new Reminder(5); System.out.println("Task scheduled."); } } When you run the example, you first see this:

Task scheduled. file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (92 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Five seconds later, you see this: 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.:

//Get the Date corresponding to 11:01:00 pm today. Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); Date time = calendar.getTime(); timer = new Timer(); timer.schedule(new RemindTask(), time);

Stopping Timer Threads

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (93 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan







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:

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. */ public class ReminderBeep { Toolkit toolkit; Timer timer; public ReminderBeep(int seconds) { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } class RemindTask extends TimerTask { public void run() { System.out.println("Time's up!"); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (94 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

toolkit.beep(); //timer.cancel(); //Not necessary because we call System.exit System.exit(0); //Stops the AWT thread (and everything else) } } public static void main(String args[]) { System.out.println("About to schedule task."); new ReminderBeep(5); System.out.println("Task scheduled."); } }

Performing a Task Repeatedly



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 class AnnoyingBeep { Toolkit toolkit; Timer timer; public AnnoyingBeep() { toolkit = Toolkit.getDefaultToolkit(); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (95 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

timer = new Timer(); timer.schedule(new RemindTask(), 0, //initial delay 1 * 1000); //subsequent rate } class RemindTask extends TimerTask { int numWarningBeeps = 3; public void run() { if (numWarningBeeps > 0) { toolkit.beep(); System.out.println("Beep!"); numWarningBeeps--; } else { toolkit.beep(); System.out.println("Time's up!"); //timer.cancel(); //Not necessary because we call System.exit System.exit(0); //Stops the AWT thread (and everything else) } } } public static void main(String args[]) { System.out.println("About to schedule task."); new AnnoyingBeep(); System.out.println("Task scheduled."); } }

Customizing Threads run Method file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (96 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Customizing a Thread's run Method









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

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:

public class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((long)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (97 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

} }









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

public class TwoThreadsDemo { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } } The main method also starts each thread immediately following its construction by calling the start method.

Assignment(s) file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (98 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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.

Chapter: 5 - IO API Java I/O Streams Java Stream I/O





Often a program needs to bring in information from an external source or to send out information to an external destination. The information can be anywhere: in a file, on disk, somewhere on the network, in memory, or in another program.



Also, the informa-tion can be of any type: objects, characters, images, or sounds.



This chapter covers the Java™ platform classes that your programs can use to read and to write data.

Overview of I/O

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (99 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan







To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information sequentially, as shown here

Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out sequentially, like this:

No matter where the data is coming from or going to and no matter what its type, the algorithms for sequentially reading and writing data are basically the same:

Reading

Writing

open a stream while more information read information close the stream

open a stream while more information write information close the stream

Stream Types

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (100 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









The java.io package contains a collection of stream classes that support these algorithms for reading and writing. To use these classes, a program needs to import the java.io package. The stream classes are divided into two class hierarchies, based on the data type (either characters or bytes) on which they operate. ❍ Character Streams ❍ Byte Streams

Reader and Writer are the abstract superclasses for character streams in java.io. Reader provides the implementation for readers--streams that read 16-bit characters--and Writer provides the implementation for writers--streams that write 16-bit characters. Most programs should use readers and writers to read and write textual information. The reason is that they can handle any character in the Unicode character set, whereas the byte streams are limited to ISO-Latin-1 8-bit bytes.

To read and write 8-bit bytes, programs should use the byte streams, descendants of InputStream and OutputStream. InputStream and OutputStream provide the implementation for input streams (streams that read 8-bit bytes) and output streams (streams that write 8-bit bytes). These streams are typically used to read and write binary data such as images and sounds.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (101 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Byte Streams



Programs use byte streams to perform input and output of 8-bit bytes.



All byte stream classes are descended from InputStream and OutputStream.



There are many byte stream classes.



To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream. mport java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyBytes { public static void main(String[] args) throws IOException {

FileInputStream in = null; FileOutputStream out = null;

try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (102 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

if (out != null) { out.close(); } } } } Notice that read() returns an int value. If the input is a stream of bytes, why doesn't read() return a byte value? Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream



Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since xanadu.txt contains character data, the best approach is to use character streams, as discussed on the next page. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O.

Character Streams

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (103 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



All character stream classes are descended from Reader and Writer. The Java platform stores character values using Unicode conventions Character stream I/O automatically translates this internal format to and from the local character set



As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter. The CopyCharacters example illustrates these classes

import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader("xanadu.txt"); outputStream = new FileWriter("characteroutput.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } }

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (104 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Notice that both CopyBytes and CopyCharacters use an int variable to read to and write from. However, in CopyCharacters, the int variable holds a character value in its 16 bits; in CopyBytes, the int variable holds a byte value in its last 8 bits.

The Java platform stores character values using Unicode conventions Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII. For most applications, I/O with character streams is no more complicated than I/O with byte streams. Input and output done with stream classes automatically translates to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer. If internationalization isn't a priority, you can simply use the character stream classes without paying much attention to character set issues. Later, if internationalization becomes a priority, your program can be adapted without extensive recoding. See the Internationalization trail for more information. Buffered Reader



Most of the examples we've seen so far use unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive



To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full



Write the following class to see how buffered reader and writer is used import java.io.*; public class CopyWithBuffers {

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (105 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

public static void main(String args[]) throws IOException { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader("xanadu.txt")); writer = new BufferedWriter(new FileWriter("bufferedOutput. txt")); int c; while ((c = reader.read()) != -1) { writer.write(c); } } finally { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } } } }

Scanners

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (106 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan







Objects of type Scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators) To see how scanning works, let's look at ScanXan, a program that reads the individual words in xanadu.txt and prints them out, one per line. import java.io.*; import java.util.Scanner; public class ScanXan { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("xanadu.txt"))); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } } } } Notice that ScanXan invokes Scanner's close method when it is done with the scanner object. Even though a scanner is not a stream, you need to close it to indicate that you're done with its underlying stream



To use a different token separator, invoke useDelimiter(). Try using "," as the delimiter and re-run the ScanXan Class.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (107 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Scanning Individual Tokens







Scanner also supports tokens for all of the Java language's primitive types (except for char), as well as BigInteger and BigDecimal. Also, numeric values can use thousands separators. Thus, in a US locale, Scanner correctly reads the string "32,767" as representing an integer value We have to mention the locale, because thousands separators and decimal symbols are locale specific

import import import import import

java.io.FileReader; java.io.BufferedReader; java.io.IOException; java.util.Scanner; java.util.Locale;

public class ScanSum { public static void main(String[] args) throws IOException { Scanner s = null; double sum = 0; try { s = new Scanner(new BufferedReader(new FileReader("usnumbers. txt"))); s.useLocale(Locale.US); while (s.hasNext()) { if (s.hasNextDouble()) { sum += s.nextDouble(); } else { s.next(); } } } finally { s.close(); } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (108 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

System.out.println(sum); } }

Deep Cloning



Override clone method as follows for deep cloning ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); Object deepCopy = ois.readObject();

Chapter: 6 - Colllection API Collection Framework The Collection Framework

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (109 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









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 A collections framework is a unified architecture for representing and manipulating collections All collections frameworks contain three things: ❍ Interfaces: abstract data types representing collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages like Java, these interfaces generally form a hierarchy. ❍ Implementations: concrete implementations of the collection interfaces. In essence, these are reusable data structures. ❍ Algorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. These algorithms are said to be polymorphic because the same method can be used on many different implementations of the appropriate collections interface. In essence, algorithms are reusable functionality

The Collection Framework API











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 collections interfaces are shown on the next slide:

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (110 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Collection Framework API (Contd).





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

The Collection Interface



The Collection interface is the root of the collection hierarchy.



A Collection represents a group of objects, known as its elements.



Some Collection implementations allow duplicate elements and others do not.



Some are ordered and others unordered.



Collection is used to pass collections around and manipulate them when maximum generality is desired.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (111 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

The Set Interface



A Set is a collection that cannot contain duplicate elements.



This interface models the mathematical set abstraction.



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 List Interface



A List is an ordered collection (sometimes called a sequence).



Lists can contain duplicate elements.



The user of a List generally has precise control over where in the List each element is inserted.



The user can access elements by their integer index (position).



If you've used Vector , you're already familiar with the general flavor of List

The Map Interface

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (112 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



A Map is an object that maps keys to values.



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

The Collection Interface Features on Collection Interface









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

Your first Collection program

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (113 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Write a new class called SimpleCollection.java as follows:

import java.util.Collection; import java.util.ArrayList; import java.util.Iterator; public class SimpleCollection { public SimpleCollection() { }

public static void main(String agrs[]) { Collection myCustomers = new ArrayList(); 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); } } }



Compile and run this class and see the results.



Note the use of implementation class : ArrayList



Also Note the use of Iterator which provides standard mechanism of iterating through the

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (114 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Array Operations







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. Write the following snippet in the program written earlier

Object[] arrayOfObjects = myCustomers.toArray() 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.

String[] arrayOfStrings = (String[]) myCustomers.toArray(new String[0]); Write a for loop to display the contents of the String array

Bulk Operations

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (115 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan







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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (116 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

The Set Interface The Set



A Set is a Collection that cannot contain duplicate elements.



Set models the mathematical set abstraction.







The Set interface extends Collection and contains no methods other than those inherited from Collection. It adds the restriction that duplicate elements are prohibited One of the general-purpose implementation of Set interface is : HashSet which stores its elements in Hashtable and the other implementation is TreeSet

Methods on Set Interface



The Set interface is shown below:

public interface Set { // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (117 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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: Collection noDups = new HashSet(c);





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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (118 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



The size operation returns the number of elements in the Set (its cardinality).



The isEmpty method does exactly what you think it does.







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. The iterator method returns an Iterator over the Set.

Basic Operations (Contd.)



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.*; public class FindDups { public static void main(String args[]) { Set s = new HashSet(); for (int i=0; i> Administrative Tools >> Data Sources (ODBC) 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



Please create the following tables in your database:

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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (134 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (135 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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:

Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");









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.

Retrieving Values from DBMS Retrieving Values from Database

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (136 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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:

ResultSet rs = stmt.executeQuery("Select id, name, address, cityId from Customer"); Surround all the code you write in try catch block catching SQLException.

Using the next method











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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (137 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Using the getter Methods on ResultSet









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:

String query = "SELECT id, name, address, cityId from Customer"; Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); System.out.println(id + " " + name); } Write the program now, execute it and see the results. ●

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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (138 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Updating & Deleting Values Updating Values







Suppose the address a customer with id = 101 changes to "Mumbai". Write a new class called UpdateData.java. Load the drivers, get the connection and create statement the same way you did in earlier program. Only, this time write

String sql = "Update Customer set address = 'Mumbai' where id = 101"; stmt.executeUpdate(sql); 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

Using Prepared Statements When to Use Prepared Statement

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (139 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









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.

Creating the PreparedStatement



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

Try out the PreparedStatement for update & delete as well.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (140 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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.

Using Transactions What is one unit of Work ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (141 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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.



This is called committing or rolling back.



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.

Setting the Auto Commit attribute of Connection





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(). In order to get hands-on practice on this, do the following: ❍ Create a table Called CustomerAddress (customerId number (5), addressline1 varchar (20), addressline2 varchar (20), addressline3 varchar (20)) ❍ The primary key in this table is customerId + addressline1 ❍ The addressline1 cannot be left null ❍ Write a program called CustomerManager.java ● which will insert 1 customer row in Customer table ● 1 or more than 1 Customer addresses for the Customer inserted ● Here Customer is a composite of CustomerAddress ● Hence it must be ensured that atleast 1 address of the customer and also that if any one of the customer address creation fails, the insert in Customer must also fail ❍ Use con.setAutoCommit(false) immediately after creating connection object ❍ Use con.commit() only after customer and customer addresses are all successfully inserted ❍ Use con.rollback(), even if one address creation fails

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (142 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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. Below is just a hint for you - write a complete prorgam yourself:

try { String sql = "Insert into Customer values (?, ?, ?, ?)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, 210); // set the other parameters using appropriate stmt.setter Method stmt.executeUpdate(); sql = "Insert into CustomerAddress (customerId, addressline1,"+ "addressline2, addressline3) values (?, ?, ?, ?)"; PreparedStatement addressStmt = con.prepareStatement(sql); stmt.setInt(1, 210); stmt.setString(2, "Lokhandwala"); stmt.setString(3, "Andheri W"); stmt.setString(3, "Suburban Mumbai"); addressStmt.executeUpdate(); // set the parameter values for the second address addressStmt.executeUpdate();

/* set the parameter values for the second address this time, deliberate set the value for addressLine 1 as null */ addressStmt.executeUpdate(); } catch (SQLException ex) { System.out.println("The error occurred [Rolling Back]: " + ex.getMessage()); con.rollback(); } try { file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (143 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

con.commit(); } catch (SQLException ex) { }

Stored Procedures What is a Stored Procedure ?











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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (144 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Create a procedure which returns a result set returning list of all Customers



Execute by creating a Callable Statement and then executing as follows:

CallableStatement cs = con.prepareCall("{call SHOW_CUSTOMERS}"); ResultSet rs = cs.executeQuery();

Assignment(s) 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (145 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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.

JDBC Assignment(s) (Contd.)



Create program called DeleteEmployee as same as SearchEmployee written earlier, but instead of retrieving, delete the employee.

JSP & Servlets Chapter: 1 - JSP Basics What is a JSP Page ? The JSP

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (146 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





A JSP page is a text-based document 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



It is the JSP elements that make up the dynamic content



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. Your First 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.)

Creating Static & Dynamic Content file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (147 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Creating Static Content







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:

A registry of content type names is kept by the IANA at : ftp://ftp.isi.edu/in-notes/iana/assignments/media-types Adding Dynamic Content Via Expressions



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: Hello! The time is now



Notice that each time you reload the page in the browser, it comes up with the current time.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (148 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan ●



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









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 syntax for the jsp:include element is as follows:

Transferring Control to Another Web Component (jsp:forward)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (149 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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:

Life Cycle of JSP Page The Life Cycle of JSP

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (150 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









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

Translation and Compilation





During the translation phase, template data is transformed into code that will emit the data into the stream that returns data to the client. JSP elements are treated as follows: ❍ Directives are used to control how the Web container translates and executes the JSP page ❍ Scripting elements are inserted into the JSP page's servlet class. ❍ Elements of the form are converted into method calls to JavaBeans components or invocations of the Java Servlet API

Translation And Compilation Errors

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (151 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









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

JSP Instance Life - Cycle



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 file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (152 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











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 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. Hello! The time is now

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. Hello! The time is now

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (153 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Mixing Scriplets & 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. Here is the JSP fragment to do it: Number



The important things to notice are how the %> and 0, then the framework represents 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. The ActionError object constructor takes min of 1 and max of 5 parameters. 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 WEBINF/classes folder Make the following enteries in the ApplicationResources.properties file

error.customer.name.required = Name Cannot Be Blank error.customer.id.required = Code Cannot Be Left Blank error.global.message={0}> file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (196 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

The Action Error (Contd.)







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:

Displaying the Error Messages

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (197 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (198 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

EJB 2.0 Chapter: 1 - Enterprise Beans What is an Enterprise Bean What is an Enterprise Bean ?









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

Benefits of Enterprise Bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (199 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











Enterprise beans simplify the development of large, distributed applications Because the EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems 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

Benefits of Enterprise Bean (Contd.)



The clients are thinner, a benefit that is particularly important for clients that run on small devices.



These applications can run on any compliant J2EE server

When to Use Enterprise Bean ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (200 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





Consider using Enterprise beans if your application has any one of the following requuirements: The application must be scalable: ❍ To accommodate a growing number of users, you may need to distribute an application's components across multiple machines. ❍ Not only can the enterprise beans of an application run on different machines, but their location will remain transparent to the clients.



Transactions are required to ensure data integrity



The application will have a variety of clients



The application will have a variety of clients. ❍ With just a few lines of code, remote clients can easily locate enterprise beans. ❍ These clients can be thin, various, and numerous

Types of Enterprise Beans



Session: Performs a task for the client



Entity: Represents a business entity object that exists in persistent storage



Message-Driven: Acts as listener for Java Message Service API, processing messages asynchronously

What is a Session Bean (SLSB & SFSB) What is a Session Bean ? file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (201 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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.

State Management Modes



Stateful Session Beans



Stateless Session Beans

Stateful Session Beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (202 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



The state of an object consists of the values of its instance variables.



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



The state is retained for the duration of the client-bean session



If the client removes the bean or terminates, the session ends and the state disappears

Stateless Session Beans











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 When the method is finished, the state is no longer retained Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client The benefits of using Stateless Session Beans are : ❍ Fewer Stateless session beans can support multiple clients ❍ They can offer better scalability for applications that require large numbers of clients ❍ 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (203 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Use Stateful Session Beans When...



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

Use Stateless Session Beans When...







The bean’s state has no data for a specific client 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

What is an Entity Bean What is an Entity Bean ?

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (204 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



An entity bean represents a business object in a persistent storage mechanism



Some examples of business objects are customers, orders, and products



In the J2EE SDK, the persistent storage mechanism is a relational database



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

What makes Entity Beans different from Session Beans ?



Entity beans differ from session beans in several ways as given below:



Entity beans are persistent



Have primary keys



May participate in relationships with other entity beans



Each one of these point is discussed on following slides

Persistence in Entity Beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (205 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











Because the state of an entity bean is saved in a storage mechanism, it is persistent. Persistence means that the entity bean's state exists beyond the lifetime of the application or the J2EE server process There are two types of persistence for entity beans: ❍ bean-managed and ❍ container-managed 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

Primary Key in Entity Beans



Each entity bean has a unique object identifier



A customer entity bean, for example, might be identified by a customer number



The unique identifier, or primary key, enables the client to locate a particular entity bean

Relationships in Entity Beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (206 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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.

Container Managed Relationships is the excellent way of automating the relationships among business objects in the your business object model. Container Managed Persistence



The term container-managed persistence means that the EJB container handles all database access required by the entity bean



The bean's code contains no database access (SQL) calls



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 Your entity beans are more portable

When to use Entity Beans

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (207 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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

What is a Message Driven Bean Brief Introduction of JMS











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

What is a Message Driven Bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (208 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









A message-driven bean is an enterprise bean the allows J2EE applications to process messages asynchronously. It acts as a JMS message listener The messages may be sent by: ❍ Any J2EE component ❍ An application client ❍ Another enterprise bean ❍ A Web component ❍ By a JMS application ❍ System does not use J2EE technology Message Driven-beans currently process only JMS messages, but in future they may be used to process other kind of messages

Message Driven Beans (Contd.)









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 If message processing is rolled back, the message will be redelivered

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (209 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

What makes Message Driven Beans Different from Other Beans











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 A single message-driven bean can process messages from multiple clients. 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.

When to use Message Driven Beans







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 To receive messages asynchronously, use a message-driven bean

Defining Client Access With Interfaces Client Access with Interfaces

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (210 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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



These interfaces define the client's view of a bean. Any method in the implementation class that is not defined on the face of the interface will not be made available to the clients (jsp(s), servlets, midlets, swing apps)





All other aspects of the bean--method implementations, deployment descriptor settings, abstract schemas, and database access calls--are hidden from the client Well-designed interfaces simplify the development and maintenance of J2EE applications. If you were to change the method definitions in the interfaces, then you might have to modify the client code as well



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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (211 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











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 a remote client, the location of the enterprise bean is transparent 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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (212 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











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

Deciding on Remote or Local Access











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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (213 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Deciding on Remote or Local (Contd.)







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

Performance and Access









Remote calls may be slower than local calls 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 file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (214 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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

The Contents of an Enterprise Bean The Contents of Enterprise Beans











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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (215 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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

Naming Conventions of Enterprise Beans The Naming Conventions

The Case - Study The Problem Statement

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (216 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











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.

Chapter: 2 - Session Beans Creating a Stateless Session Bean Writing the implementation Bean Class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (217 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



This class is exactly the one which contains implementation of business methods - i.e. your business logic. We are developing this bean as per the case-study discussed earlier. We will develop OrderManager - Session Bean which will serve the purpose of use-case controller/manager for the "Manage Sales Order" use case in the application.









Create a new EJB module with the name SalesEJB and then create the package in it with the name: businesslogic. Now within businesslogic create a package called session. Within this package create a class with the name OrderManagerBean.java. Please note we are following the naming convention - Infact we must. Implement SessionBean interface in this class. Since, SessionBean interface is in javax.ejb package, you have to import the class from the said package. As you know, implementing the interface is implementing all the methods declared on the face of the interface: hence implement following methods:

public void ejbActivate() throws EJBException, RemoteException { } public void ejbPassivate() throws EJBException, RemoteException { } public void ejbRemove() throws EJBException, RemoteException { } public void setSessionContext(SessionContext arg0) throws EJBException, RemoteException { }

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (218 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

The methods implemented above are of hardly any use in case of Stateless Session Beans - they are useful in Stateful beans. Since the both the type of beans implements the same interface we have to write dummy implementations of the above mentioned methods. Writing Business Methods in Implementation Bean Class



Write two business methods in the OrderManagerBean.java class



public void createOrder() { System.out.println("Creating the order...."); } public void editOrder() { System.out.println("Editing the order...."); }







These business methods are the ones which serves the use case logic of Use Case - Manage Sales Order. We have deliberately not put any processing code in these methods - only to keep the example simple. We will later revisit these methods and add more code to it.

Writing ejbCreate Method file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (219 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





When the client invokes create method on the home, the EJB-Container creates the instance of the bean and executes the ejbCreate Method in the implementation bean class Hence please create ejbCreate method in the implementation bean class as follows:

public void ejbCreate() throws CreateException { // SOP - Executing ejbCreate Method. }

Creating Remote Interface





Create a new interface - OrderManager.java, in the same package in which you have created the OrderManagerBean.java. Extend this interface from EJBObject. The interface EJBObject is in javax. ejb package. Declare two methods in this interface as follows:

public void createOrder() throws RemoteException; public void editOrder() throws RemoteException;





Please note that the method name and signature is as same as the business methods declared in OrderManagerBean.java. The business methods declared here are methods that will be made available to the client of the

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (220 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

OrderManager Bean. Re-Collect that the bean class is made up of not just the implementation bean class but also the home and remote interfaces. Note that what we have written now is the Remote Interface



We have created a Remote Interface and hence (as per ejb specs), each business method must throw RemoteException which is available in java.rmi package - Please import this class in OrderManager interface.

Extra explore: Please open the j2ee.jar file (The name of the file may differ based on what application server you are using). Explore the javax.ejb pacakage - you will find all the classes and interfaces we are using for e.g. SessionBean, EJBObject, EJBHome etc. Creating Home Interface





Now create one more new interface called OrderManagerHome.java. Extend this interface from javax. ejb.EJBHome. - Needless to say that this interface must also be in the same package in which you have created the OrderManagerBean.java and OrderManager.java Declare a create method in this interface as follows:

public OrderManager create() throws CreateException, RemoteException;







Note the throws clause here: Each create method must throw a CreateException (as per ejb specs). The CreateException is in javax.ejb package. Re-Compile all the classes. Now your bean is ready to be deployed. Once again - the total number of .class files now we have is 3 1. The implementation bean class (OrderManagerBean.java) 2. The Remote Interface (OrderManager.java) 3. The Home Interface (OrderManagerHome.java)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (221 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Note that the implementation bean class does not in any way specify the names of home and remote interface. It is the deployment descriptor where the relationship/dependency among these classes are specified. Deploying the bean









Now that we have created all the necessary .class files, we can deploy the same to the application server There n number of ways in which you can deploy an ejb. First of all please note that an individual bean is never deployed. It is bundled into a module (a .jar file) and then deployed The .jar file (ejb module) consists of a. all the .class files of a bean (there can be more than one bean in one single module) and b. The deployment descriptor - a .xml file which contains the bean's description (description of one or more beans in the module) How do you create the ejb module ?. You can create ejb module either - with the help of "deploytool" utility provided by the application server you are using or with the help of "ide" you are using. IDE(s) like Pramati Studio, Sun One Studio, WebLogic WorkShop (my favourite), WebSphere Developer Studio etc. If you are using any IDE, it will help you to assemble the bean, create the deployment descriptor (xml file), generate a jar file and deploy the same to the application server configured.



Use any technique you prefer (I will help you with the IDE you are using) and deploy the bean

Accessing a Session Bean from Servlet file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (222 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Creating JSP(s)



Create index.jsp in your Web Module (Create a new web module in your application if not yet created)



Write the following code in index.jsp:

Welcome to Sales Management System Create New Order



Also create order.jsp and write the following code in

Enter Order Order Id

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (223 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan







Note that from index.jsp we are moving to order.jsp and when the user clicks on submit button, we will move to orderServlet. It is the OrderServlet from where we are going to access the Session Bean Deploy your web module and run the applcation. (You will get an error when you click on submit button on order.jsp. This is because we have not yet created the OrderServlet)

Creating the OrderServlet



Create OrderServlet.java in servlets package of your web-module and call doGet method from doPost method



Add the following code in the doGet method of the servlet:

try { Context ctx = new InitialContext(); Object obj = ctx.lookup("java:comp/env/ejb/OrderManager"); OrderManagerHome orderHome = (OrderManagerHome) PortableRemoteObject.narrow (obj, OrderManagerHome.class); OrderManager orderManager = orderHome.create(); orderManager.createOrder();

} catch (NamingException ex) { out.println("Naming Exception : " + ex.getMessage()); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (224 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

return; } catch (CreateException ex) { out.println("Create Exception : " + ex.getMessage()); return; } catch (RemoteException ex) { out.println("Remote Exception : " + ex.getMessage()); return; }





Note the following in the above given code snippet: ❍ The JNDI api is used to lookup for the Home of the enterprise bean. ❍ You need to perform some low-level operations on the Remote Home object obtained and hence PortableRemoteObject.narrow ❍ create Method is used on the Home interface to obtain the Remote Object ❍ Once the Remote Object is obtained, you can now invoke the business method on it ❍ Note the exceptions that are caught ❍ Context, InitialContext and NamingException is in javax.naming and PortableRemoteObject is in javax.rmi package The servlet is not dependent on implementation bean class i.e. OrderManagerBean. It is dependent / has a contract with the Home and Remote interfaces only. Now we can say that The client class i.e. the servlet is dependent on abstraction - the interfaces and not on implementation - the OrderManagerBean These Home and Remote classes must be made available to the Web-Module. The best way is to bundle them into a jar file and put the jar file in WEB-INF/lib folder. Use IDE feature to do this



Please do not forget to configure the url pattern : orderServlet to the servlet just created. WAIT............. Do not hurry - and run the application. We have not yet set the ejb-coded reference name for the ejb used in the above given code snippet - ctx. lookup("java:comp/env/ejb/OrderManager"). Move to next slide for more details

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (225 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Configuring EJB Coded Reference Name









There are two ways in which you can lookup for the enterprise bean. 1. Directly through its jndi name 2. Through Coded Reference Name There is nothing wrong in directly using the jndi name to lookup. But then if the jndi name of the Remote Object changes, you will have to make changes in the entire web-app where ever you have used the jndi name to lookup for that particular bean On the other hand, you can configure a ejb-coded name of your choice in your web-module which will be mapped to the jndi name of the Remote Object. Now you use your ejb-coded ref name to lookup instead of jndi name of the bean. This approach offers more loose coupling. Configure the ejb-coded ref name in your web-module so that any web-component (servlet x, y or z) can lookup for the Remote Object mapped to the ejb-coded ref name. You can do this with the help of IDE you are using or the deploytool provided by your app server. What ever is the technique - please note that the configuration finally goes in web.xml file



NOW that you have done all that was supposed to be done, Re-Compile, Re-Deploy and run your application. Note the SOP results on app server console which you had coded in createOrder business method of the OrderManagerBean.java

Local Access to Session Bean Local Home and Local Object

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (226 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











In the previous example we have created two interfaces - OrderManagerHome - the home interface (Home for remote access) and OrderManager - the remote interface again - for remote access Keeping the implementation bean class as it is, we can create LocalOrderManagerHome - the Local Home Interface and LocalOrderManager - the Local Object. LocalOrderManagerHome will be extended from EJBLocalHome and LocalOrderManager will be extended from EJbLocalObject. In such a case you will be able to access OrderManager bean locally i.e. from any component which is deployed in the same EAR. Any J2EE component running on remote machine (remote process) will not be able to access the bean. This will improve the performance but will no longer make this object a distributed object However, please note that a particular ejb can have both : Local and Remote interfaces. In such a case there will be 4 interfaces declared in total.

The Difference









The business methods declared in the local interface will not throw RemoteException Also in the servlet when you lookup for the local object, you will not have to use PortableRemoteObject.narrow after lookinup the bean - simply because it is not a Remote Object. While setting the ejb coded ref name, you will specify that the interfaces of the bean are local and not remote. The performance will be very good but then as explained earlier, any j2ee component out of the ear in which the ejb with local access is created will not be able to access the ejb

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (227 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Creating a Stateful Session Bean Creating implementation bean class







Re-Collect from the Case-Study that there was a use case called: Record Autmobiles, where customer (stockists of PAE) can record the Automobiles - the spare parts of which they deal in. The user must be able to enter the automobile name for e.g. Honda, Hyundai, Tata etc. on a jsp. After he finally confirms his entry the system must save all his selection/entries in the database. Let us start developing this use case by first developing the SFSB called ProductLineManager Create a new class called ProductLineManagerBean.java in the same EJB Module in which we had created the SLSB OrderManagerBean.java.The package must again be businesslogic.session i.e. session package within businesslogic. Implement SessionBean in this class and thereby also implement all the methods of the SessionBean interface - exactly as same as we had done in case of OrderManagerBean.java. Do not forget implement ejbCreate method as follows:

public void ejbCreate() throws CreateException { }





This time create one instance variable in the ProductLineManagerBean.java as Collection productLine = new ArrayList(). Import java.util.* in this class. It is this instance variable in which we will maintain all the Automobile-names that the user selects/enters before saving it to the database Add three business methods in the ProductLineManagerBean.java as follows:

public void addAutomobileName(String name) { productLine.add(name); } public Collection getAutomobileNames() { return this.productLine; } public void saveAutomobileNames() { file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (228 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

// the business logic of adding the contents of productLine collection to the database // can be written here System.out.println("Writing Names to the database..........."); }

Note that we are not coding how to save the data to the database through saveAutoMobileNames business method. The objective here is to understand how the SFSB works and not how to interact with the database. Creating Remote Interface





Create a new interface - ProductLineManager.java, in the same package in which you have created the ProductLineManagerBean.java. Extend this interface from EJBObject. The interface EJBObject is in javax. ejb package. Declare three methods in this interface as follows:

public void addAutomobileName(String name) throws RemoteException; public Collection getAutomobileNames() throws RemoteException; public void saveAutomobileNames() throws RemoteException;





Please note that the method name and signature is as same as the business methods declared in ProductLineManagerBean.java The business methods declared here are methods that will be made available to the client of the ProductLineManager Bean. Re-Collect that the bean class is made up of not just the implementation bean class but also the home and remote interfaces. Note that what we have written now is the Remote Interface

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (229 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan ●

We have created a Remote Interface and hence (as per ejb specs), each business method must throw RemoteException which is available in java.rmi package - Please import this class in OrderManager interface

Creating Home Interface





Now create one more new interface called ProductLineManagerHome.java. Extend this interface from javax.ejb.EJBHome. - Needless to say that this interface must also be in the same package in which you have created the ProductLineManagerBean.java and ProductLineManager.java Declare a create method in this interface as follows: public ProductLineManager create() throws CreateException;







Note the throws clause here: Each create method must throw a CreateException (as per ejb specs). The CreateException is in javax.ejb package. Re-Compile all the classes Now your bean is ready to be deployed. The total number of .class files now we have is 3 1. The implementation bean class (ProductLineManagerBean.java) 2. The Remote Interface (ProductLineManager.java) 3. The Home Interface (ProductLineManagerHome.java)

Deploying the Bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (230 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









Now that we have created all the necessary .class files, we can deploy the same to the application server There n number of ways in which you can deploy an ejb. First of all please note that an individual bean is never deployed. It is bundled into a module (a .jar file) and then deployed The .jar file (ejb module) consists of a. all the .class files of a bean (there can be more than one bean in one single module) and b. The deployment descriptor - a .xml file which contains the bean's description (description of one or more beans in the module) How do you create the ejb module ?. You can create ejb module either - with the help of "deploytool" utility provided by the application server you are using or with the help of "ide" you are using. IDE(s) like Pramati Studio, Sun One Studio, WebLogic WorkShop (my favourite), WebSphere Developer Studio etc. If you are using any IDE, it will help you to assemble the bean, create the deployment descriptor (xml file), generate a jar file and deploy the same to the application server configured.



We did not anywhere in our code specifiy that the bean is stateful. Then how does the container understand that it is a stateful bean ? - At the time of deployment. When you deploy the bean, you have to specify in the deployment descriptor (ejb-jar.xml) that the bean is Stateful.

Accessing Stateful Session Bean Creating the JSP(s)

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (231 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





Create a jsp called index.jsp (Do not recreate if you already have one in your app.). Add an anchor on it as follows: Record Product Line Create one more jsp called productline.jsp and add the following code:

Add Automobile Names which constitutes your Product Line The List you have added includes Save







Note the scriptlet written above. We will discuss the same later. When the user clicks on Record Product Line anchor in index.jsp the system presents productline.jsp to the user where he can enter the Automobile name and click on add. When the user clicks on add, on productline.jsp, the system executes a servlet "ProductLineServlet" on the server, the servlet will access the SFSB - ProductLineManager add the name of the product to it, return the control back to productline.jsp - so that user can continue adding more Automobile names.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (232 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Creating ProductLineServlet



Create ProductLineServlet.java in servlets package of your web-module and call doGet method from doPost method



Add the following code in doGet method of the servlet:

ProductLineManager productLineManager = null; String automobileName = request.getParameter("automobileName"); HttpSession session = request.getSession(); Object objectInHttpSession = session.getAttribute("productLineManager"); if (objectInHttpSession == null) { try { Context ctx = new InitialContext(); Object obj = ctx.lookup("java:comp/env/ejb/ProductLineManager"); ProductLineManagerHome productLineManagerHome = (ProductLineManagerHome) PortableRemoteObject.narrow(obj, ProductLineManagerHome. class); productLineManager = productLineManagerHome.create(); session.setAttribute("productLineManager", productLineManager); } catch (NamingException ex) { out.println("Naming Exception : " + ex.getMessage()); } catch (CreateException ex) { out.println("Create Exception : " + ex.getMessage()); } } else { productLineManager = (ProductLineManager) objectInHttpSession; } try { productLineManager.addAutomobileName(automobileName); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (233 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Collection allNames = productLineManager.getAutomobileNames(); request.setAttribute("automobileNames", allNames); RequestDispatcher dispatcher = request.getRequestDispatcher("productline. jsp"); dispatcher.forward(request, response); } catch (RemoteException ex) { out.println("Remote Exception : " + ex.getMessage()); return; }





Note the following in the above given code snippet: ❍ The JNDI api is used to lookup for the Home of the enterprise bean. ❍ You need to perform some low-level operations on the Remote Home object obtained and hence PortableRemoteObject. narrow ❍ create Method is used on the Home interface to obtain the Remote Object ❍ Once the Remote Object is obtained, you can now invoke the business method on it ❍ The exceptions : Context, InitialContext and NamingException are in javax.naming and PortableRemoteObject is in javax.rmi package The servlet is not dependent on implementation bean class i.e. ProductLineManagerBean.java. It is dependent / has a contract with the Home and Remote interfaces only. Now we can say that The client class i.e. the servlet is dependent on abstraction the interfaces and not on implementation - the ProductLineManagerBean These Home and Remote classes must be made available to the Web-Module. The best way is to bundle them into a jar file and put the jar file in WEB-INF/lib folder. Use IDE feature to do this



Please do not forget to configure the url pattern : productLineServlet to the servlet just created. We have not yet set the ejbcoded reference name for the ejb used in the above given code snippet - ctx.lookup("java:comp/env/ejb/ProductLineManager"). Move to next slide for more details

Configuring EJB Coded Reference Name file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (234 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









There are two ways in which you can lookup for the enterprise bean. 1. Directly through its jndi name 2. Through Coded Reference Name There is nothing wrong in directly using the jndi name to lookup. But then if the jndi name of the Remote Object changes, you will have to make changes in the entire web-app where ever you have used the jndi name to lookup for that particular bean On the other hand, you can configure a ejb-coded name of your choice in your web-module which will be mapped to the jndi name of the Remote Object. Now you use your ejb-coded ref name to lookup instead of jndi name of the bean. This approach offers more loose coupling Configure the ejb-coded ref name in your web-module so that any web-component (servlet x, y or z) can lookup for the Remote Object mapped to the ejb-coded ref name. You can do this with the help of IDE you are using or the deploytool provided by your app server. What ever is the technique - please note that the configuration finally goes in web.xml file



NOW that you have done all that was supposed to be done, Re-Compile, Re-Deploy and run your application. Note the following: 1. When the user clicks on Add button after entering the name, the ProductLineServlet gets executed. 2. The ProductLineServlet uses the bean (from http session or creates a new one) and adds the name to it 3. Then all the names are taken from the bean (that were added in earlier requests) and put in the request object using getAutomobileNames() method 4. The control is then forwarded to productline.jsp 5. The productline.jsp reads the collection from the request (now see the scriptlet written in productline.jsp) and renders the names using out.println

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (235 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Chapter: 3 - Developing Entity Beans (BMP & CMP) Introduction to Entity Beans Entity Beans - Heart of Business Apps



Data is the heart of most business applications



In J2EE applications, entity beans represent the business objects stored in a database



For entity beans with bean-managed persistence, you must write code for the database access calls





Writing this code is additional responsibility, but you will have more control over how the entity bean access a database We will develop a BMP for Order table. We have Manage Sales Order use case in which the details the Sales Order Details are entered by the user. The OrderServlet then makes a createOrder call to the Session Bean - OrderManager. We will now develop a BMP - Order which we will access locally from OrderManage session bean.

Order Entity Bean

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (236 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan











We will discuss the coding technique for entity beans with bean-managed persistence taking Order Bean from our case-study The Order Bean represents an Order received recorded by the Sales Office / SalesMan which is received from the customer The state of OrderEJB is stored in the Order table in the database The structure of the table in the database is as follows: ❍ id - varchar (3) – this is the primary key ❍ customerid– varchar(5) ❍ productid - varchar (5) ❍ quantity - number (5) ❍ rate - number(5)> The OrderEJB requires following class files: 1. The OrderBean.java - implementation bean class 2. LocalOrder.java - local interface 3. LocalOrderHome.java - local home

Writing the Implementation Bean Class The Entity Bean Class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (237 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan









The OrderEntityBean class must meet the following requirements like any other entity bean class: ❍ Implements EntityBean interface ❍ Zero or more ejbCreate and ejbPostCreate methods ❍ Finder methods ❍ Business methods ❍ Home methods In addition, an entity bean class with bean-managed persistence has following requirements: ❍ The class is defined as public ❍ The class cannot be defined as abstract or final ❍ It contains an empty constructor ❍ It does not implement the finalize method The EntityBean interface extends the EnterpriseBean interface, which extends the Serializable interface The EntityBean interface declares number of methods, such as ejbActivate and ejbLoad, which you must implement in your entity bean class

The OrderBean Entity Class

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (238 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan







Please create a new ejb module and create the following package structure: com..sales.model.entity. Lets create implementation bean class which will adhere to ejb specs. Note the following in the implementation bean class written below: ❍ It implements EntityBean interface and hence all the methods of that interface. ❍ The ejbLoad and ejbStore methods. (We will write code in these methods later). ❍ The persistent fields declared like id, orderDate, customerId etc. The implementation bean class must be written as follows:

import javax.ejb.*; public class OrderBean implements EntityBean { EntityContext entityContext; java.lang.Integer id; java.util.Date orderDate; java.lang.Integer customerId; java.util.Date validityDate; public java.lang.Integer ejbCreate(java.lang.Integer id, java.util.Date orderDate, java.lang.Integer customerId, java.util.Date validityDate) throws CreateException { setId(id); setOrderDate(orderDate); setCustomerId(customerId); setValidityDate(validityDate); return null; } public void ejbPostCreate(java.lang.Integer id, java.util.Date orderDate, java.lang. Integer customerId, java.util.Date validityDate) throws CreateException { /**@todo Complete this method*/ } public void ejbRemove() throws RemoveException { /**@todo Complete this method*/ } public void setId(java.lang.Integer id) { this.id = id; file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (239 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

} public void setOrderDate(java.util.Date orderDate) { this.orderDate = orderDate; } public void setCustomerId(java.lang.Integer customerId) { this.customerId = customerId; } public void setValidityDate(java.util.Date validityDate) { this.validityDate = validityDate; } public java.lang.Integer getId() { return id; } public java.util.Date getOrderDate() { return orderDate; } public java.lang.Integer getCustomerId() { return customerId; } public java.util.Date getValidityDate() { return validityDate; } public java.lang.String ejbFindByPrimaryKey(java.lang.String untitledField1) throws FinderException { /**@todo Complete this method*/ return null; } public void ejbLoad() { /**@todo Complete this method*/ } public void ejbStore() { /**@todo Complete this method*/ } public void ejbActivate() { /**@todo Complete this method*/ } public void ejbPassivate() { /**@todo Complete this method*/ } file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (240 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

public void unsetEntityContext() { this.entityContext = null; } public void setEntityContext(EntityContext entityContext) { this.entityContext = entityContext; } public java.lang.Integer ejbFindByPrimaryKey(java.lang.Integer id) throws FinderException { /**@todo Complete this method*/ return null; } }

Connection Pool









What we are developing is a bean managed persistent entity. Hence we have to implement database logic (inserting, deleting etc.). For this reason we will have obtain the connection object through which we will talk to the database. Now how do we get the connection object. Our entity bean will be deployed on the application server. The application server maintains pool of connection objects. We can obtain one of the connection objects from the pool, make database calls using this connection object and leave it back in the pool. If the connection object is to be obtained from the pool, we wil need to create a connection pool in the database. Use Admin-Console of Weblogic / Pramati Application Server / make entries in the apprpriate xml file of JBoss (Refer to your application server documentation to know how to create a connection pool) to create a connection pool. The Connection Pool creates connection objects of type: javax.sql.DataSource and maintains the same. Please note this is an interface. The specific driver that you will use in order to create Connection Pool has a class which implements this interface.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (241 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan ●

In order to obtain one of the connection objects from the pool (which will be of type javax.sql. DataSource), we will have to create a JNDI DataSource which will be mapped to the connection pool. Please use admin console of your Application Server to create the DataSource. Once created, you can lookup for this datasource from your bmp using JNDI to get the connection object

Getting Connection Object in Bean





Please note that there is a method called setEntityContext in your bean which is called by the container when the bean is first created. This is the ideal place to lookup the datasource and keep it in instance variable. Lets write a private method called initializeDataSource and call it from setEntityContext. Create a variable in the bean as follows:

private EntityContext entityContext;



Now create a private initializeDataSoruce method as follows:

private DataSource initializeDataSource() Context ctx = new InitialContext();

throws NamingException {

ds = (DataSource) ctx.lookup("jdbc/TrainingDB"); return ds; }



Now write the following in setEntityContext method

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (242 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

this.entityContext = entityContext; try { ds = this.initializeDataSource(); } catch (NamingException ex) { throw new EJBException(ex.getMessage()); }

Writing the ejbCreate Method







The bean that we are developing is a BMP entity bean. This means that we need to implement the database logic not the container. When you invoke create bean from the client class, it is the ejbCreate that gets executed. The ejbCreate method (as per ejb specs) is expected to insert a row in the table. Note the arguments passed as parameters to ejbCreate/create method. Instead of writing all database logic in ejbCreatre we will simply write a private method - insertRow() which we will call from ejbCreate method. Write the insertRow method as follows:

private void insertRow(Integer id, Date orderDate, Integer customerId, Date validityDate) throws SQLException { Connection con = ds.getConnection(); String sql = "Insert into SalesOrder (id, orderDate, customerId, validityDate) values ( ?, ?, ?, ?)"; PreparedStatement stmt = con.prepareStatement(sql); stmt.setInt(1, id.intValue()); stmt.setDate(2, new java.sql.Date(orderDate.getTime())); stmt.setInt(3, customerId.intValue()); stmt.setDate(4, new java.sql.Date(validityDate.getTime())); stmt.execute(); file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (243 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

} Please note that we have obtained connection object from connection pool through a datasource - ds which was initialized from setEntityContext method. ●

Let us call insertRow from ejbCreate as follows:

try { insertRow(id, orderDate, customerId, validityDate); } catch (SQLException ex) { throw new CreateException(ex.getMessage()); } setId(id); setOrderDate(orderDate); setCustomerId(customerId); setValidityDate(validityDate); return id;



Note that we have returned the value of id if row was successfully created (also synchronized the intsance variables with the values that were passed as parameters) else we throw CreateException

Writing Home & Local Interfaces Writing Local & Home Interfaces

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (244 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





Please note that we are writing code for entity bean which we intend to access from session bean locally. As per our design, we will never invoke a method on this entity bean from out of the container. Considering this, we need to create a local interface called Order which will extend from EJBLocalObject. Write the interface as follows:

import javax.ejb.*; import java.util.*; public interface Order extends javax.ejb.EJBLocalObject { public Integer getId(); public void setOrderDate(Date orderDate); public Date getOrderDate(); public void setCustomerId(Integer customerId); public Integer getCustomerId(); public void setValidityDate(Date validityDate); public Date getValidityDate(); }



Now let is write a local home interface called OrderHome which will be extend EJBLocalHome. Write the interface as follows:

import javax.ejb.*; import java.util.*; public interface OrderHome extends javax.ejb.EJBLocalHome { public Order create(Integer id, Date orderDate, Integer customerId, Date validityDate) throws CreateException; public Order findByPrimaryKey(Integer id) throws FinderException; }



Now your ejb is ready to be deployed. Atleast create will work We will then later write code for find, remove

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (245 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

and update.

Accessing Entity from Session Writing Code in Session Bean





Please reuse the OrderManager that we have already written. You have a method called createOrder in the Session Bean. Please change the signature of the bean such that it accepts 4 parameters viz. Integer id, Date orderDate, Integer customerId, Date validityDate. Here is the code that you need to write in Entity Bean:

OrderHome home = null; Order order = null; try { Context ctx = new InitialContext(); home = (OrderHome) ctx.lookup("java:comp/env/ejb/Order"); order = home.create(id, orderDate, customerId, validityDate);

} catch throw } catch throw }

(NamingException ex ){ new EJBException(ex.getMessage()); (CreateException ex) { new EJBException(ex.getMessage());

Recompile and deploy the SalesEJB module ●

We have already written code in the servlet which calls createOrder method on the session bean. Only change the signature in the servlet to call createOrder passing all the four parameters expected by the method. Hard code the values for the time-being and then later you can accept values from the user on jsp, call servet, from servlet invoke createOrder on session bean and finally session bean invokes create in Entity Bean.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (246 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Re-Deploy the web application and see the results.

Finding Entity Bean findByPrimaryKey method







You already have a findByPrimaryKey method declared in OrderHome (note that it throws FinderException) There is a corresponding method called ejbFindByPrimaryKey in the bean which is called by when the client component invokes findByPrimaryKey. You know that the client component gets the view of Home and Local Interfaces and not of implementation bean class. Insead of directly writing database logic in ejbFindByPrimaryKey, we will write searchRow private method and call from ejbFindByPrimaryKey. The findByPrimaryKey and ejbFindByPrimaryKey accepts 1 parameter of primary key type. The only objective of ejbFindByPrimaryKey is to find whether the bean requested is available in persitent storage (database) or not.



The code in searchRow private method will be written as follows :



You need to write following in ejbFindByPrimaryKey method in the implementation bean class:

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (247 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

Chapter: 4 - Life Cycle of Enterprise Beans Life Cycle of Session Bean Life Cycle of Entity Bean Life Cycle of Message Driven Bean

The Case Study Chapter: 1 - Sales & Distribution The Problem Statement The Problem Statement





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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (248 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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 SalesManager 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 DepotManager. 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.

How do you Manage Requirements ? How do you Model Requirements ? The Use Case Model

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (249 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Identify the Actors in the system



Identify Use Cases for each Actor



Create a Use Case Diagram



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 Use Cases







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.

How do you Model Logical View ? Perform Architectural Analysis

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (250 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



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

Perform Use Case Analysis







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.

Refine the Architecture

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (251 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



Identify packages in Application and Business Services layers. Identify subsystems.



Organize the classes within appropriate packages



Identify the dependencies among these packages. Also describe Architectural Mechanisms (Data Transfer Object Mechanism, MVC Mechanism)



Design Database based on entity classes identified so far.



Create and baseline the deployment diagram

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.

Chapter: 2 - Purchase Management The Problem Statement file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (252 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

The Problem Statement









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

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (253 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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.

How do you Manage Requirements ? How do you Model Requirements ? The Use Case Model

Describe Use Cases

How do you Model Logical View ? Perform Architectural Analysis

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (254 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan





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

Perform Use Case Analysis







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.

Refine the Architecture



Identify packages in Application and Business Services layers. Identify subsystems.



Organize the classes within appropriate packages



Identify the dependencies among these packages. Also describe Architectural Mechanisms (Data Transfer Object Mechanism, MVC Mechanism)



Design Database based on entity classes identified so far.



Create and baseline the deployment diagram

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (255 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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.

Chapter: 3 - The Course Registration System The Problem Statement Problem Statement

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (256 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan



The 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 file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (257 of 258)12/6/2010 2:00:24 AM

Amit Kr. Balyan

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.

file:///D|/Projects/RBI/Development/eclipse/workspaceSpring/CoreJava.htm (258 of 258)12/6/2010 2:00:24 AM

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF