KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > forums > NewsMessage


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oña, 107 1º2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.forums;
34
35 import java.util.Date JavaDoc;
36
37 import java.io.IOException JavaDoc;
38 import java.io.Reader JavaDoc;
39
40 import java.sql.SQLException JavaDoc;
41 import java.sql.CallableStatement JavaDoc;
42 import java.sql.Statement JavaDoc;
43 import java.sql.PreparedStatement JavaDoc;
44 import java.sql.ResultSet JavaDoc;
45 import java.sql.ResultSetMetaData JavaDoc;
46 import java.sql.Timestamp JavaDoc;
47 import java.sql.Types JavaDoc;
48
49 import com.knowgate.debug.DebugFile;
50 import com.knowgate.jdc.JDCConnection;
51 import com.knowgate.misc.Gadgets;
52
53 import com.knowgate.dataobjs.DB;
54 import com.knowgate.dataobjs.DBBind;
55 import com.knowgate.dataobjs.DBPersist;
56 import com.knowgate.dataobjs.DBSubset;
57
58 import com.knowgate.hipergate.Product;
59
60 /**
61  * <p>NewsMessage</p>
62  * @author Sergio Montoro Ten
63  * @version 3.0
64  */

65 public class NewsMessage extends DBPersist{
66
67   /**
68    * Create empty NewsMessage
69    */

70   public NewsMessage() {
71     super(DB.k_newsmsgs, "NewsMessage");
72   }
73
74   // ----------------------------------------------------------
75

76   /**
77    * Post a Plain Text Message
78    * @param oConn Database Conenction
79    * @param sNewsGroupId GUID of NewsGroup for posting
80    * @param sThreadId GUID of message thread (may be <b>null</b>)
81    * @param dtStart Start publishing date (may be <b>null</b>)
82    * @param dtEnd Expiration date (may be <b>null</b>)
83    * @param iStatus STATUS_VALIDATED or STATUS_PENDING
84    * @param sText Message Text
85    * @return GUID of new message
86    * @throws SQLException
87    */

88   public String JavaDoc post (JDCConnection oConn, String JavaDoc sNewsGroupId, String JavaDoc sThreadId, Date JavaDoc dtStart, Date JavaDoc dtEnd, short iStatus, String JavaDoc sText) throws SQLException JavaDoc {
89
90     if (DebugFile.trace) {
91       DebugFile.writeln("Begin NewsMessage.post([Connection], " + sNewsGroupId + "," + sThreadId + ")");
92       DebugFile.incIdent();
93     }
94
95     String JavaDoc sRetVal;
96
97     remove(DB.gu_newsgrp);
98     if (sNewsGroupId!=null) put(DB.gu_newsgrp, sNewsGroupId);
99
100     remove(DB.gu_thread_msg);
101     if (sThreadId!=null) put(DB.gu_thread_msg, sThreadId);
102
103     remove(DB.dt_start);
104     if (dtStart!=null) put(DB.dt_start, dtStart);
105
106     remove(DB.dt_end);
107     if (dtEnd!=null) put(DB.dt_end, dtEnd);
108
109     remove(DB.id_status);
110     put(DB.id_status, iStatus);
111
112     remove(DB.tx_msg);
113     if (sText!=null) put(DB.tx_msg, sText);
114
115     if (store(oConn))
116       sRetVal = getString(DB.gu_msg);
117     else
118       sRetVal = null;
119
120     if (DebugFile.trace) {
121       DebugFile.decIdent();
122       DebugFile.writeln("End NewsMessage.post() : " + sRetVal);
123     }
124
125     return sRetVal;
126   } // post
127

128   // ----------------------------------------------------------
129

130   /**
131    * Load message
132    * @param oConn JDCConnection
133    * @param sGuMsg String Message GUID
134    * @return boolean <b>true</b> if message was successfully loaded,
135    * <b>false</b> if no message with such GUID was found
136    * @throws SQLException
137    * @since 3.0
138    */

139   public boolean load (JDCConnection oConn, String JavaDoc sGuMsg) throws SQLException JavaDoc {
140     final int BufferSize = 2048;
141     final String JavaDoc sSQL = "SELECT * FROM " + DB.k_newsmsgs + " WHERE " + DB.gu_msg + "=?";
142     boolean bRetVal;
143     if (DebugFile.trace) {
144       DebugFile.writeln("Begin NewsMessage.load([Connection], " + sGuMsg + ")");
145       DebugFile.incIdent();
146       DebugFile.writeln("Connection.prepareStatement("+sSQL+")");
147     }
148     PreparedStatement JavaDoc oStmt = oConn.prepareStatement(sSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
149     oStmt.setString(1, sGuMsg);
150     ResultSet JavaDoc oRSet = oStmt.executeQuery();
151     bRetVal = oRSet.next();
152     if (bRetVal) {
153       ResultSetMetaData JavaDoc oMDat = oRSet.getMetaData();
154       int nCols = oMDat.getColumnCount();
155       int iType;
156       int iReaded;
157       for (int c=1; c<=nCols; c++) {
158         iType = oMDat.getColumnType(c);
159         if ((iType!=Types.LONGVARCHAR) && (iType!=Types.LONGVARBINARY) &&
160             (iType!=Types.CLOB) && (iType!=Types.BLOB)) {
161           put (oMDat.getColumnName(c).toLowerCase(), oRSet.getObject(c));
162         } else if (iType==Types.LONGVARCHAR) {
163           char Buffer[] = new char[BufferSize];
164           StringBuffer JavaDoc oBody = new StringBuffer JavaDoc();
165           Reader JavaDoc oRead = oRSet.getCharacterStream(c);
166           if (null!=oRead) {
167             try {
168               do {
169                 iReaded = oRead.read(Buffer,0,BufferSize);
170                 if (iReaded>0) oBody.append(Buffer,0,iReaded);
171               } while (BufferSize==iReaded);
172               oRead.close();
173             } catch (IOException JavaDoc ioe) {
174               try { oRSet.close(); } catch (Exception JavaDoc ignore) {}
175               try { oStmt.close(); } catch (Exception JavaDoc ignore) {}
176               throw new SQLException JavaDoc (ioe.getMessage());
177             }
178             put (oMDat.getColumnName(c).toLowerCase(), oBody.toString());
179           } // fi (oRead!=null)
180
}
181       } // next (c)
182
} // fi (bRetVal)
183
oRSet.close();
184     oStmt.close();
185
186     if (DebugFile.trace) {
187       DebugFile.decIdent();
188       DebugFile.writeln("End NewsMessage.load() : " + String.valueOf(bRetVal));
189     }
190
191     return bRetVal;
192   } // load
193

194   // ----------------------------------------------------------
195

196   /**
197    * Get attachments
198    * @param oConn JDCConnection
199    * @return DBSubset listing attachments or <b>null</b> if this message has no attachments
200    * @throws SQLException
201    * @since 3.0
202    */

203   public DBSubset getAttachments(JDCConnection oConn) throws SQLException JavaDoc {
204     Product oProd;
205     if (isNull(DB.gu_product))
206       return null;
207     else {
208       oProd = new Product(getString(DB.gu_product));
209       return oProd.getLocations(oConn);
210     }
211   } // getAttachments
212

213   // ----------------------------------------------------------
214

215   public boolean load (JDCConnection oConn, Object JavaDoc[] aPK) throws SQLException JavaDoc {
216     return load(oConn, (String JavaDoc) aPK[0]);
217   }
218
219   // ----------------------------------------------------------
220

221   /**
222    * <p>Store NewsMessage</p>
223    * Message is posted into a NewsGroup by setting gu_newsgrp property of
224    * NewsMessage to the GUID of newsMessage that will contain it.<br>
225    * If gu_msg is <b>null</b> then a new GUID will be assigned.<br>
226    * If gu_thread_msg is <b>null</b> and gu_parent_msg is <b>null</b> then gu_thread_msg will be assigned the same value as gu_msg.<br>
227    * If gu_thread_msg is <b>null</b> and gu_parent_msg is not <b>null</b> then gu_thread_msg will be assigned the same the parent message thread.<br>
228    * If id_status is <b>null</b> then it will be assigned to NewsMessage.STATUS_PENDING.<br>
229    * If id_msg_type is <b>null</b> then it will be assigned to "TXT" by default.<br>
230    * If dt_start is <b>null</b> then message visibility will start inmediately.<br>
231    * If dt_end is <b>null</b> then message will never expire.<br>
232    * dt_published will always be set to the currents system date no matter with values it is passed as parameter.<br>
233    * nu_thread_msgs will be updated in all messages from this thread by calling k_sp_count_thread_msgs stored procedure.<br>
234    * Column k_newsgroups.dt_last_update is automatically set to the current date each time a new message is stored.
235    * @param oConn Database Connection
236    * @throws SQLException
237    */

238   public boolean store(JDCConnection oConn) throws SQLException JavaDoc {
239     boolean bNewMsg;
240     boolean bRetVal;
241     String JavaDoc sMsgId;
242     int nThreadMsgs;
243     ResultSet JavaDoc oRSet;
244     Statement JavaDoc oStmt;
245     CallableStatement JavaDoc oCall;
246     String JavaDoc sSQL;
247
248     Timestamp JavaDoc dtNow = new Timestamp JavaDoc(DBBind.getTime());
249
250     if (DebugFile.trace) {
251       DebugFile.writeln("Begin NewsMessage.store([Connection])");
252       DebugFile.incIdent();
253     }
254
255     // Si no se especificó un identificador para el mensaje, entonces añadirlo automáticamente
256
if (!AllVals.containsKey(DB.gu_msg)) {
257       bNewMsg = true;
258       sMsgId = Gadgets.generateUUID();
259       put(DB.gu_msg, sMsgId);
260     }
261     else {
262       bNewMsg = false;
263       sMsgId = getString(DB.gu_msg);
264     }
265
266     if (!AllVals.containsKey(DB.id_status))
267       put(DB.id_status, STATUS_PENDING);
268
269     if (!AllVals.containsKey(DB.gu_thread_msg))
270       if (AllVals.containsKey(DB.gu_parent_msg)) {
271         oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
272
273         if (DebugFile.trace) DebugFile.writeln("Statement.executeQuery(SELECT " + DB.gu_thread_msg + " FROM " + DB.k_newsmsgs + " WHERE " + DB.gu_msg + "='" + getStringNull(DB.gu_parent_msg, "null") + "'");
274
275         oRSet = oStmt.executeQuery("SELECT " + DB.gu_thread_msg + " FROM " + DB.k_newsmsgs + " WHERE " + DB.gu_msg + "='" + getString(DB.gu_parent_msg) + "'");
276         if (oRSet.next())
277           put (DB.gu_thread_msg, oRSet.getString(1));
278         else
279           put (DB.gu_thread_msg, sMsgId);
280         oRSet.close();
281         oStmt.close();
282       }
283       else
284         put (DB.gu_thread_msg, sMsgId);
285
286     if (oConn.getDataBaseProduct()==JDCConnection.DBMS_POSTGRESQL) {
287         sSQL = "SELECT k_sp_count_thread_msgs ('" + getString(DB.gu_thread_msg) + "')";
288
289         oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
290
291         if (DebugFile.trace) DebugFile.writeln("Statement.executeQuery(" + sSQL + ")");
292
293         oRSet = oStmt.executeQuery(sSQL);
294         oRSet.next();
295         nThreadMsgs = oRSet.getInt(1);
296         oRSet.close();
297         oStmt.close();
298     }
299     else {
300         sSQL = "{call k_sp_count_thread_msgs(?,?)}";
301         if (DebugFile.trace) DebugFile.writeln("CallableStatement.prepareCall(" + sSQL + ")");
302         oCall = oConn.prepareCall(sSQL);
303         oCall.setString(1, getString(DB.gu_thread_msg));
304         oCall.registerOutParameter(2, Types.INTEGER);
305         oCall.execute();
306         nThreadMsgs = oCall.getInt(2);
307         oCall.close();
308     }
309
310     replace(DB.nu_thread_msgs, ++nThreadMsgs);
311
312     if (!AllVals.containsKey(DB.dt_start))
313       put(DB.dt_start, dtNow);
314
315     if (!AllVals.containsKey(DB.id_msg_type))
316       put(DB.id_msg_type, "TXT");
317
318     replace(DB.dt_published, dtNow);
319
320     bRetVal = super.store(oConn);
321
322     oStmt = oConn.createStatement();
323     sSQL = "UPDATE " + DB.k_newsmsgs + " SET " + DB.nu_thread_msgs + "=" + String.valueOf(nThreadMsgs) + " WHERE " + DB.gu_thread_msg + "='" + getString(DB.gu_thread_msg) + "'";
324     if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate(" + sSQL + ")");
325     oStmt.executeUpdate(sSQL);
326     oStmt.close();
327
328     if (!AllVals.containsKey(DB.gu_newsgrp) && !sMsgId.equals(get (DB.gu_thread_msg))) {
329
330       sSQL = "SELECT " + DB.gu_category + " FROM " + DB.k_x_cat_objs + " WHERE " + DB.gu_object + "='" + getStringNull(DB.gu_thread_msg, "null") + "'";
331
332       oStmt = oConn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
333
334       if (DebugFile.trace) DebugFile.writeln("Statement.executeQuery(" + sSQL + ")");
335
336       oRSet = oStmt.executeQuery(sSQL);
337
338       if (oRSet.next())
339         put (DB.gu_newsgrp, oRSet.getString(1));
340
341       oRSet.close();
342       oStmt.close();
343     }
344
345     if (bRetVal && AllVals.containsKey(DB.gu_newsgrp)) {
346       if (DebugFile.trace) DebugFile.writeln("Category.store() && containsKey(DB.gu_newsgrp)");
347
348       if (bNewMsg) {
349
350         if (DebugFile.trace) DebugFile.writeln("new message");
351
352         // Check whether or not dt_last_update column exists for backward compatibility with 1.x versions
353
boolean bHasLastUpdate;
354         try {
355           bHasLastUpdate = (((DBBind) (oConn.getPool().getDatabaseBinding())).getDBTable(DB.k_newsgroups).getColumnByName(DB.dt_last_update)!=null);
356         } catch (NullPointerException JavaDoc npe) { bHasLastUpdate = true; }
357
358         if (bHasLastUpdate) {
359           PreparedStatement JavaDoc oUpdt = null;
360           sSQL = "UPDATE " + DB.k_newsgroups + " SET " + DB.dt_last_update + "=? WHERE " + DB.gu_newsgrp + "=?";
361
362           if (DebugFile.trace) DebugFile.writeln("Connection.prepareStatement (" + sSQL + ")");
363
364           oUpdt = oConn.prepareStatement(sSQL);
365           oUpdt.setTimestamp(1, new Timestamp JavaDoc(new Date JavaDoc().getTime()));
366           oUpdt.setObject(2, AllVals.get(DB.gu_newsgrp), java.sql.Types.VARCHAR);
367           oUpdt.executeUpdate();
368           oUpdt.close();
369           oUpdt = null;
370         } // fi (bHasLastUpdate)
371
}
372       else {
373         sSQL = "DELETE FROM " + DB.k_x_cat_objs + " WHERE " + DB.gu_category + "='" + getString(DB.gu_newsgrp) + "' AND " + DB.gu_object + "='" + sMsgId + "'";
374         oStmt = oConn.createStatement();
375         if (DebugFile.trace) DebugFile.writeln("Statement.execute(" + sSQL + ")");
376         oStmt.execute(sSQL);
377         oStmt.close();
378       } // fi (!bNewMsg)
379

380       sSQL = "INSERT INTO " + DB.k_x_cat_objs + "(" + DB.gu_category + "," + DB.gu_object + "," + DB.id_class + "," + DB.bi_attribs + "," + DB.od_position + ") VALUES ('" + getString(DB.gu_newsgrp) + "','" + sMsgId + "'," + String.valueOf(NewsMessage.ClassId) + ",0,NULL)";
381       oStmt = oConn.createStatement();
382       if (DebugFile.trace) DebugFile.writeln("Statement.execute(" + sSQL + ")");
383       oStmt.execute(sSQL);
384       oStmt.close();
385     } // fi (bRetVal && containsKey(gu_newsgrp))
386

387     if (DebugFile.trace) {
388       DebugFile.decIdent();
389       DebugFile.writeln("End NewsMessage.store() : " + String.valueOf(bRetVal));
390     }
391
392     return bRetVal;
393   } // store
394

395   // ----------------------------------------------------------
396

397   /**
398    * <p>Delete NewsMessage.</p>
399    * Files attached to NewsMessage (stored as Products) are delete prior to
400    * the NewsMessage itself. Then k_sp_del_newsmsg stored procedure is called.
401    * @param oConn Database Connection
402    * @throws SQLException
403    */

404   public boolean delete(JDCConnection oConn) throws SQLException JavaDoc {
405     Product oProd;
406     Statement JavaDoc oStmt;
407     CallableStatement JavaDoc oCall;
408     String JavaDoc sSQL;
409
410     if (DebugFile.trace) {
411       DebugFile.writeln("Begin NewsMessage.delete([Connection])");
412       DebugFile.incIdent();
413       DebugFile.writeln("gu_msg=" + getStringNull(DB.gu_msg,"null"));
414     }
415
416     if (!isNull(DB.gu_product)) {
417       oProd = new Product(oConn, getString(DB.gu_product));
418
419       oStmt = oConn.createStatement();
420       sSQL = "UPDATE " + DB.k_newsmsgs + " SET " + DB.gu_product + "=NULL WHERE " + DB.gu_msg + "='" + getString(DB.gu_msg) + "'";
421       if (DebugFile.trace) DebugFile.writeln("Statement.executeUpdate(" + sSQL + ")");
422       oStmt.executeUpdate(sSQL);
423       oStmt.close();
424
425       oProd.delete(oConn);
426
427       remove(DB.gu_product);
428     } // fi
429

430     sSQL = "{ call k_sp_del_newsmsg ('" + getString(DB.gu_msg) + "') }";
431     if (DebugFile.trace) DebugFile.writeln("Connection.prepareCall(" + sSQL + ")");
432     oCall = oConn.prepareCall(sSQL);
433     oCall.execute();
434     oCall.close();
435
436     if (DebugFile.trace) {
437       DebugFile.decIdent();
438       DebugFile.writeln("End NewsMessage.delete() : true");
439     }
440
441     return true;
442   } // delete
443

444   // **********************************************************
445
// Static Methods
446

447   /**
448    * <p>Delete NewsMessage.</p>
449    * Files attached to NewsMessage (stored as Products) are delete prior to
450    * the NewsMessage itself. Then k_sp_del_newsmsg stored procedure is called.
451    * @param oConn Database Connection
452    * @param sNewsMsgGUID GUID of NewsMessage to be deleted
453    * @throws SQLException
454    */

455   public static boolean delete(JDCConnection oConn, String JavaDoc sNewsMsgGUID) throws SQLException JavaDoc {
456     NewsMessage oMsg = new NewsMessage();
457
458     if (oMsg.load(oConn, new Object JavaDoc[]{sNewsMsgGUID}))
459       return oMsg.delete(oConn);
460     else
461       return false;
462   } // delete
463

464   // **********************************************************
465
// Constantes Publicas
466

467    public static final short STATUS_VALIDATED = 0;
468    public static final short STATUS_PENDING = 1;
469    public static final short STATUS_DISCARDED = 2;
470    public static final short STATUS_EXPIRED = 3;
471
472    public static final short ClassId = 31;
473
474 }
475
Popular Tags