by admin ~ October 14, 2008
Following is the example from the chapter “Session Beans” from the book “Enterprise JavaBeans 3.0″ by Bill Bruke & Richard Monson-Haefel. This example I have tried it out on JBoss AS 5.0.0.CR1. I have used Postgresql as the database. And I have used eclipse WTP as IDE.
Example 4: Stateful Session Bean
This is a crude command-line-driven reservation system which uses a stateful session bean. Through this system one can book a cruise for a customer and pay for it with their credit card.
Client: TravelAgentShell.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
| package com.titan.clients;
import com.titan.domain.*;
import com.titan.travelagent.*;
import com.titan.processpayment.*;
import com.titan.access.DataAccess;
import javax.naming.*;
import java.util.*;
import java.text.DateFormat;
import java.text.ParseException;
public class TravelAgentShell {
public static void main(String[] args) throws Exception {
System.out.println();
System.out.println("********************");
System.out.println(" Titan Cruises");
System.out.println("********************");
System.out.println();
TravelAgentShell shell = new TravelAgentShell();
shell.shell();
}
private TravelAgentRemote agent;
private DataAccess access;
private TravelAgentRemote getAgent() {
try {
if (agent == null)
agent = (TravelAgentRemote) getInitialContext().lookup(
"TitanCruises/TravelAgentBean/remote");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return agent;
}
public void shell() throws Exception {
access = (DataAccess) getInitialContext().lookup(
"TitanCruises/DataAccessBean/remote");
access.initializeDB();
try {
access.makePaymentDbTable();
} catch (Exception ignored) {
}
while (true) {
System.out.println();
System.out.print("> ");
String command = "";
char read = '\0';
while (read != '\r' && read != '\n') {
read = (char) System.in.read();
command = command + read;
}
// clear out newlines from system input
int available = System.in.available();
for (int i = 0; i < available; i++)
System.in.read();
command = command.trim();
if (command.equals("")) {
continue;
}
processCommand(command);
}
}
public void processCommand(String command) {
if (command.startsWith("help")) {
help();
} else if (command.startsWith("cruises")) {
cruises();
} else if (command.startsWith("cabins")) {
cabins(command);
} else if (command.startsWith("cruise")) {
cruise(command);
} else if (command.startsWith("cabin")) {
cabin(command);
} else if (command.startsWith("book")) {
book(command);
} else if (command.startsWith("customer")) {
customer(command);
} else {
System.out.println("UNKNOWN COMMAND!");
}
}
public void cruises() {
System.out.println();
List list = access.getCruises();
for (Object obj : list) {
Cruise cruise = (Cruise) obj;
System.out.println(cruise.getId() + " " + cruise.getName());
}
}
public void cabins(String command) {
StringTokenizer tokens = new StringTokenizer(command);
tokens.nextToken();
int cruiseId = Integer.parseInt(tokens.nextToken().trim());
System.out.println();
List list = access.getCabins(cruiseId);
for (Object obj : list) {
Cabin cabin = (Cabin) obj;
System.out.println(cabin.getId() + " " + cabin.getName());
}
System.out.println();
}
public void customer(String command) {
StringTokenizer tokens = new StringTokenizer(command);
tokens.nextToken();
String first = tokens.nextToken().trim();
String last = tokens.nextToken().trim();
getAgent().findOrCreateCustomer(first, last);
System.out.println("set customer: " + first + " " + last);
}
public void cruise(String command) {
StringTokenizer tokens = new StringTokenizer(command);
tokens.nextToken();
String id = tokens.nextToken().trim();
int cruiseId = Integer.parseInt(id);
getAgent().setCruiseID(cruiseId);
System.out.println("set cruise: " + id);
}
public void cabin(String command) {
StringTokenizer tokens = new StringTokenizer(command);
tokens.nextToken();
String id = tokens.nextToken().trim();
int cabinId = Integer.parseInt(id);
getAgent().setCabinID(cabinId);
System.out.println("set cabin");
}
public void book(String command) {
StringTokenizer tokens = new StringTokenizer(command);
tokens.nextToken();
String number = tokens.nextToken().trim();
String exp = tokens.nextToken().trim();
String dollars = tokens.nextToken().trim();
Date expDate = null;
try {
expDate = DateFormat.getDateInstance(DateFormat.SHORT).parse(exp);
} catch (ParseException ex) {
System.out
.println("Illegal date format for expiration date! Format is MM/DD/YY");
return;
}
if (expDate.before(new java.util.Date())) {
System.out.println("Credit Card expired: " + expDate.toString()
+ " today: " + (new java.util.Date()).toString());
return;
}
double amount = Double.parseDouble(dollars);
String type = "";
// bet you didn't know that first digit determines type?
if (number.startsWith("5"))
type = CreditCardDO.MASTER_CARD;
else if (number.startsWith("4"))
type = CreditCardDO.VISA;
else if (number.startsWith("3"))
type = CreditCardDO.AMERICAN_EXPRESS;
else
type = "UNKNOWN";
CreditCardDO card = new CreditCardDO(number, expDate, type);
try {
TicketDO ticket = getAgent().bookPassage(card, amount);
System.out.println(ticket.toString());
System.out.println();
} catch (IncompleteConversationalState ex) {
System.out
.println("You have not set either customer, cruise, or cabin yet.");
}
// agent was removed
agent = null;
}
public void help() {
System.out.println();
System.out.println("Titan Cruises Commands");
System.out.println();
System.out.println("cruises - list all cruises");
System.out.println("cabins {cruiseId} - list all cabins");
System.out
.println("customer {first} {last} - find or create a customer");
System.out.println("cabin {id} - set cabin");
System.out.println("cruise {id} - set cruise");
System.out.println("book {credit, MM/DD/YY, amount} - book a cruise");
}
static public Context getInitialContext() throws Exception {
return new InitialContext();
}
} |
jndi.properties
1
2
3
| java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=202.141.151.148:1099 |
DataAccess.java
1
2
3
4
5
6
7
8
9
10
11
12
13
| package com.titan.access;
import javax.ejb.Remote;
import java.util.List;
@Remote
public interface DataAccess {
List getCruises();
List getCabins(int cruiseId);
void initializeDB();
public void makePaymentDbTable();
public void dropPaymentDbTable();
} |
DataAccessBean.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
| package com.titan.access;
import java.sql.*;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.*;
import javax.sql.DataSource;
import javax.ejb.EJBException;
import com.titan.domain.*;
@Stateless
public class DataAccessBean implements DataAccess {
@PersistenceContext(unitName = "titan")
private EntityManager manager;
@Resource(mappedName = "java:/TitanDB")
DataSource dataSource;
public List getCruises() {
return manager.createQuery("FROM Cruise").getResultList();
}
public List getCabins(int cruiseId) {
Ship ship = (Ship) manager.createQuery(
"SELECT cruise.ship FROM Cruise cruise WHERE cruise.id = "
+ cruiseId).getSingleResult();
return manager.createQuery("FROM Cabin c WHERE c.ship = :ship")
.setParameter("ship", ship).getResultList();
}
public void initializeDB() {
List list = manager.createQuery("FROM Ship ship").getResultList();
if (list.size() > 0) {
return;
}
Ship queenMary = new Ship("Queen Mary", 40000.0);
manager.persist(queenMary);
Ship titanic = new Ship("Titanic", 100000.0);
manager.persist(titanic);
// Create cabins
Cabin cabin1 = new Cabin();
cabin1.setDeckLevel(1);
cabin1.setShip(queenMary);
cabin1.setBedCount(1);
cabin1.setName("Queen Cabin 1");
manager.persist(cabin1);
Cabin cabin2 = new Cabin();
cabin2.setDeckLevel(1);
cabin2.setShip(queenMary);
cabin2.setBedCount(1);
cabin2.setName("Queen Cabin 2");
manager.persist(cabin2);
Cabin cabin3 = new Cabin();
cabin3.setDeckLevel(1);
cabin3.setShip(titanic);
cabin3.setBedCount(2);
cabin3.setName("Titanic Cabin 1");
manager.persist(cabin3);
Cabin cabin4 = new Cabin();
cabin4.setDeckLevel(1);
cabin4.setShip(titanic);
cabin4.setBedCount(2);
cabin4.setName("Titanic Cabin 2");
manager.persist(cabin4);
Cabin cabin5 = new Cabin();
cabin5.setDeckLevel(1);
cabin5.setShip(titanic);
cabin5.setBedCount(2);
cabin5.setName("Titanic Cabin 3");
manager.persist(cabin5);
// Create cruise
Cruise alaskan = new Cruise("Alaskan Cruise", queenMary);
manager.persist(alaskan);
Cruise atlantic = new Cruise("Atlantic Cruise", titanic);
manager.persist(atlantic);
}
// Create DB environmnet
//
public void makePaymentDbTable() {
PreparedStatement ps = null;
Connection con = null;
try {
con = dataSource.getConnection();
System.out.println("Creating table PAYMENT...");
ps = con.prepareStatement("CREATE TABLE PAYMENT ( "
+ "CUSTOMER_ID INT, " + "AMOUNT DECIMAL (8,2), "
+ "TYPE CHAR (10), " + "CHECK_BAR_CODE CHAR (50), "
+ "CHECK_NUMBER INTEGER, " + "CREDIT_NUMBER CHAR (20), "
+ "CREDIT_EXP_DATE DATE" + ")");
ps.execute();
System.out.println("...done!");
} catch (SQLException sql) {
throw new EJBException(sql);
} finally {
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
try {
if (con != null)
con.close();
} catch (Exception e) {
}
}
}
public void dropPaymentDbTable() {
PreparedStatement ps = null;
Connection con = null;
try {
con = dataSource.getConnection();
System.out.println("Dropping table PAYMENT...");
ps = con.prepareStatement("DROP TABLE PAYMENT");
ps.execute();
System.out.println("...done!");
} catch (SQLException sql) {
throw new EJBException(sql);
} finally {
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
try {
if (con != null)
con.close();
} catch (Exception e) {
}
}
}
} |
Address.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| package com.titan.domain;
import javax.persistence.*;
@Entity
public class Address implements java.io.Serializable
{
private int id;
private String street;
private String city;
private String state;
private String zip;
@Id @GeneratedValue
public int getId() { return id;}
public void setId(int id) { this.id = id; }
public String getStreet() { return street; }
public void setStreet(String street) { this.street = street; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
public String getZip() { return zip; }
public void setZip(String zip) { this.zip = zip; }
} |
Cabin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| package com.titan.domain;
import javax.persistence.*;
@Entity
public class Cabin implements java.io.Serializable
{
private int id;
private String name;
private int bedCount;
private int deckLevel;
private Ship ship;
@Id @GeneratedValue
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getBedCount() { return bedCount; }
public void setBedCount(int count) { this.bedCount = count; }
public int getDeckLevel() { return deckLevel; }
public void setDeckLevel(int level) { this.deckLevel = level; }
@ManyToOne
@JoinColumn(name="SHIP_ID")
public Ship getShip() { return ship; }
public void setShip(Ship ship) { this.ship = ship; }
} |
CreditCard.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| package com.titan.domain;
import javax.persistence.*;
import java.util.Date;
@Entity
public class CreditCard implements java.io.Serializable{
private int id;
private Date expirationDate;
private String number;
private String nameOnCard;
private Customer customer;
private CreditCompany creditCompany;
@Id @GeneratedValue
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Date getExpirationDate() { return expirationDate; }
public void setExpirationDate(Date date) { expirationDate = date; }
public String getNumber() { return number; }
public void setNumber(String number) { this.number = number; }
public String getNameOnCard() { return nameOnCard; }
public void setNameOnCard(String name) { nameOnCard = name; }
@OneToOne(mappedBy="creditCard")
public Customer getCustomer() { return customer; }
public void setCustomer(Customer customer) { this.customer = customer; }
@ManyToOne
public CreditCompany getCreditCompany() { return creditCompany; }
public void setCreditCompany(CreditCompany creditCompany) { this.creditCompany = creditCompany; }
} |
CreditCompany.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| package com.titan.domain;
import javax.persistence.*;
import java.util.*;
@Entity
public class CreditCompany implements java.io.Serializable{
private int id;
private String name;
private Address address;
@Id @GeneratedValue
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public |