001: /**
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */package org.apache.geronimo.timer.jdbc;
017:
018: import com.thoughtworks.xstream.XStream;
019: import org.apache.geronimo.timer.PersistenceException;
020: import org.apache.geronimo.timer.Playback;
021: import org.apache.geronimo.timer.WorkInfo;
022: import org.apache.geronimo.timer.WorkerPersistence;
023:
024: import javax.sql.DataSource;
025: import java.sql.Connection;
026: import java.sql.PreparedStatement;
027: import java.sql.ResultSet;
028: import java.sql.SQLException;
029: import java.sql.Types;
030: import java.util.ArrayList;
031: import java.util.Collection;
032: import java.util.Date;
033:
034: /**
035: * TODO use an insert returning or stored procedure to insert.
036: *
037: * @version $Rev: 476049 $ $Date: 2006-11-16 20:35:17 -0800 (Thu, 16 Nov 2006) $
038: */
039: public class JDBCWorkerPersistence implements WorkerPersistence {
040:
041: private static final String createSequenceSQL = "create sequence timertasks_seq";
042: private static final String createTableSQLWithSequence = "create table timertasks (id long primary key, serverid varchar(256) not null, timerkey varchar(256) not null, userid varchar(4096), userinfo varchar(4096), firsttime long not null, period long, atfixedrate boolean not null)";
043: private static final String createTableSQLWithIdentity = "create table timertasks (id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), serverid varchar(256) not null, timerkey varchar(256) not null, userid varchar(4096), userinfo varchar(4096), firsttime NUMERIC(18,0) not null, period NUMERIC(18, 0), atfixedrate CHAR(1))";
044: private static final String sequenceSQL = "select timertasks_seq.nextval";
045: private static final String identitySQL = "values IDENTITY_VAL_LOCAL()";
046: private static final String insertSQLWithSequence = "insert into timertasks (id, serverid, timerkey, userid, userinfo, firsttime, period, atfixedrate) values (?, ?, ?, ?, ?, ?, ?, ?)";
047: private static final String insertSQLWithIdentity = "insert into timertasks (serverid, timerkey, userid, userinfo, firsttime, period, atfixedrate) values (?, ?, ?, ?, ?, ?, ?)";
048: private static final String deleteSQL = "delete from timertasks where id=?";
049: private static final String selectSQL = "select id, userid, userinfo, firsttime, period, atfixedrate from timertasks where serverid = ? and timerkey=?";
050: private static final String fixedRateUpdateSQL = "update timertasks set firsttime = firsttime + period where id = ?";
051: private static final String intervalUpdateSQL = "update timertasks set firsttime = ? where id = ?";
052: private static final String selectByKeySQL = "select id from timertasks where serverid = ? and timerkey = ? and (userid = ? or ? is null)";
053:
054: private final String serverUniqueId;
055: private final DataSource dataSource;
056: private boolean useSequence = false;
057:
058: protected JDBCWorkerPersistence(String serverUniqueId,
059: DataSource datasource, boolean useSequence)
060: throws SQLException {
061: this .serverUniqueId = serverUniqueId;
062: this .dataSource = datasource;
063: this .useSequence = useSequence;
064: if (this .useSequence) {
065: execSQL(createSequenceSQL);
066: execSQL(createTableSQLWithSequence);
067: } else {
068: execSQL(createTableSQLWithIdentity);
069: }
070: }
071:
072: public void save(WorkInfo workInfo) throws PersistenceException {
073: boolean threwException = false;
074: Connection c = getConnection();
075: try {
076: if (useSequence) {
077: long id;
078: PreparedStatement seqStatement = c
079: .prepareStatement(sequenceSQL);
080: try {
081: ResultSet seqRS = seqStatement.executeQuery();
082: try {
083: seqRS.next();
084: id = seqRS.getLong(1);
085: } finally {
086: seqRS.close();
087: }
088: } finally {
089: seqStatement.close();
090: }
091: workInfo.setId(id);
092: PreparedStatement insertStatement = c
093: .prepareStatement(insertSQLWithSequence);
094: try {
095: String serializedUserId = serialize(workInfo
096: .getUserId());
097: String serializedUserKey = serialize(workInfo
098: .getUserInfo());
099: insertStatement.setLong(1, id);
100: insertStatement.setString(2, serverUniqueId);
101: insertStatement.setString(3, workInfo.getKey());
102: insertStatement.setString(4, serializedUserId);
103: insertStatement.setString(5, serializedUserKey);
104: insertStatement.setLong(6, workInfo.getTime()
105: .getTime());
106: if (workInfo.getPeriod() == null) {
107: insertStatement.setNull(7, Types.NUMERIC);
108: } else {
109: insertStatement.setLong(7, workInfo.getPeriod()
110: .longValue());
111: }
112: insertStatement.setBoolean(8, workInfo
113: .getAtFixedRate());
114: int result = insertStatement.executeUpdate();
115: if (result != 1) {
116: throw new PersistenceException(
117: "Could not insert!");
118: }
119: } finally {
120: insertStatement.close();
121: }
122: } else {
123: PreparedStatement insertStatement = c
124: .prepareStatement(insertSQLWithIdentity);
125: try {
126: String serializedUserId = serialize(workInfo
127: .getUserId());
128: String serializedUserKey = serialize(workInfo
129: .getUserInfo());
130: insertStatement.setString(1, serverUniqueId);
131: insertStatement.setString(2, workInfo.getKey());
132: insertStatement.setString(3, serializedUserId);
133: insertStatement.setString(4, serializedUserKey);
134: insertStatement.setLong(5, workInfo.getTime()
135: .getTime());
136: if (workInfo.getPeriod() == null) {
137: insertStatement.setNull(6, Types.NUMERIC);
138: } else {
139: insertStatement.setLong(6, workInfo.getPeriod()
140: .longValue());
141: }
142: insertStatement.setBoolean(7, workInfo
143: .getAtFixedRate());
144: int result = insertStatement.executeUpdate();
145: if (result != 1) {
146: throw new PersistenceException(
147: "Could not insert!");
148: }
149: } finally {
150: insertStatement.close();
151: }
152: long id;
153: PreparedStatement identityStatement = c
154: .prepareStatement(identitySQL);
155: try {
156: ResultSet seqRS = identityStatement.executeQuery();
157: try {
158: seqRS.next();
159: id = seqRS.getLong(1);
160: } finally {
161: seqRS.close();
162: }
163: } finally {
164: identityStatement.close();
165: }
166: workInfo.setId(id);
167: }
168: } catch (SQLException e) {
169: threwException = true;
170: throw new PersistenceException(e);
171: } finally {
172: close(c, !threwException);
173: }
174: }
175:
176: public void cancel(long id) throws PersistenceException {
177: boolean threwException = false;
178:
179: Connection c = getConnection();
180: try {
181: PreparedStatement deleteStatement = c
182: .prepareStatement(deleteSQL);
183: try {
184: deleteStatement.setLong(1, id);
185: deleteStatement.execute();
186: } finally {
187: deleteStatement.close();
188: }
189: } catch (SQLException e) {
190: threwException = true;
191: throw new PersistenceException(e);
192: } finally {
193: close(c, !threwException);
194: }
195: }
196:
197: public void playback(String key, Playback playback)
198: throws PersistenceException {
199: boolean threwException = false;
200: Connection c = getConnection();
201: try {
202: PreparedStatement selectStatement = c
203: .prepareStatement(selectSQL);
204: selectStatement.setString(1, serverUniqueId);
205: selectStatement.setString(2, key);
206: try {
207: ResultSet taskRS = selectStatement.executeQuery();
208: try {
209: while (taskRS.next()) {
210: long id = taskRS.getLong(1);
211: String serizalizedUserId = taskRS.getString(2);
212: Object userId = deserialize(serizalizedUserId);
213: String serializedUserInfo = taskRS.getString(3);
214: Object userInfo = deserialize(serializedUserInfo);
215: long timeMillis = taskRS.getLong(4);
216: Date time = new Date(timeMillis);
217: Long period = null;
218: period = new Long(taskRS.getLong(5));
219: if (!taskRS.wasNull()) {
220: period = null;
221: }
222: boolean atFixedRate = taskRS.getBoolean(6);
223: //TODO make sure the reference to this is ok, meaning we can't use a handle to this WorkerPersistence.
224: WorkInfo workInfo = new WorkInfo(key, userId,
225: userInfo, time, period, atFixedRate);
226: workInfo.setId(id);
227: playback.schedule(workInfo);
228: }
229: } finally {
230: taskRS.close();
231: }
232: } finally {
233: selectStatement.close();
234: }
235: } catch (SQLException e) {
236: threwException = true;
237: throw new PersistenceException(e);
238: } finally {
239: close(c, !threwException);
240: }
241: }
242:
243: public void fixedRateWorkPerformed(long id)
244: throws PersistenceException {
245: boolean threwException = false;
246: Connection c = getConnection();
247: try {
248: PreparedStatement updateStatement = c
249: .prepareStatement(fixedRateUpdateSQL);
250: try {
251: updateStatement.setLong(1, id);
252: updateStatement.execute();
253: } finally {
254: updateStatement.close();
255: }
256: } catch (SQLException e) {
257: threwException = true;
258: throw new PersistenceException(e);
259: } finally {
260: close(c, !threwException);
261: }
262: }
263:
264: public void intervalWorkPerformed(long id, long period)
265: throws PersistenceException {
266: boolean threwException = false;
267: long next = System.currentTimeMillis() + period;
268: Connection c = getConnection();
269: try {
270: PreparedStatement updateStatement = c
271: .prepareStatement(intervalUpdateSQL);
272: try {
273: updateStatement.setLong(1, next);
274: updateStatement.setLong(2, id);
275: updateStatement.execute();
276: } finally {
277: updateStatement.close();
278: }
279: } catch (SQLException e) {
280: threwException = true;
281: throw new PersistenceException(e);
282: } finally {
283: close(c, !threwException);
284: }
285: }
286:
287: public Collection getIdsByKey(String key, Object userId)
288: throws PersistenceException {
289: boolean threwException = false;
290:
291: Collection ids = new ArrayList();
292: Connection c = getConnection();
293: try {
294: PreparedStatement selectStatement = c
295: .prepareStatement(selectByKeySQL);
296: selectStatement.setString(1, serverUniqueId);
297: selectStatement.setString(2, key);
298: if (userId == null) {
299: selectStatement.setNull(3, Types.VARCHAR);
300: selectStatement.setNull(4, Types.VARCHAR);
301: } else {
302: String userIdString = serialize(userId);
303: selectStatement.setString(3, userIdString);
304: selectStatement.setString(4, userIdString);
305: }
306: try {
307: ResultSet taskRS = selectStatement.executeQuery();
308: try {
309: while (taskRS.next()) {
310: long id = taskRS.getLong(1);
311: ids.add(new Long(id));
312: }
313: } finally {
314: taskRS.close();
315: }
316: } finally {
317: selectStatement.close();
318: }
319: } catch (SQLException e) {
320: threwException = true;
321: throw new PersistenceException(e);
322: } finally {
323: close(c, !threwException);
324: }
325:
326: return ids;
327: }
328:
329: private String serialize(Object task) {
330: XStream xStream = new XStream();
331: return xStream.toXML(task);
332: }
333:
334: private Object deserialize(String serializedRunnable) {
335: XStream xStream = new XStream();
336: return xStream.fromXML(serializedRunnable);
337: }
338:
339: private void execSQL(String sql) throws SQLException {
340: Connection c = dataSource.getConnection();
341: try {
342: PreparedStatement updateStatement = c.prepareStatement(sql);
343: try {
344: updateStatement.execute();
345: } catch (SQLException e) {
346: //ignore... table already exists.
347: } finally {
348: updateStatement.close();
349: }
350: } finally {
351: c.close();
352: }
353: }
354:
355: private Connection getConnection() throws PersistenceException {
356: try {
357: return dataSource.getConnection();
358: } catch (Exception e) {
359: throw new PersistenceException(e);
360: }
361: }
362:
363: private void close(Connection c, boolean reportSqlException)
364: throws PersistenceException {
365: try {
366: c.close();
367: } catch (Exception e) {
368: if (!reportSqlException) {
369: throw new PersistenceException(e);
370: }
371: }
372: }
373: }
|