Also apply the __toString fix to UserInfo
[cacert-mgr.git] / external / ZendFramework-1.9.5 / externals / dojo / demos / offline / editor / server / org / dojo / moxie / Documents.java
1 package org.dojo.moxie;
2
3 import java.util.*;
4 import java.sql.*;
5
6 /**
7 FIXME: We simply synchronize every method in this static class in order
8 to ensure that our JDBC Connection is thread safe. This is fine for our simple
9 uses as a demo app, but if Moxie needs to be used in an environment with lots
10 of accesses it should be rewritten to use a thread-safe JDBC connection
11 pooling library instead; JDBC Connections are not necessarily thread-safe
12 by default.
13
14 @author Brad Neuberg, bkn3@columbia.edu
15 */
16 public final class Documents{
17 private static Connection con;
18
19 // use PreparedStatements to protect against SQL Injection Attacks
20 private static PreparedStatement listSQL = null;
21 private static PreparedStatement findByFileNameSQL = null;
22 private static PreparedStatement findByIDSQL = null;
23 private static PreparedStatement newItemSQL = null;
24 private static PreparedStatement deleteItemSQL = null;
25 private static PreparedStatement updateItemSQL = null;
26
27 /**
28 Initializes our Documents object and underlying database connection.
29 */
30 public synchronized static void initialize(String jdbcURL, String userName,
31 String password, String driver)
32 throws MoxieException{
33 try {
34 // open the database
35 Class.forName(driver).newInstance();
36 con = DriverManager.getConnection(jdbcURL, userName, password);
37
38 // create the schema if necessary
39 Documents.createDb();
40 }catch(Exception e) {
41 throw new MoxieException(e);
42 }
43 }
44
45 /** Returns all available documents. */
46 public synchronized static List<Document> list() throws MoxieException{
47 try{
48 if(listSQL == null){
49 listSQL = Documents.con.prepareStatement(
50 "SELECT * FROM DOCUMENTS");
51 }
52
53 List<Document> allDocs = new ArrayList<Document>();
54 ResultSet results = listSQL.executeQuery();
55
56 while(results.next()){
57 Document doc = fromResultSet(results);
58 allDocs.add(doc);
59 }
60
61 return allDocs;
62 }catch(Exception e){
63 throw new MoxieException(e);
64 }
65 }
66
67 /**
68 Finds the given Document based on the filename. If this file name
69 does not exist than null is returned.
70 */
71 public synchronized static Document findByFileName(String fileName)
72 throws MoxieException{
73 try{
74 if(findByFileNameSQL == null){
75 findByFileNameSQL = con.prepareStatement(
76 "SELECT * FROM DOCUMENTS WHERE file_name=?");
77 }
78
79 // execute our query
80 findByFileNameSQL.setString(1, fileName);
81 ResultSet results = findByFileNameSQL.executeQuery();
82
83 // try to get the first result
84 if(results.next() == false){ // no results
85 return null;
86 }
87
88 Document doc = fromResultSet(results);
89
90 return doc;
91 }catch(Exception e){
92 throw new MoxieException(e);
93 }
94 }
95
96 /**
97 Finds the given Document based on it's ID. If no Document with this
98 ID exists than null is returned.
99 */
100 public synchronized static Document findByID(int id)
101 throws MoxieException{
102 try{
103 if(findByIDSQL == null){
104 findByIDSQL = con.prepareStatement(
105 "SELECT * FROM DOCUMENTS WHERE ID=?");
106 }
107
108 // execute our query
109 findByIDSQL.setInt(1, id);
110 ResultSet results = findByIDSQL.executeQuery();
111
112 // try to get the first result
113 if(results.next() == false){ // no results
114 return null;
115 }
116
117 Document doc = fromResultSet(results);
118
119 return doc;
120 }catch(Exception e){
121 throw new MoxieException(e);
122 }
123 }
124
125 /**
126 Creates a new document based on the given document object.
127
128 @param doc A Document object with it's values filled in; the id
129 field should be a negative number to indicate that no actual id
130 has been assigned to this document yet.
131
132 @returns Document The new document created, with it's id field filled
133 out to be an actual, assigned ID and origID filled out with the original
134 value of ID. For example, if a document is passed in with ID "-2", then
135 the document returned will be an actual ID such as "2000" and origID will
136 be "-2".
137
138 @throws MoxieException Thrown if a document with the given file name
139 already exists.
140 */
141 public synchronized static Document newItem(Document doc)
142 throws MoxieException{
143 try{
144 if(newItemSQL == null){
145 newItemSQL = con.prepareStatement(
146 "INSERT INTO DOCUMENTS (file_name, created_on, last_updated, content) "
147 + "VALUES (?, ?, ?, ?)");
148 }
149
150 // see if we exist yet
151 if(exists(doc.getFileName())){
152 throw new MoxieException("The document '" + doc.getFileName()
153 + "' already exists");
154 }
155
156 // setup our SQL values
157 newItemSQL.setString(1, doc.getFileName());
158 java.sql.Timestamp createdOnTimestamp =
159 new java.sql.Timestamp(doc.getCreatedOn());
160 java.sql.Timestamp lastUpdatedTimestamp =
161 new java.sql.Timestamp(doc.getLastUpdated());
162 newItemSQL.setTimestamp(2, createdOnTimestamp);
163 newItemSQL.setTimestamp(3, lastUpdatedTimestamp);
164 newItemSQL.setString(4, doc.getContent());
165
166 // execute our insert
167 newItemSQL.executeUpdate();
168
169 // look the Document back up to get its
170 // new ID
171 Document newDoc = findByFileName(doc.getFileName());
172 newDoc.setOrigId(doc.getId());
173
174 return newDoc;
175 }catch(Exception e){
176 throw new MoxieException(e);
177 }
178 }
179
180 public synchronized static void deleteItem(Document doc)
181 throws MoxieException{
182 Documents.deleteItem(doc.getId());
183 }
184
185 /*
186 Deletes a Document with the given ID.
187 */
188 public synchronized static void deleteItem(int id)
189 throws MoxieException{
190 try{
191 if(deleteItemSQL == null){
192 deleteItemSQL = con.prepareStatement(
193 "DELETE FROM DOCUMENTS WHERE ID = ?");
194 }
195
196 // execute our query
197 deleteItemSQL.setInt(1, id);
198 deleteItemSQL.executeUpdate();
199 }catch(Exception e){
200 throw new MoxieException(e);
201 }
202 }
203
204 /**
205 Updates the given Document with new data.
206
207 @throws MoxieException Thrown if a different document already
208 exists with the given new file name, if a new file name
209 is given.
210 */
211 public synchronized static void updateItem(Document doc)
212 throws MoxieException{
213 try{
214 if(updateItemSQL == null){
215 updateItemSQL = con.prepareStatement(
216 "UPDATE DOCUMENTS SET file_name = ?, "
217 + "created_on = ?, "
218 + "last_updated = ?, "
219 + "content = ? "
220 + "WHERE id = ?");
221 }
222
223 // see if we even exist with this ID
224 if(exists(doc.getId()) == false){
225 return;
226 }
227
228 // see if this file name is already taken,
229 // just in case it was renamed to something already
230 // existing
231 Document compareMe = findByFileName(doc.getFileName());
232 if(compareMe != null && compareMe.getFileName().equals(doc.getFileName())
233 && compareMe.getId() != null
234 && doc.getId() != null
235 && compareMe.getId().equals(doc.getId()) == false){
236 throw new MoxieException("A different document with the file name "
237 + "'" + doc.getFileName() + "' already exists");
238 }
239
240 // setup our SQL values
241 updateItemSQL.setString(1, doc.getFileName());
242 java.sql.Timestamp createdOnTimestamp =
243 new java.sql.Timestamp(doc.getCreatedOn());
244 java.sql.Timestamp lastUpdatedTimestamp =
245 new java.sql.Timestamp(doc.getLastUpdated());
246 updateItemSQL.setTimestamp(2, createdOnTimestamp);
247 updateItemSQL.setTimestamp(3, lastUpdatedTimestamp);
248 updateItemSQL.setString(4, doc.getContent());
249 updateItemSQL.setInt(5, doc.getId());
250
251 // execute our insert
252 updateItemSQL.executeUpdate();
253 }catch(Exception e){
254 throw new MoxieException(e);
255 }
256 }
257
258 public synchronized static boolean exists(String fileName)
259 throws MoxieException{
260 Document doc = findByFileName(fileName);
261 return (doc != null);
262 }
263
264 public synchronized static boolean exists(int id)
265 throws MoxieException{
266 Document doc = findByID(id);
267 return (doc != null);
268 }
269
270 private static Document fromResultSet(ResultSet results)
271 throws MoxieException{
272 try{
273 // create a Document object with our values
274 int id = results.getInt("id");
275 String fileName = results.getString("file_name");
276 String content = results.getString("content");
277
278 // convert java.sql.Date objects to java.util.Date objects
279 long createdOnTime = results.getTimestamp("created_on").getTime();
280
281 long lastUpdatedTime = results.getTimestamp("last_updated").getTime();
282
283 Document doc = new Document(id, fileName, createdOnTime, lastUpdatedTime,
284 content);
285
286 return doc;
287 }catch(Exception e){
288 throw new MoxieException(e);
289 }
290 }
291
292 private static void createDb() throws MoxieException{
293 try{
294 Statement s = con.createStatement();
295
296 // see if the DOCUMENTS table exists yet
297 DatabaseMetaData metaData = con.getMetaData();
298 ResultSet rs = metaData.getTables(null, null, "DOCUMENTS", null);
299 boolean exist = false;
300 if(rs.next()){
301 exist = true;
302 }
303
304 if(exist){
305 return;
306 }
307
308 s.execute("CREATE TABLE DOCUMENTS ("
309 + "id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, "
310 + "file_name VARCHAR(255) NOT NULL, "
311 + "created_on TIMESTAMP NOT NULL, "
312 + "last_updated TIMESTAMP NOT NULL, "
313 + "content CLOB(500K) NOT NULL, "
314 + "PRIMARY KEY(id), "
315 + "UNIQUE(file_name) "
316 + ")");
317
318 // create some fake data
319 s.execute("INSERT INTO DOCUMENTS (file_name, created_on, last_updated, content) "
320 + "VALUES ('message', CURRENT TIMESTAMP, CURRENT TIMESTAMP, 'Watson, come quickly!')");
321 s.execute("INSERT INTO DOCUMENTS (file_name, created_on, last_updated, content) "
322 + "VALUES ('message2', CURRENT TIMESTAMP, CURRENT TIMESTAMP, 'Hello World!')");
323 s.execute("INSERT INTO DOCUMENTS (file_name, created_on, last_updated, content) "
324 + "VALUES ('message3', CURRENT TIMESTAMP, CURRENT TIMESTAMP, 'Goodbye World!')");
325 s.execute("INSERT INTO DOCUMENTS (file_name, created_on, last_updated, content) "
326 + "VALUES ('message4', CURRENT TIMESTAMP, CURRENT TIMESTAMP, 'Brad Neuberg was here')");
327 }catch(Exception e){
328 throw new MoxieException(e);
329 }
330 }
331 }