01 package wodbupdate;
02
03 import com.webobjects.appserver.*;
04 import com.webobjects.eoaccess.*;
05 import com.webobjects.foundation.*;
06
07
08 public class Updater {
09 protected String updatesClassNamesPrefix = Update.class.getName();
10 protected Databaseable database;
11
12 protected Updater() {
13 }
14
15 public Updater(EOModel aModel) {
16 createDatabase(aModel.connectionDictionary());
17 }
18
19 private void createDatabase(NSDictionary connectionDictionary) {
20 String urlString = (String)connectionDictionary.objectForKey("URL");
21 String userName = (String)connectionDictionary.objectForKey("username");
22 String password = (String)connectionDictionary.objectForKey("password");
23 database = new Database(urlString, userName, password);
24 }
25
26 protected boolean tryToLockDB() {
27 return database.tryToLock();
28 }
29
30 protected void unlockDB() {
31 database.unlock();
32 }
33
34 protected int currentDBVersionNumber() {
35 try {
36 return database.currentVersionNumber();
37 } catch (Throwable e) {
38 return -1;
39 }
40 }
41
42 protected void closeDB() {
43 database.close();
44 }
45
46 protected void executeUpdates() throws Exception {
47 try {
48 while (true) {
49 Update update = (Update)Class.forName(updatesClassNamesPrefix + (currentDBVersionNumber() + 1)).newInstance();
50 update.setDatabase(database);
51 update.performUpdate();
52 incrementDBVersion();
53 }
54 } catch (ClassNotFoundException e) {
55 }
56 }
57
58 protected void incrementDBVersion() {
59 database.setVersionNumber(currentDBVersionNumber() + 1);
60 }
61
62 protected void waitUntilDBUnlocked() {
63 do {
64 System.out.println("waiting while another application instance performs DB updates");
65 try {
66 Thread.sleep(5 * 1000);
67 } catch (InterruptedException e) {
68 }
69 } while (database.isLocked());
70 }
71
72 public void performUpdate() {
73 try {
74 System.out.println("WODBUpdate - ensuring DB is up-to-date");
75 if (tryToLockDB()) {
76 executeUpdates();
77 unlockDB();
78 } else
79 waitUntilDBUnlocked();
80 System.out.println("WODBUpdate - DB is now up-to-date");
81 } catch (Throwable e) {
82 e.printStackTrace();
83 WOApplication.application().terminate();
84 } finally {
85 closeDB();
86 }
87 }
88
89 }
|