KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > fr > dyade > aaa > util > DBRepository


1 /*
2  * Copyright (C) 2006 ScalAgent Distributed Technologies
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17  * USA.
18  *
19  * Initial developer(s): ScalAgent Distributed Technologies
20  * Contributor(s):
21  */

22 package fr.dyade.aaa.util;
23
24 import java.io.File JavaDoc;
25 import java.io.ByteArrayInputStream JavaDoc;
26 import java.io.ObjectInputStream JavaDoc;
27 import java.io.IOException JavaDoc;
28 import java.io.FileNotFoundException JavaDoc;
29
30 import java.util.Vector JavaDoc;
31 import java.util.Properties JavaDoc;
32
33 import java.sql.Connection JavaDoc;
34 import java.sql.DriverManager JavaDoc;
35 import java.sql.Statement JavaDoc;
36 import java.sql.PreparedStatement JavaDoc;
37 import java.sql.ResultSet JavaDoc;
38 import java.sql.SQLException JavaDoc;
39
40 final class DBRepository implements Repository {
41   String JavaDoc driver = "org.apache.derby.jdbc.EmbeddedDriver";
42   String JavaDoc connurl = "jdbc:derby:";
43 // String driver = "org.hsqldb.jdbcDriver";
44
// String connurl = "jdbc:hsqldb:file:";
45

46   File JavaDoc dir = null;
47
48   private int nbsaved = 0;
49
50   /**
51    * Returns the number of save operation to repository.
52    *
53    * @return The number of save operation to repository.
54    */

55   public int getNbSavedObjects() {
56     return nbsaved;
57   }
58
59   private int nbdeleted = 0;
60
61   /**
62    * Returns the number of delete operation on repository.
63    *
64    * @return The number of delete operation on repository.
65    */

66   public int getNbDeletedObjects() {
67     return nbdeleted;
68   }
69
70   private int baddeleted = 0;
71
72   /**
73    * Returns the number of useless delete operation on repository.
74    *
75    * @return The number of useless delete operation on repository.
76    */

77   public int getNbBadDeletedObjects() {
78     return baddeleted;
79   }
80
81   private int nbloaded = 0;
82
83   /**
84    * Returns the number of load operation from repository.
85    *
86    * @return The number of load operation from repository.
87    */

88   public int getNbLoadedObjects() {
89     return nbloaded;
90   }
91   
92   Connection JavaDoc conn = null;
93   
94   DBRepository() {}
95
96   PreparedStatement JavaDoc insertStmt = null;
97   PreparedStatement JavaDoc updateStmt = null;
98   PreparedStatement JavaDoc deleteStmt = null;
99
100   /**
101    * Initializes the repository.
102    * Opens the connection, evntually creates the database and tables.
103    */

104   public void init(File JavaDoc dir) throws IOException JavaDoc {
105     this.dir = dir;
106
107     try {
108       Class.forName(driver).newInstance();
109 // conn = DriverManager.getConnection(connurl + new File(dir, "JoramDB").getPath() + ";shutdown=true;server.no_system_exit=true", "sa", "");
110
Properties JavaDoc props = new Properties JavaDoc();
111       props.put("user", "user1");
112       props.put("password", "user1");
113
114       conn = DriverManager.getConnection(connurl + new File JavaDoc(dir, "JoramDB").getPath() + ";create=true", props);
115       conn.setAutoCommit(false);
116     } catch (IllegalAccessException JavaDoc exc) {
117       throw new IOException JavaDoc(exc.getMessage());
118     } catch (ClassNotFoundException JavaDoc exc) {
119       throw new IOException JavaDoc(exc.getMessage());
120     } catch (InstantiationException JavaDoc exc) {
121       throw new IOException JavaDoc(exc.getMessage());
122     } catch (SQLException JavaDoc sqle) {
123       throw new IOException JavaDoc(sqle.getMessage());
124     }
125
126     try {
127       // Creating a statement lets us issue commands against the connection.
128
Statement JavaDoc s = conn.createStatement();
129       // We create the table.
130
// s.execute("create cached table JoramDB(name VARCHAR PRIMARY KEY, content VARBINARY(256))");
131
s.execute("CREATE TABLE JoramDB (name VARCHAR(256), content LONG VARCHAR FOR BIT DATA, PRIMARY KEY(name))");
132       s.close();
133       conn.commit();
134     } catch (SQLException JavaDoc sqle) {
135     }
136
137     try {
138       insertStmt = conn.prepareStatement("INSERT INTO JoramDB VALUES (?, ?)");
139       updateStmt = conn.prepareStatement("UPDATE JoramDB SET content=? WHERE name=?");
140       deleteStmt = conn.prepareStatement("DELETE FROM JoramDB WHERE name=?");
141     } catch (SQLException JavaDoc sqle) {
142       throw new IOException JavaDoc(sqle.getMessage());
143     }
144   }
145
146   /**
147    * Gets a list of persistent objects that name corresponds to prefix.
148    *
149    * @return The list of corresponding names.
150    */

151   public String JavaDoc[] list(String JavaDoc prefix) throws IOException JavaDoc {
152     try {
153       // Creating a statement lets us issue commands against the connection.
154
Statement JavaDoc s = conn.createStatement();
155       ResultSet JavaDoc rs = s.executeQuery("SELECT name FROM JoramDB WHERE name LIKE '" + prefix + "%'");
156
157       Vector JavaDoc v = new Vector JavaDoc();
158       while (rs.next()) {
159         v.add(rs.getString(1));
160       }
161       rs.close();
162       s.close();
163
164       String JavaDoc[] result = new String JavaDoc[v.size()];
165       result = (String JavaDoc[]) v.toArray(result);
166
167       return result;
168     } catch (SQLException JavaDoc sqle) {
169       throw new IOException JavaDoc(sqle.getMessage());
170     }
171   }
172
173   /**
174    * Save the corresponding bytes array.
175    */

176   public void save(String JavaDoc dirName, String JavaDoc name, byte[] content) throws IOException JavaDoc {
177     String JavaDoc fname = null;
178     if (dirName == null) {
179       fname = name;
180     } else {
181       fname = new StringBuffer JavaDoc(dirName).append('/').append(name).toString();
182     }
183
184     try {
185       insertStmt.setString(1, fname);
186       insertStmt.setBytes(2, content);
187       insertStmt.executeUpdate();
188     } catch (SQLException JavaDoc e) {
189       try {
190         updateStmt.setBytes(1, content);
191         updateStmt.setString(2, fname);
192         updateStmt.executeUpdate();
193       } catch (SQLException JavaDoc sqle) {
194         throw new IOException JavaDoc(sqle.getMessage());
195       }
196     }
197
198     nbsaved += 1;
199   }
200
201   /**
202    * Loads the object.
203    *
204    * @return The loaded object or null if it does not exist.
205    */

206   public Object JavaDoc loadobj(String JavaDoc dirName, String JavaDoc name) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
207     byte[] content = load(dirName, name);
208
209     ByteArrayInputStream JavaDoc bis = new ByteArrayInputStream JavaDoc(content);
210     ObjectInputStream JavaDoc ois = new ObjectInputStream JavaDoc(bis);
211     try {
212       Object JavaDoc obj = ois.readObject();
213       return obj;
214     } finally {
215       ois.close();
216       bis.close();
217     }
218   }
219
220   /**
221    * Loads the byte array.
222    *
223    * @return The loaded bytes array.
224    */

225   public byte[] load(String JavaDoc dirName, String JavaDoc name) throws IOException JavaDoc {
226     String JavaDoc fname = null;
227     if (dirName == null) {
228       fname = name;
229     } else {
230       fname = new StringBuffer JavaDoc(dirName).append('/').append(name).toString();
231     }
232
233     try {
234       // Creating a statement lets us issue commands against the connection.
235
Statement JavaDoc s = conn.createStatement();
236       //
237
ResultSet JavaDoc rs = s.executeQuery("SELECT content FROM JoramDB WHERE name='" + fname + "'");
238
239        if (!rs.next()) {
240          throw new FileNotFoundException JavaDoc("Cannot find object " + fname);
241        }
242
243        byte[] content = rs.getBytes(1);
244
245        rs.close();
246        s.close();
247
248        nbloaded += 1;
249        return content;
250     } catch (SQLException JavaDoc sqle) {
251       throw new IOException JavaDoc(sqle.getMessage());
252     }
253   }
254
255   /**
256    * Deletes the corresponding objects in repository.
257    */

258   public void delete(String JavaDoc dirName, String JavaDoc name) throws IOException JavaDoc {
259     String JavaDoc fname = null;
260     if (dirName == null) {
261       fname = name;
262     } else {
263       fname = new StringBuffer JavaDoc(dirName).append('/').append(name).toString();
264     }
265
266     int nb = 0;
267     try {
268       // Creating a statement lets us issue commands against the connection.
269
Statement JavaDoc s = conn.createStatement();
270       //
271
nb = s.executeUpdate("DELETE FROM JoramDB WHERE name='" + fname + "'");
272     } catch (SQLException JavaDoc sqle) {
273       throw new IOException JavaDoc(sqle.getMessage());
274     }
275     
276     if (nb != 1) baddeleted += 1;
277     nbdeleted += 1;
278   }
279
280   /**
281    * Commits all changes to the repository.
282    */

283   public void commit() throws IOException JavaDoc {
284     try {
285       conn.commit();
286     } catch (SQLException JavaDoc sqle) {
287       throw new IOException JavaDoc(sqle.getMessage());
288     }
289   }
290
291   /**
292    * Closes the repository.
293    */

294   public void close() throws IOException JavaDoc {
295     try {
296       conn.close();
297     } catch (SQLException JavaDoc sqle) {
298       throw new IOException JavaDoc(sqle.getMessage());
299     }
300   }
301 }
302
Popular Tags