/
SampleApplication.java
331 lines (298 loc) · 10.4 KB
/
SampleApplication.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.empire.jsf2.websample.web;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
import org.apache.empire.commons.StringUtils;
import org.apache.empire.db.DBCommand;
import org.apache.empire.db.DBDatabase;
import org.apache.empire.db.DBDatabaseDriver;
import org.apache.empire.db.DBRecord;
import org.apache.empire.db.DBSQLScript;
import org.apache.empire.db.exceptions.QueryFailedException;
import org.apache.empire.db.hsql.DBDatabaseDriverHSql;
import org.apache.empire.db.mysql.DBDatabaseDriverMySQL;
import org.apache.empire.db.oracle.DBDatabaseDriverOracle;
import org.apache.empire.db.sqlserver.DBDatabaseDriverMSSQL;
import org.apache.empire.jsf2.app.FacesApplication;
import org.apache.empire.jsf2.controls.InputControlManager;
import org.apache.empire.jsf2.custom.controls.FileInputControl;
import org.apache.empire.jsf2.websample.db.SampleDB;
import org.apache.empire.jsf2.websample.web.pages.SamplePages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SampleApplication extends FacesApplication {
// Logger
private static final Logger log = LoggerFactory
.getLogger(SampleApplication.class);
private static SampleApplication sampleApplication = null;
protected static final String MANAGED_BEAN_NAME = "sampleApplication";
protected static final Locale DEFAULT_LOCALE = Locale.ENGLISH;
// Non-Static
private SampleConfig config = new SampleConfig();
private SampleDB sampleDB = null;
private Connection conn = null;
public static SampleApplication get() {
return SampleApplication.sampleApplication;
}
public SampleApplication() {
// Check for single instance
if (SampleApplication.sampleApplication != null) {
throw new RuntimeException(
"Attempt to create second instance of SampleApplication. SampleApplication is a singleton!");
}
// trace
SampleApplication.log.trace("SampleApplication created");
SampleApplication.sampleApplication = this;
// register custom control types
InputControlManager.registerControl(new FileInputControl());
}
@Override
public void init(ServletContext servletContext) {
// register all controls
// InputControlManager.registerControl("myType", new
// MyTypeInputControl());
config.init(servletContext.getRealPath("WEB-INF/config.xml"));
// Get a JDBC Connection
log.info("*** getJDBCConnection() ***");
conn = getJDBCConnection(servletContext);
log.info("*** initDatabase() ***");
initDatabase();
log.info("*** initPages() ***");
initPages(servletContext);
// Set Database to Servlet Context
servletContext.setAttribute("db", sampleDB);
// Done
log.info("Application initialized ");
}
/*
* getJDBCConnection
*/
private Connection getJDBCConnection(ServletContext appContext) {
// Establish a new database connection
Connection conn = null;
String jdbcURL = config.getJdbcURL();
if (jdbcURL.indexOf("file:") > 0)
jdbcURL = StringUtils.replace(jdbcURL, "file:", "file:"
+ appContext.getRealPath("/"));
// Connect
log.info("Connecting to Database'" + jdbcURL + "' / User="
+ config.getJdbcUser());
try { // Connect to the databse
Class.forName(config.getJdbcClass()).newInstance();
conn = DriverManager.getConnection(jdbcURL, config.getJdbcUser(),
config.getJdbcPwd());
log.info("Connected successfully");
// set the AutoCommit to false this session. You must commit
// explicitly now
conn.setAutoCommit(false);
log.info("AutoCommit is " + conn.getAutoCommit());
} catch (Exception e) {
log.error("Failed to connect directly to '" + config.getJdbcURL()
+ "' / User=" + config.getJdbcUser());
log.error(e.toString());
throw new RuntimeException(e);
}
return conn;
}
private void initDatabase() {
sampleDB = new SampleDB();
// Open Database (and create if not existing)
log.info("*** open database ***");
String driverProvider = config.getDatabaseProvider();
DBDatabaseDriver driver = getDatabaseDriver(driverProvider);
Connection conn = null;
try {
conn = getConnection(sampleDB);
sampleDB.open(driver, conn);
if (!databaseExists(conn)) {
// STEP 4: Create Database
log.info("*** create Database ***");
createSampleDatabase(driver, conn);
}
} finally {
releaseConnection(sampleDB, conn, true);
}
}
/*
* getDatabaseDriver
*/
private DBDatabaseDriver getDatabaseDriver(String provider) {
if (provider.equalsIgnoreCase("mysql")) {
DBDatabaseDriverMySQL driver = new DBDatabaseDriverMySQL();
// Set Driver specific properties (if any)
driver.setDatabaseName(config.getSchemaName());
return driver;
} else if (provider.equalsIgnoreCase("oracle")) {
DBDatabaseDriverOracle driver = new DBDatabaseDriverOracle();
// Set Driver specific properties (if any)
return driver;
} else if (provider.equalsIgnoreCase("sqlserver")) {
DBDatabaseDriverMSSQL driver = new DBDatabaseDriverMSSQL();
// Set Driver specific properties (if any)
driver.setDatabaseName(config.getSchemaName());
return driver;
} else if (provider.equalsIgnoreCase("hsqldb")) {
DBDatabaseDriverHSql driver = new DBDatabaseDriverHSql();
// Set Driver specific properties (if any)
return driver;
} else { // Unknown Provider
throw new RuntimeException("Unknown Database Provider " + provider);
}
}
private void initPages(ServletContext sc) {
// register Page Beans
new SamplePages().registerPageBeans(this.getFacesImplementation());
}
public SampleDB getDatabase() {
return sampleDB;
}
private boolean databaseExists(Connection conn) {
// Check wether DB exists
DBCommand cmd = sampleDB.createCommand();
cmd.select(sampleDB.T_DEPARTMENTS.count());
try {
return (sampleDB.querySingleInt(cmd, -1, conn) >= 0);
} catch (QueryFailedException e) {
return false;
}
}
/*
* creates a DDL Script for the entire SampleDB Database then checks if the
* department table exists by running "select count(*) from DEPARTMENTS" if
* the department tables does not exist, the entire dll-script is executed
* line by line
*/
private void createSampleDatabase(DBDatabaseDriver driver, Connection conn) {
// create DLL for Database Definition
DBSQLScript script = new DBSQLScript();
sampleDB.getCreateDDLScript(driver, script);
// Show DLL Statements
System.out.println(script.toString());
// Execute Script
script.run(driver, conn, false);
sampleDB.commit(conn);
// Open again
if (!sampleDB.isOpen()) {
sampleDB.open(driver, conn);
}
// Insert Sample Departments
insertDepartmentSampleRecord(conn, "Procurement", "ITTK");
int idDevDep = insertDepartmentSampleRecord(conn, "Development", "ITTK");
int idSalDep = insertDepartmentSampleRecord(conn, "Sales", "ITTK");
// Insert Sample Employees
insertEmployeeSampleRecord(conn, "Mr.", "Eugen", "Miller", "M", idDevDep);
insertEmployeeSampleRecord(conn, "Mr.", "Max", "Mc. Callahan", "M", idDevDep);
insertEmployeeSampleRecord(conn, "Mrs.", "Anna", "Smith", "F", idSalDep);
// Commit
sampleDB.commit(conn);
}
/*
* Insert a department
*/
private int insertDepartmentSampleRecord(Connection conn,
String department_name, String businessUnit) {
// Insert a Department
DBRecord rec = new DBRecord();
rec.create(sampleDB.T_DEPARTMENTS);
rec.setValue(sampleDB.T_DEPARTMENTS.NAME, department_name);
rec.setValue(sampleDB.T_DEPARTMENTS.BUSINESS_UNIT, businessUnit);
try {
rec.update(conn);
} catch (Exception e) {
log.error(e.getLocalizedMessage());
return 0;
}
// Return Department ID
return rec.getInt(sampleDB.T_DEPARTMENTS.DEPARTMENT_ID);
}
/*
* Insert a person
*/
private int insertEmployeeSampleRecord(Connection conn, String salutation,
String firstName, String lastName, String gender, int depID) {
// Insert an Employee
DBRecord rec = new DBRecord();
rec.create(sampleDB.T_EMPLOYEES);
rec.setValue(sampleDB.T_EMPLOYEES.SALUTATION, salutation);
rec.setValue(sampleDB.T_EMPLOYEES.FIRST_NAME, firstName);
rec.setValue(sampleDB.T_EMPLOYEES.LAST_NAME, lastName);
rec.setValue(sampleDB.T_EMPLOYEES.GENDER, gender);
rec.setValue(sampleDB.T_EMPLOYEES.DEPARTMENT_ID, depID);
try {
rec.update(conn);
} catch (Exception e) {
log.error(e.getLocalizedMessage());
return 0;
}
// Return Employee ID
return rec.getInt(sampleDB.T_EMPLOYEES.EMPLOYEE_ID);
}
@Override
/**
* returns null as connection pooling is not used
*/
protected DataSource getAppDataSource(DBDatabase db) {
return null;
}
/**
* Usually returns a connection from the connection pool
* As the sample does not use connection pooling, a static connection is returned
* @return a connection for the requested db
*/
@Override
protected Connection getConnection(DBDatabase db)
{
return conn;
}
/**
* Usually releases a connection from the connection pool
* As the sample does not use connection pooling, only a commit or rollback is performed
*/
@Override
protected void releaseConnection(DBDatabase db, Connection conn, boolean commit)
{
// release connection
if (conn == null)
{
return;
}
// Commit or rollback connection depending on the exit code
if (commit)
{ // success: commit all changes
db.commit(conn);
log.debug("REQUEST {}: commited.");
}
else
{ // failure: rollback all changes
db.rollback(conn);
log.debug("REQUEST {}: rolled back.");
}
}
protected SampleConfig getSampleConfig() {
if (config == null) {
SampleApplication.log
.error("Application configuration not initialized!");
}
return config;
}
}