01: package com.xoetrope.data;
02:
03: import com.xoetrope.data.PreparationTask;
04: import javax.swing.SwingUtilities;
05: import net.xoetrope.optional.data.sql.DataConnection;
06: import net.xoetrope.optional.data.sql.DatabaseTableModel;
07: import net.xoetrope.xui.XPage;
08: import net.xoetrope.xui.XProject;
09:
10: /**
11: * A class that is kicked off in the background when the application loads. The
12: * class prepares the database for use.
13: * <p> Copyright (c) Xoetrope Ltd., 2001-2007, This software is licensed under
14: * the GNU Public License (GPL), please see license.txt for more details. If
15: * you make commercial use of this software you must purchase a commercial
16: * license from Xoetrope.</p>
17: */
18: public class DatabasePreparationTask implements PreparationTask {
19: private boolean prepared;
20: private boolean connected;
21: private DatabaseConnector connector;
22:
23: /*
24: * Creates a new instance of DatabasePreparationTask
25: */
26: public DatabasePreparationTask() {
27: // The PL17 tables use NULLs deliberately
28: DatabaseTableModel.setAllowNull(true);
29: prepared = false;
30: connected = false;
31: }
32:
33: /**
34: * Prepare the database
35: * @param project the owner project
36: * @param listener the object to be invoked when the prepatation task is complete
37: * @param tableName the name of a small table that will be loaded as part of the database loading process.
38: */
39: public synchronized void prepare(XProject project,
40: PreparationListener listener, final String tableName) {
41: final PreparationListener listenerPage = listener;
42: final XProject currentProject = project;
43:
44: new Thread() {
45: public void run() {
46: if (!prepared) {
47: final DatabaseConnector connector = new DatabaseConnector(
48: currentProject);
49: DataConnection connection = connector
50: .getConnection("default");
51: connected = false;
52: try {
53: connection.borrowConnection().getConnection();
54: connection.returnConnection();
55: connected = true;
56:
57: // Load a data source to force the database to load
58: connection.executeQuery("SELECT * FROM "
59: + tableName);
60: connection.closeQuery();
61: } catch (Exception ex) {
62: ex.printStackTrace();
63: }
64:
65: while (!prepared) {
66: if (listenerPage.isReady()) {
67: SwingUtilities.invokeLater(new Runnable() {
68: public void run() {
69: if (connected)
70: listenerPage
71: .preparationCompleted(connector);
72: else
73: listenerPage
74: .preparationFailed("Unable to load the database");
75: }
76: });
77: prepared = true;
78: } else {
79: try {
80: Thread.currentThread().sleep(1000);
81: } catch (Exception e) {
82: }
83: }
84: }
85: }
86: }
87: }.start();
88: }
89: }
|