KickJava   Java API By Example, From Geeks To Geeks.

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


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 /**
55  * Copyright (C) 2000 CoolServlets.com. All rights reserved.
56  *
57  * ===================================================================
58  * The Apache Software License, Version 1.1
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  * notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  * notice, this list of conditions and the following disclaimer in
69  * the documentation and/or other materials provided with the
70  * distribution.
71  *
72  * 3. The end-user documentation included with the redistribution,
73  * if any, must include the following acknowledgment:
74  * "This product includes software developed by
75  * CoolServlets.com (http://www.coolservlets.com)."
76  * Alternately, this acknowledgment may appear in the software itself,
77  * if and wherever such third-party acknowledgments normally appear.
78  *
79  * 4. The names "Jive" and "CoolServlets.com" must not be used to
80  * endorse or promote products derived from this software without
81  * prior written permission. For written permission, please
82  * contact webmaster@coolservlets.com.
83  *
84  * 5. Products derived from this software may not be called "Jive",
85  * nor may "Jive" appear in their name, without prior written
86  * permission of CoolServlets.com.
87  *
88  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
89  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
90  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
91  * DISCLAIMED. IN NO EVENT SHALL COOLSERVLETS.COM OR
92  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
93  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
94  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
95  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
96  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
97  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
98  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
99  * SUCH DAMAGE.
100  * ====================================================================
101  *
102  * This software consists of voluntary contributions made by many
103  * individuals on behalf of CoolServlets.com. For more information
104  * on CoolServlets.com, please see <http://www.coolservlets.com>.
105  */

106
107 package com.Yasna.forum.database;
108
109 import java.sql.*;
110 import java.util.*;
111 import java.text.SimpleDateFormat JavaDoc;
112
113 import com.Yasna.forum.*;
114 import com.Yasna.forum.Exceptions.RapidPostingException;
115 import com.Yasna.forum.Exceptions.UserBlackListedException;
116 import com.Yasna.forum.util.ClientIP;
117 import com.Yasna.util.Cacheable;
118 import com.Yasna.util.CacheSizes;
119 import com.Yasna.util.StringUtils;
120
121 /**
122  * Database implementation of the ForumMessage interface. It stores messages
123  * in the YazdMessage database table, and message properties in yazdMessageProp
124  * table.
125  */

126 public final class DbForumMessage implements ForumMessage, Cacheable {
127
128     /** DATABASE QUERIES **/
129     private static final String JavaDoc CHECK_LASTPOST=
130             "select max(a.creationDate) as lastpost from yazdMessage a,yazdMessageProp b where a.messageID=b.messageID and b.name=? and b.propValue=?";
131     private static final String JavaDoc CHECK_LASTPOSTWITHUSER =
132             "select max(creationDate) as lastpost from yazdMessage where userID=?";
133     private static final String JavaDoc LOAD_PROPERTIES =
134         "SELECT name, propValue FROM yazdMessageProp WHERE messageID=?";
135     private static final String JavaDoc DELETE_PROPERTIES =
136         "DELETE FROM yazdMessageProp WHERE messageID=?";
137     private static final String JavaDoc INSERT_PROPERTY =
138         "INSERT INTO yazdMessageProp(messageID,name,propValue) VALUES(?,?,?)";
139     private static final String JavaDoc LOAD_MESSAGE =
140         "SELECT userID, creationDate, modifiedDate, subject, body, threadID, " +
141         "replyPrivateUserId, approved,ranking FROM yazdMessage WHERE messageID=?";
142     private static final String JavaDoc INSERT_MESSAGE =
143         "INSERT INTO yazdMessage(messageID, threadID,creationDate,modifiedDate,userID," +
144         "subject,body,approved, replyPrivateUserId,ranking) VALUES(?,?,?,?,?,?,?,?,?,0)";
145     private static final String JavaDoc SAVE_MESSAGE =
146         "UPDATE yazdMessage SET userID=?, subject=?, body=?, creationDate=?, " +
147         "modifiedDate=?, replyPrivateUserId = ?, approved = ?,ranking=? WHERE messageID=?";
148     private static final String JavaDoc GET_FORUM_BY_THREAD =
149         "SELECT forumID FROM yazdThread where threadID=?";
150     private static final String JavaDoc CHECK_BLACK_LIST_IP="select ip from yazdBlackList where ip=?";
151     private static final String JavaDoc UPDATE_BLACK_LIST_IP="update yazdBlackList set blockcount=blockcount+1 where ip=?";
152     private static final String JavaDoc CHECK_BLACK_LIST_USER="select userID from yazdUserProp where userID=? and name=? and propValue=?";
153     private static final String JavaDoc CHECK_SESSION="select initime from yazdSessions where IP=?";
154
155     private int id = -1;
156     private java.util.Date JavaDoc creationDate;
157     private java.util.Date JavaDoc modifiedDate;
158     private String JavaDoc subject = "";
159     private int replyPrivateUserId = 0;
160     private boolean approved;
161     private String JavaDoc body = "";
162     private int userID;
163     private int threadID;
164     private Map properties;
165     private Object JavaDoc propertyLock = new Object JavaDoc();
166     private DbForumFactory factory;
167     private ForumThread thread = null;
168     private int ranking = MessageRanking.NOTRANKED; // default to neutral
169

170     /**
171      * Indicates if the object is ready to be saved or not. An object is not
172      * ready to be saved if it has just been created and has not yet been added
173      * to its container. For example, a message added to a thread, etc.
174      */

175     private boolean isReadyToSave = false;
176
177     /**
178      * Creates a new dummy DbForumMessage object.
179      * this is used to obtain the filtered message
180      */

181     protected DbForumMessage(User user, DbForumFactory factory) {
182         this.id = -1;
183         long now = System.currentTimeMillis();
184         creationDate = new java.util.Date JavaDoc(now);
185         modifiedDate = new java.util.Date JavaDoc(now);
186         this.userID = user.getID();
187         this.factory = factory;
188         this.approved = true;
189         properties = Collections.synchronizedMap(new HashMap());
190         isReadyToSave = false;
191     }
192
193     /**
194      * Creates a new DbForumMessage object.
195      */

196     protected DbForumMessage(User user, DbForumFactory factory, boolean approved,ClientIP clientIP) throws RapidPostingException,UserBlackListedException {
197         checkBlackList(user,clientIP);
198         checkForRapidPosts(user,clientIP);
199         checkForSession(user,clientIP);
200         this.id = DbSequenceManager.nextID("ForumMessage");
201         long now = System.currentTimeMillis();
202         creationDate = new java.util.Date JavaDoc(now);
203         modifiedDate = new java.util.Date JavaDoc(now);
204         this.userID = user.getID();
205         this.factory = factory;
206         this.approved = approved;
207         properties = Collections.synchronizedMap(new HashMap());
208     }
209
210     /**
211      * Loads the specified DbForumMessage by its message id.
212      */

213     protected DbForumMessage(int id, DbForumFactory factory)
214             throws ForumMessageNotFoundException
215     {
216         this.id = id;
217         this.factory = factory;
218         loadFromDb();
219         loadProperties();
220         isReadyToSave = true;
221     }
222
223     //FROM THE FORUMMESSAGE INTERFACE//
224

225     public int getID() {
226         return id;
227     }
228
229     public java.util.Date JavaDoc getCreationDate() {
230         return creationDate;
231     }
232
233     public void setCreationDate(java.util.Date JavaDoc creationDate)
234             throws UnauthorizedException
235     {
236         this.creationDate = creationDate;
237         //Only save to the db if the object is read
238
if (!isReadyToSave) {
239             return;
240         }
241         saveToDb();
242     }
243
244     public java.util.Date JavaDoc getModifiedDate() {
245         return modifiedDate;
246     }
247
248     public void setModifiedDate(java.util.Date JavaDoc modifiedDate)
249             throws UnauthorizedException
250     {
251         this.modifiedDate = modifiedDate;
252         //Only save to the db if the object is read
253
if (!isReadyToSave) {
254             return;
255         }
256         saveToDb();
257     }
258
259     public String JavaDoc getSubject() {
260         return subject;
261     }
262
263     public int getReplyPrivateUserId() {
264         return replyPrivateUserId;
265     }
266
267     public boolean isPrivate() {
268         return replyPrivateUserId > 0;
269     }
270
271     public String JavaDoc getUnfilteredSubject() {
272         return subject;
273     }
274
275     public void setSubject(String JavaDoc subject) throws UnauthorizedException {
276         this.subject = subject;
277         //Only save to the db if the object is read
278
if (!isReadyToSave) {
279             return;
280         }
281         //Update modifiedDate to the current time.
282
modifiedDate.setTime(System.currentTimeMillis());
283         saveToDb();
284     }
285
286     public void setReplyPrivateUserId(int replyPrivateUserId) throws UnauthorizedException {
287         this.replyPrivateUserId = replyPrivateUserId;
288         //Only save to the db if the object is read
289
if (!isReadyToSave) {
290             return;
291         }
292         //Update modifiedDate to the current time.
293
modifiedDate.setTime(System.currentTimeMillis());
294         saveToDb();
295     }
296
297     public void setApprovment(boolean approved) throws UnauthorizedException {
298         this.approved = approved;
299         //Only save to the db if the object is read
300
if (!isReadyToSave) {
301             return;
302         }
303         //Update modifiedDate to the current time.
304
modifiedDate.setTime(System.currentTimeMillis());
305         saveToDb();
306     }
307
308     public boolean isApproved() {
309         return approved;
310     }
311
312     public String JavaDoc getBody() {
313         return body;
314     }
315
316     public String JavaDoc getUnfilteredBody() {
317         return body;
318     }
319
320     public void setBody(String JavaDoc body) throws UnauthorizedException {
321         this.body = body;
322         //Only save to the db if the object is read
323
if (!isReadyToSave) {
324             return;
325         }
326         //Update modifiedDate to the current time.
327
modifiedDate.setTime(System.currentTimeMillis());
328         saveToDb();
329     }
330
331     public User getUser() {
332         User user = null;
333         try {
334             if (userID == -1) {
335                 user = factory.getProfileManager().getAnonymousUser();
336             }
337             else {
338                 user = factory.getProfileManager().getUser(userID);
339             }
340         }
341         catch (UserNotFoundException unfe) {
342             unfe.printStackTrace();
343         }
344         return user;
345     }
346
347     public String JavaDoc getProperty(String JavaDoc name) {
348         //For security reasons, pass through the HTML filter.
349
return StringUtils.escapeHTMLTags((String JavaDoc)properties.get(name));
350     }
351
352     public String JavaDoc getUnfilteredProperty(String JavaDoc name) {
353         return (String JavaDoc)properties.get(name);
354     }
355
356     public void setProperty(String JavaDoc name, String JavaDoc value) {
357         properties.put(name, value);
358         //Only save to the db if the object is read
359
if (!isReadyToSave) {
360             return;
361         }
362         saveProperties();
363     }
364
365     public Iterator propertyNames() {
366         return Collections.unmodifiableSet(properties.keySet()).iterator();
367     }
368
369     public boolean isAnonymous() {
370         return (userID == -1);
371     }
372
373     public ForumThread getForumThread() {
374         if (thread != null) {
375             return thread;
376         }
377         //Load the thread since this is the first time the method has been
378
//called.
379
else {
380             //First, we need a handle on the parent Forum object based
381
//on the threadID.
382

383             int forumID = -1;
384             Connection con = null;
385             PreparedStatement pstmt = null;
386             try {
387                 con = DbConnectionManager.getConnection();
388                 pstmt = con.prepareStatement(GET_FORUM_BY_THREAD);
389                 pstmt.setInt(1, threadID);
390                 ResultSet rs = pstmt.executeQuery();
391                 if (rs.next()) {
392                     forumID = rs.getInt("forumID");
393                 }
394              }
395             catch( SQLException sqle ) {
396                 sqle.printStackTrace();
397             }
398             finally {
399                 try { pstmt.close(); }
400                 catch (Exception JavaDoc e) { e.printStackTrace(); }
401                 try { con.close(); }
402                 catch (Exception JavaDoc e) { e.printStackTrace(); }
403             }
404             //If the forumID for the message is less than 1, we have problems.
405
//Print a warning and return null
406
if (forumID < 1) {
407                 System.err.println("WARNING: forumID of " + forumID +
408                     " found for message " + id + " in DbForumMessage.getForumThread()." +
409                     " You may wish to delete the message from your database."
410                 );
411                 return null;
412             }
413
414             Forum forum = null;
415             ForumThread thread = null;
416             try {
417                 forum = factory.getForum(forumID);
418                 //Now, get the thread
419
thread = forum.getThread(threadID);
420             }
421             catch (Exception JavaDoc e) {
422                 e.printStackTrace();
423                 return null;
424             }
425             this.thread = thread;
426             return thread;
427         }
428     }
429
430     public boolean hasPermission(int type) {
431         return true;
432     }
433
434     //FROM CACHEABLE INTERFACE//
435

436     public int getSize() {
437         //Approximate the size of the object in bytes by calculating the size
438
//of each field.
439
int size = 0;
440         size += CacheSizes.sizeOfObject(); //overhead of object
441
size += CacheSizes.sizeOfInt(); //id
442
size += CacheSizes.sizeOfString(subject); //subject
443
size += CacheSizes.sizeOfString(body); //body
444
size += CacheSizes.sizeOfDate(); //creation date
445
size += CacheSizes.sizeOfDate(); //modified date
446
size += CacheSizes.sizeOfInt(); //userID
447
size += CacheSizes.sizeOfInt(); //threadID
448
size += CacheSizes.sizeOfInt(); //replyPrivateUserId
449
size += CacheSizes.sizeOfBoolean(); //approved
450
size += CacheSizes.sizeOfMap(properties); //map object
451
size += CacheSizes.sizeOfObject(); //property lock
452
size += CacheSizes.sizeOfObject(); //ref to factory
453

454         return size;
455     }
456
457     //OTHER METHODS//
458

459     /**
460      * Returns a String representation of the message object using the subject.
461      *
462      * @return a String representation of the ForumMessage object.
463      */

464     public String JavaDoc toString() {
465         return subject;
466     }
467
468     public int hashCode() {
469         return id;
470     }
471
472     public boolean equals(Object JavaDoc object) {
473         if (this == object) {
474             return true;
475         }
476         if (object != null && object instanceof DbForumMessage) {
477             return id == ((DbForumMessage)object).getID();
478         }
479         else {
480             return false;
481         }
482     }
483
484     /**
485      * Loads message properties from the database.
486      */

487     private void loadProperties() {
488         synchronized(propertyLock) {
489             Properties newProps = new Properties();
490             Connection con = null;
491             PreparedStatement pstmt = null;
492             try {
493                 con = DbConnectionManager.getConnection();
494                 pstmt = con.prepareStatement(LOAD_PROPERTIES);
495                 pstmt.setInt(1, id);
496                 ResultSet rs = pstmt.executeQuery();
497                 while(rs.next()) {
498                     String JavaDoc name = rs.getString("name");
499                     String JavaDoc value = rs.getString("propValue");
500                     newProps.put(name, value);
501                 }
502             }
503             catch( SQLException sqle ) {
504                 System.err.println("Error in DbForumMessage:loadProperties():" + sqle);
505                 sqle.printStackTrace();
506             }
507             finally {
508                 try { pstmt.close(); }
509                 catch (Exception JavaDoc e) { e.printStackTrace(); }
510                 try { con.close(); }
511                 catch (Exception JavaDoc e) { e.printStackTrace(); }
512             }
513             this.properties = newProps;
514         }
515     }
516
517     /**
518      * Saves message properties to the database.
519      */

520     private void saveProperties() {
521         synchronized(propertyLock) {
522             Connection con = null;
523             PreparedStatement pstmt = null;
524             try {
525                 con = DbConnectionManager.getConnection();
526                 //Delete all old values.
527
pstmt = con.prepareStatement(DELETE_PROPERTIES);
528                 pstmt.setInt(1, id);
529                 pstmt.execute();
530                 pstmt.close();
531                 //Now insert new values.
532
pstmt = con.prepareStatement(INSERT_PROPERTY);
533                 Iterator iter = properties.keySet().iterator();
534                 while (iter.hasNext()) {
535                     String JavaDoc name = (String JavaDoc)iter.next();
536                     String JavaDoc value = (String JavaDoc)properties.get(name);
537                     pstmt.setInt(1, id);
538                     pstmt.setString(2, name);
539                     pstmt.setString(3, value);
540                     pstmt.executeUpdate();
541                 }
542             }
543             catch( SQLException sqle ) {
544                 System.err.println(sqle);
545             }
546             finally {
547                 try { pstmt.close(); }
548                 catch (Exception JavaDoc e) { e.printStackTrace(); }
549                 try { con.close(); }
550                 catch (Exception JavaDoc e) { e.printStackTrace(); }
551             }
552         }
553     }
554
555     /**
556      * Loads message and user data from the database.
557      */

558     private void loadFromDb() throws ForumMessageNotFoundException {
559         // Based on the id in the object, get the message data from the database.
560
Connection con = null;
561         PreparedStatement pstmt = null;
562         try {
563             con = DbConnectionManager.getConnection();
564             pstmt = con.prepareStatement(LOAD_MESSAGE);
565             pstmt.setInt(1, id);
566             ResultSet rs = pstmt.executeQuery();
567             if( !rs.next() ) {
568                 throw new ForumMessageNotFoundException("Message " + id +
569                     " could not be loaded from the database.");
570             }
571             //Get the query results. We use int indexes into the ResultSet
572
//because it is slightly faster. Care should be taken so that the
573
//SQL query is not modified without modifying these indexes.
574
this.userID = rs.getInt(1);
575             //We trim() the dates before trying to parse them because some
576
//databases pad with extra characters when returning the data.
577
this.creationDate =
578                 new java.util.Date JavaDoc(Long.parseLong(rs.getString(2).trim()));
579             this.modifiedDate =
580                 new java.util.Date JavaDoc(Long.parseLong(rs.getString(3).trim()));
581             this.subject = rs.getString(4);
582             this.body = rs.getString(5);
583             this.threadID = rs.getInt(6);
584             this.replyPrivateUserId = rs.getInt(7);
585             this.approved = rs.getInt(8) == 1 ? true : false;
586             this.ranking = rs.getInt("ranking");
587          }
588         catch( SQLException sqle ) {
589             throw new ForumMessageNotFoundException( "Message of id "
590                     + id + " was not found in the database."
591             );
592         }
593         catch (NumberFormatException JavaDoc nfe) {
594             System.err.println("WARNING: In DbForumMessage.loadFromDb() -- there " +
595                 "was an error parsing the dates returned from the database. Ensure " +
596                 "that they're being stored correctly.");
597         }
598         finally {
599             try { pstmt.close(); }
600             catch (Exception JavaDoc e) { e.printStackTrace(); }
601             try { con.close(); }
602             catch (Exception JavaDoc e) { e.printStackTrace(); }
603         }
604     }
605
606     /**
607      * Inserts a new message into the database. A connection object must
608      * be passed in. The connection must be open when passed in, and will
609      * remain open when passed back. This method allows us to make insertions
610      * be transactional.
611      *
612      * @param con an open Connection used to insert the thread to the db.
613      * @param thread the ForumThread the message is being added to.
614      */

615     public void insertIntoDb(Connection con, ForumThread thread)
616             throws SQLException
617     {
618         //Set the message threadID to the thread that the message is being
619
//added to.
620
this.threadID = thread.getID();
621         PreparedStatement pstmt = con.prepareStatement(INSERT_MESSAGE);
622         pstmt.setInt(1, id);
623         pstmt.setInt(2, threadID);
624         pstmt.setString(3, Long.toString(creationDate.getTime()));
625         pstmt.setString(4, Long.toString(modifiedDate.getTime()));
626         pstmt.setInt(5, userID);
627         pstmt.setString(6, subject);
628         pstmt.setString(7, body);
629         pstmt.setInt(8, approved ? 1 : 0);
630         pstmt.setInt(9, replyPrivateUserId);
631         pstmt.executeUpdate();
632         pstmt.close();
633
634         //We're done inserting the message, so now save any extended
635
//properties to the database.
636
saveProperties();
637
638         //Now add the message to the watch list so that the proper users are notified.
639
factory.getWatchManager().addMessage(this);
640         //since we're done inserting the object to the database, it is ready
641
//for future insertions.
642
isReadyToSave = true;
643     }
644
645     /**
646      * Saves message data to the database.
647      */

648     private synchronized void saveToDb() {
649         Connection con = null;
650         PreparedStatement pstmt = null;
651         try {
652             con = DbConnectionManager.getConnection();
653             pstmt = con.prepareStatement(SAVE_MESSAGE);
654             pstmt.setInt(1, userID);
655             pstmt.setString(2, subject);
656             pstmt.setString(3, body);
657             pstmt.setString(4, Long.toString(creationDate.getTime()));
658             pstmt.setString(5, Long.toString(modifiedDate.getTime()));
659             pstmt.setInt(6, replyPrivateUserId);
660             pstmt.setInt(7, approved ? 1 : 0);
661             pstmt.setInt(8,this.ranking);
662             pstmt.setInt(9, id);
663             pstmt.executeUpdate();
664         }
665         catch( SQLException sqle ) {
666             System.err.println( "SQLException in DbForumMessage:saveToDb()- " + sqle );
667             sqle.printStackTrace();
668         }
669         finally {
670             try { pstmt.close(); }
671             catch (Exception JavaDoc e) { e.printStackTrace(); }
672             try { con.close(); }
673             catch (Exception JavaDoc e) { e.printStackTrace(); }
674         }
675     }
676     /**
677      * this method checks to see if the user has already posted another message in the restricted window.
678      * @param user
679      * @param clientIP
680      * @throws RapidPostingException
681      */

682     private void checkForRapidPosts(User user,ClientIP clientIP) throws RapidPostingException{
683         // there is minor problem with this method:
684
// A user who is logged in can post a message, then logout and post another message without a problem.
685
// We need to check against the IP addresses of the messages.
686
Connection con = null;
687             PreparedStatement pstmt = null;
688             try {
689                 con = DbConnectionManager.getConnection();
690                 int ranking=10; //This would be anonymous ranking
691
if(user.isAnonymous()){
692                     pstmt = con.prepareStatement(CHECK_LASTPOST);
693                     pstmt.setString(1, "IP");
694                     pstmt.setString(2,clientIP.getRemoteIP());
695                 } else {
696                     pstmt = con.prepareStatement(CHECK_LASTPOSTWITHUSER);
697                     pstmt.setInt(1, user.getID());
698                     ranking=Integer.parseInt(user.getProperty("ranking"));
699                 }
700                 ResultSet rs = pstmt.executeQuery();
701                 if( rs.next() ) {
702                     if (rs.getString("lastpost")!=null && !rs.getString("lastpost").toUpperCase().equals("NULL") && !rs.getString("lastpost").equals("")){
703                      if(Calendar.getInstance().getTimeInMillis()-Long.parseLong(rs.getString("lastpost")) < Long.parseLong(SystemProperty.getProperty("PeriodBetweenPosts"))*ranking){
704                       long timediff = (Calendar.getInstance().getTimeInMillis() - Long.parseLong(rs.getString("lastpost")))/1000;
705                       throw new RapidPostingException("Rapid Posting Error. There was a post already posted at " + Long.toString(timediff)+" seconds ago!");
706                      }
707                     }
708                 }
709             }
710             catch( SQLException sqle ) {
711                 System.err.println("an error occured in DbForumMessage (0934):"+sqle.getMessage());
712                 sqle.printStackTrace();
713             }
714             finally {
715                 try { pstmt.close(); }
716                 catch (Exception JavaDoc e) { e.printStackTrace(); }
717                 try { con.close(); }
718                 catch (Exception JavaDoc e) { e.printStackTrace(); }
719             }
720     }
721     private void checkForSession(User user,ClientIP clientIP) throws RapidPostingException{
722             Connection con = null;
723             PreparedStatement pstmt = null;
724             try {
725                 con = DbConnectionManager.getConnection();
726         pstmt = con.prepareStatement(CHECK_SESSION);
727         pstmt.setString(1,clientIP.getRemoteIP());
728                 ResultSet rs = pstmt.executeQuery();
729                 if( rs.next() ) {
730                      if(Calendar.getInstance().getTimeInMillis()-Long.parseLong(rs.getString("initime"))*1000.0 < Long.parseLong(SystemProperty.getProperty("WaitPeriod"))){
731                       throw new RapidPostingException("Rapid Posting Error. Wait period is " + SystemProperty.getProperty("WaitPeriod")+"!");
732                      }
733                 }
734             }
735             catch( SQLException sqle ) {
736                 System.err.println("an error occured in DbForumMessage (0936):"+sqle.getMessage());
737                 sqle.printStackTrace();
738             }
739             finally {
740                 try { pstmt.close(); }
741                 catch (Exception JavaDoc e) { e.printStackTrace(); }
742                 try { con.close(); }
743                 catch (Exception JavaDoc e) { e.printStackTrace(); }
744             }
745     }
746     
747     private void checkBlackList(User user,ClientIP clientIP) throws UserBlackListedException {
748         System.err.println("checking blacklist");
749         Connection con = null;
750         PreparedStatement pstmt = null;
751         try {
752             con = DbConnectionManager.getConnection();
753             pstmt = con.prepareStatement(CHECK_BLACK_LIST_IP);
754             pstmt.setString(1,clientIP.getRemoteIP());
755             ResultSet rs = pstmt.executeQuery();
756             if(rs.next()){
757                 pstmt = con.prepareStatement(UPDATE_BLACK_LIST_IP);
758                 pstmt.setString(1,clientIP.getRemoteIP());
759                 pstmt.executeUpdate();
760                 throw new UserBlackListedException("User Black Listed Error. The IP address "+clientIP.getRemoteIP()+" has been black listed");
761             }
762             pstmt = con.prepareStatement(CHECK_BLACK_LIST_USER);
763             pstmt.setInt(1,user.getID());
764             pstmt.setString(2,"BLOCKED");
765             pstmt.setString(3,"true");
766             rs = pstmt.executeQuery();
767             if(rs.next()){
768                 throw new UserBlackListedException("User Black Listed Error. This user has been black listed from the sytem");
769             }
770         }
771         catch( SQLException sqle ) {
772             System.err.println("an error occured in DbForumMessage (0935):"+sqle.getMessage());
773             sqle.printStackTrace();
774         }
775         finally {
776             try { pstmt.close(); }
777             catch (Exception JavaDoc e) { e.printStackTrace(); }
778             try { con.close(); }
779             catch (Exception JavaDoc e) { e.printStackTrace(); }
780         }
781     }
782     public MessageRanking getRanking(){
783         return new MessageRanking(this.ranking);
784     }
785     public void setRanking(int para) throws UnauthorizedException{
786         this.ranking=para;
787         saveToDb();
788
789     }
790
791 }
Popular Tags