KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > Yasna > forum > database > DbCategory


1 /**
2  * Copyright (C) 2001 Yasna.com. All rights reserved.
3  *
4  * ===================================================================
5  * The Apache Software License, Version 1.1
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  * if any, must include the following acknowledgment:
21  * "This product includes software developed by
22  * Yasna.com (http://www.yasna.com)."
23  * Alternately, this acknowledgment may appear in the software itself,
24  * if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Yazd" and "Yasna.com" must not be used to
27  * endorse or promote products derived from this software without
28  * prior written permission. For written permission, please
29  * contact yazd@yasna.com.
30  *
31  * 5. Products derived from this software may not be called "Yazd",
32  * nor may "Yazd" appear in their name, without prior written
33  * permission of Yasna.com.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL YASNA.COM OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of Yasna.com. For more information
51  * on Yasna.com, please see <http://www.yasna.com>.
52  */

53
54 package com.Yasna.forum.database;
55
56 import java.util.Iterator JavaDoc;
57 import java.util.Enumeration JavaDoc;
58 import java.util.Properties JavaDoc;
59 import java.util.ArrayList JavaDoc;
60 import java.util.Date JavaDoc;
61 import java.sql.*;
62 import java.io.*;
63
64 import com.Yasna.forum.*;
65 import com.Yasna.forum.filter.*;
66 import com.Yasna.util.Cache;
67 import com.Yasna.util.Cacheable;
68 import com.Yasna.util.CacheSizes;
69
70 /**
71  * Database implementation of the Category interface. It loads and stores category
72  * information from the database.
73  *
74  * @see Category
75  */

76 public class DbCategory implements Category, Cacheable {
77
78     /** DATABASE QUERIES **/
79     private static final String JavaDoc LOAD_CATEGORY_BY_ID =
80         "SELECT categoryID, name, description, creationDate, modifiedDate,catorder FROM yazdCategory WHERE CategoryID=?";
81     private static final String JavaDoc LOAD_CATEGORY_BY_NAME =
82         "SELECT categoryID, name, description, creationDate, modifiedDate,catorder FROM yazdCategory WHERE name=?";
83     private static final String JavaDoc UPDATE_CATEGORY_MODIFIED_DATE =
84         "UPDATE yazdCategory SET modifiedDate=? WHERE categoryID=?";
85     private static final String JavaDoc ADD_CATEGORY =
86         "INSERT INTO yazdCategory(categoryID, name, description, creationDate, " +
87         "modifiedDate,catorder) VALUES (?,?,?,?,?,0)";
88     private static final String JavaDoc SAVE_CATEGORY =
89         "UPDATE yazdCategory SET name=?, description=?, creationDate=?, " +
90         "modifiedDate=?,catorder=? WHERE categoryID=?";
91     private static final String JavaDoc DELETE_FORUM_GROUP =
92         "DELETE FROM yazdForumGroup WHERE forumGroupID=?";
93
94     private int id = -1;
95     private String JavaDoc name;
96     private String JavaDoc description;
97     private java.util.Date JavaDoc creationDate;
98     private java.util.Date JavaDoc modifiedDate;
99
100     private DbForumFactory factory;
101     private int catorder=0;
102
103     /**
104      * Creates a new category with the specified name and description.
105      *
106      * @param name the name of the category.
107      * @param description the description of the category.
108      * @param factory the DbForumFactory that will hold the category.
109      */

110     protected DbCategory(String JavaDoc name, String JavaDoc description, DbForumFactory factory) {
111         this.id = DbSequenceManager.nextID("Category");
112         this.name = name;
113         this.description = description;
114         long now = System.currentTimeMillis();
115         creationDate = new java.util.Date JavaDoc(now);
116         modifiedDate = new java.util.Date JavaDoc(now);
117         this.factory = factory;
118         insertIntoDb();
119     }
120
121     /**
122      * Loads a category with the specified id.
123      */

124     protected DbCategory(int id, DbForumFactory factory)
125             throws CategoryNotFoundException
126     {
127         this.id = id;
128         this.factory = factory;
129         loadFromDb();
130     }
131
132     /**
133      * Loads a category with the specified name.
134      */

135     protected DbCategory(String JavaDoc name, DbForumFactory factory)
136             throws CategoryNotFoundException
137     {
138         this.name = name;
139         this.factory = factory;
140         loadFromDb();
141     }
142
143     //FROM THE CATEGORY INTERFACE//
144

145     public int getID() {
146         return id;
147     }
148
149     public String JavaDoc getName() {
150         return name;
151     }
152     public int getOrder(){
153         return this.catorder;
154     }
155     public void setOrder(int param) throws UnauthorizedException{
156         this.catorder=param;
157         saveToDb();
158     }
159     public void setName(String JavaDoc name) throws UnauthorizedException {
160         this.name = name;
161         saveToDb();
162     }
163
164     public String JavaDoc getDescription() {
165         return description;
166     }
167
168     public void setDescription(String JavaDoc description) throws UnauthorizedException
169     {
170         this.description = description;
171         saveToDb();
172     }
173
174     public java.util.Date JavaDoc getCreationDate() {
175         return creationDate;
176     }
177
178     public void setCreationDate(java.util.Date JavaDoc creationDate)
179             throws UnauthorizedException
180     {
181        this.creationDate = creationDate;
182        saveToDb();
183     }
184
185     public java.util.Date JavaDoc getModifiedDate() {
186         return modifiedDate;
187     }
188
189     public void setModifiedDate(java.util.Date JavaDoc modifiedDate)
190             throws UnauthorizedException
191     {
192         this.modifiedDate = modifiedDate;
193         saveToDb();
194     }
195
196     public Iterator JavaDoc forumGroups() {
197         return new DbForumGroupIterator(this, factory);
198     }
199
200     public ForumGroup getForumGroup(int forumGroupID) throws
201             ForumGroupNotFoundException
202     {
203         return factory.getForumGroup(forumGroupID, this);
204     }
205
206     public ForumGroup createForumGroup(String JavaDoc name, String JavaDoc description) throws UnauthorizedException
207     {
208         return new DbForumGroup(name, description, this, factory);
209     }
210
211
212     public void deleteForumGroup(ForumGroup forumGroup) throws UnauthorizedException
213     {
214         Iterator JavaDoc forumIterator = forumGroup.forums();
215         while(forumIterator.hasNext()){
216             Forum forumTmp = (Forum)forumIterator.next();
217             factory.deleteForum(forumTmp);
218         }
219
220         Connection con = null;
221         PreparedStatement pstmt = null;
222         try {
223             con = DbConnectionManager.getConnection();
224             pstmt = con.prepareStatement(DELETE_FORUM_GROUP);
225             pstmt.setInt(1,forumGroup.getID());
226             pstmt.execute();
227             pstmt.close();
228         }
229         catch( Exception JavaDoc sqle ) {
230             System.err.println("Error in DbForumFactory:deleteForumGroup()-" + sqle);
231         }
232         finally {
233             try { pstmt.close(); }
234             catch (Exception JavaDoc e) { e.printStackTrace(); }
235             try { con.close(); }
236             catch (Exception JavaDoc e) { e.printStackTrace(); }
237         }
238
239     }
240
241
242     //FROM THE CACHEABLE INTERFACE//
243

244     public int getSize() {
245         //Approximate the size of the object in bytes by calculating the size
246
//of each field.
247
int size = 0;
248         size += CacheSizes.sizeOfObject(); //overhead of object
249
size += CacheSizes.sizeOfObject(); //ref to category
250
size += CacheSizes.sizeOfInt(); //id
251
size += CacheSizes.sizeOfString(name); //name
252
size += CacheSizes.sizeOfString(description); //description
253
size += CacheSizes.sizeOfDate(); //creation date
254
size += CacheSizes.sizeOfDate(); //modified date
255
size += CacheSizes.sizeOfObject(); //save lock
256
size += CacheSizes.sizeOfInt(); //catorder
257

258         return size;
259     }
260
261     /**
262      * Updates the modified date but doesn't require a security check since
263      * it is a protected method.
264      */

265     protected void updateModifiedDate(java.util.Date JavaDoc modifiedDate) {
266         this.modifiedDate = modifiedDate;
267         Connection con = null;
268         PreparedStatement pstmt = null;
269         try {
270             con = DbConnectionManager.getConnection();
271             pstmt = con.prepareStatement(UPDATE_CATEGORY_MODIFIED_DATE);
272             pstmt.setString(1, ""+modifiedDate.getTime());
273             pstmt.setInt(2, id);
274             pstmt.executeUpdate();
275         }
276         catch( SQLException sqle ) {
277             System.err.println("Error in DbCategory:updateModifiedDate()-" + sqle);
278             sqle.printStackTrace();
279         }
280         finally {
281             try { pstmt.close(); }
282             catch (Exception JavaDoc e) { e.printStackTrace(); }
283             try { con.close(); }
284             catch (Exception JavaDoc e) { e.printStackTrace(); }
285         }
286     }
287
288
289     /**
290      * Loads category data from the database.
291      */

292     private void loadFromDb() throws CategoryNotFoundException {
293         Connection con = null;
294         PreparedStatement pstmt = null;
295         try {
296             con = DbConnectionManager.getConnection();
297             //See if we should load by categoryID or by name
298
if (id == -1) {
299                 pstmt = con.prepareStatement(LOAD_CATEGORY_BY_NAME);
300                 pstmt.setString(1,name);
301             }
302             else {
303                 pstmt = con.prepareStatement(LOAD_CATEGORY_BY_ID);
304                 pstmt.setInt(1, id);
305             }
306             ResultSet rs = pstmt.executeQuery();
307             if( !rs.next() ) {
308                 throw new CategoryNotFoundException("Category " + getID() +
309                     " could not be loaded from the database.");
310             }
311             id = rs.getInt("categoryID");
312             name = rs.getString("name");
313             description = rs.getString("description");
314             this.creationDate =
315                 new java.util.Date JavaDoc(Long.parseLong(rs.getString("creationDate").trim()));
316             this.modifiedDate =
317                 new java.util.Date JavaDoc(Long.parseLong(rs.getString("modifiedDate").trim()));
318             catorder=rs.getInt("catorder");
319         }
320         catch( SQLException sqle ) {
321             sqle.printStackTrace();
322             throw new CategoryNotFoundException("Category " + getID() +
323                 " could not be loaded from the database.");
324         }
325         catch (NumberFormatException JavaDoc nfe) {
326             System.err.println("WARNING: In DbCAtegory.loadFromDb() -- there " +
327                 "was an error parsing the dates returned from the database. Ensure " +
328                 "that they're being stored correctly.");
329         }
330         finally {
331             try { pstmt.close(); }
332             catch (Exception JavaDoc e) { e.printStackTrace(); }
333             try { con.close(); }
334             catch (Exception JavaDoc e) { e.printStackTrace(); }
335         }
336     }
337
338     /**
339      * Inserts a new record into the database.
340      */

341     private void insertIntoDb() {
342         Connection con = null;
343         PreparedStatement pstmt = null;
344         try {
345             con = DbConnectionManager.getConnection();
346             pstmt = con.prepareStatement(ADD_CATEGORY);
347             pstmt.setInt(1,id);
348             pstmt.setString(2,name);
349             pstmt.setString(3,description);
350             pstmt.setString(4, Long.toString(creationDate.getTime()));
351             pstmt.setString(5, Long.toString(modifiedDate.getTime()));
352             pstmt.executeUpdate();
353         }
354         catch( SQLException sqle ) {
355             System.err.println("Error in DbCategory:insertIntoDb()-" + sqle);
356             sqle.printStackTrace();
357         }
358         finally {
359             try { pstmt.close(); }
360             catch (Exception JavaDoc e) { e.printStackTrace(); }
361             try { con.close(); }
362             catch (Exception JavaDoc e) { e.printStackTrace(); }
363         }
364     }
365
366     /**
367      * Saves category data to the database.
368      */

369     private synchronized void saveToDb() {
370         Connection con = null;
371         PreparedStatement pstmt = null;
372         try {
373             con = DbConnectionManager.getConnection();
374             pstmt = con.prepareStatement(SAVE_CATEGORY);
375             pstmt.setString(1, name);
376             pstmt.setString(2, description);
377             pstmt.setString(3, Long.toString(creationDate.getTime()));
378             pstmt.setString(4, Long.toString(modifiedDate.getTime()));
379             pstmt.setInt(5,catorder);
380             pstmt.setInt(6, id);
381             pstmt.executeUpdate();
382         }
383         catch( SQLException sqle ) {
384             System.err.println("Error in DbForum:saveToDb()-" + sqle);
385             sqle.printStackTrace();
386         }
387         finally {
388             try { pstmt.close(); }
389             catch (Exception JavaDoc e) { e.printStackTrace(); }
390             try { con.close(); }
391             catch (Exception JavaDoc e) { e.printStackTrace(); }
392         }
393     }
394 }
395
Popular Tags