KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > audit > JahiaDBAuditLogManagerService


1 /*
2  * ____.
3  * __/\ ______| |__/\. _______
4  * __ .____| | \ | +----+ \
5  * _______| /--| | | - \ _ | : - \_________
6  * \\______: :---| : : | : | \________>
7  * |__\---\_____________:______: :____|____:_____\
8  * /_____|
9  *
10  * . . . i n j a h i a w e t r u s t . . .
11  *
12  *
13  *
14  * ----- BEGIN LICENSE BLOCK -----
15  * Version: JCSL 1.0
16  *
17  * The contents of this file are subject to the Jahia Community Source License
18  * 1.0 or later (the "License"); you may not use this file except in
19  * compliance with the License. You may obtain a copy of the License at
20  * http://www.jahia.org/license
21  *
22  * Software distributed under the License is distributed on an "AS IS" basis,
23  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
24  * for the rights, obligations and limitations governing use of the contents
25  * of the file. The Original and Upgraded Code is the Jahia CMS and Portal
26  * Server. The developer of the Original and Upgraded Code is JAHIA Ltd. JAHIA
27  * Ltd. owns the copyrights in the portions it created. All Rights Reserved.
28  *
29  * The Shared Modifications are Jahia View Helper.
30  *
31  * The Developer of the Shared Modifications is Jahia Solution S�rl.
32  * Portions created by the Initial Developer are Copyright (C) 2002 by the
33  * Initial Developer. All Rights Reserved.
34  *
35  * Contributor(s):
36  * 22-AUG-2003, Jahia Solutions Sarl, Fulco Houkes
37  *
38  * ----- END LICENSE BLOCK -----
39  */

40
41
42 package org.jahia.services.audit;
43
44 import java.sql.Connection JavaDoc;
45 import java.sql.ResultSet JavaDoc;
46 import java.sql.SQLException JavaDoc;
47 import java.sql.Statement JavaDoc;
48 import java.text.DateFormat JavaDoc;
49 import java.util.ArrayList JavaDoc;
50 import java.util.HashMap JavaDoc;
51 import java.util.HashSet JavaDoc;
52 import java.util.List JavaDoc;
53 import java.util.Set JavaDoc;
54 import java.util.Vector JavaDoc;
55
56 import org.jahia.data.JahiaDBDOMObject;
57 import org.jahia.data.JahiaDOMObject;
58 import org.jahia.data.containers.JahiaContainer;
59 import org.jahia.data.containers.JahiaContainerList;
60 import org.jahia.data.events.JahiaEvent;
61 import org.jahia.data.fields.JahiaField;
62 import org.jahia.exceptions.JahiaException;
63 import org.jahia.params.ParamBean;
64 import org.jahia.registries.ServicesRegistry;
65 import org.jahia.services.database.JahiaIncrementorsDBService;
66 import org.jahia.services.pages.JahiaPage;
67 import org.jahia.services.pages.JahiaPageDefinition;
68 import org.jahia.services.sites.JahiaSite;
69 import org.jahia.services.usermanager.JahiaUser;
70 import org.jahia.settings.SettingsBean;
71 import org.jahia.utils.JahiaObjectTool;
72
73
74 public class JahiaDBAuditLogManagerService extends JahiaAuditLogManagerService {
75
76     private static org.apache.log4j.Logger logger =
77             org.apache.log4j.Logger.getLogger (JahiaDBAuditLogManagerService.class);
78
79     public static final String JavaDoc TABLE_NAME = "jahia_audit_log";
80     public static final int FIELD_TYPE = JahiaObjectTool.FIELD_TYPE;
81     public static final int CONTAINER_TYPE = JahiaObjectTool.CONTAINER_TYPE;
82     public static final int CONTAINERLIST_TYPE = JahiaObjectTool.CONTAINERLIST_TYPE;
83     public static final int PAGE_TYPE = JahiaObjectTool.PAGE_TYPE;
84     public static final int TEMPLATE_TYPE = JahiaObjectTool.TEMPLATE_TYPE;
85     public static final int ACL_TYPE = JahiaObjectTool.ACL_TYPE;
86
87     public static final String JavaDoc ENTRY_ID = "ENTRY_ID";
88     public static final String JavaDoc TIME = "TIME";
89     public static final String JavaDoc USER_ID = "USER_ID";
90     public static final String JavaDoc OBJECT_TYPE = "OBJECT_TYPE";
91     public static final String JavaDoc OBJECT_ID = "OBJECT_ID";
92     public static final String JavaDoc CONTENT = "CONTENT";
93
94     private static final String JavaDoc MSG_INTERNAL_ERROR = new String JavaDoc ("Audit Log Manager internal error");
95     private static final String JavaDoc JSP_FILE = "/jsp/jahia/engines/logs/viewlogs.jsp";
96
97
98     private static JahiaDBAuditLogManagerService instance = null;
99     private JahiaIncrementorsDBService mIncrementorService = null;
100
101     private int maxLogs;
102
103
104     /**
105      * constructor
106      * initializes database connection pool and incrementor service.
107      *
108      */

109     private JahiaDBAuditLogManagerService ()
110             throws JahiaException {
111         logger.info ("***** Starting AuditLogManager *****");
112
113         // Try to get the DB Pool Service
114
ServicesRegistry registry = ServicesRegistry.getInstance ();
115         if (registry != null) {
116             mIncrementorService = registry.getJahiaIncrementorsDBService ();
117             if (mIncrementorService == null) {
118                 throw new JahiaException (MSG_INTERNAL_ERROR, "Audit Log manager could not get the Incrementors DB Service instance.",
119                         JahiaException.SERVICE_ERROR, JahiaException.CRITICAL_SEVERITY);
120             }
121
122         } else {
123             throw new JahiaException (MSG_INTERNAL_ERROR, "Audit Log manager could not get the Service Registry instance.",
124                     JahiaException.REGISTRY_ERROR, JahiaException.CRITICAL_SEVERITY);
125         }
126     } // end constructor
127

128
129     /**
130      * returns a single instance of the object
131      */

132     public static synchronized JahiaDBAuditLogManagerService getInstance ()
133             throws JahiaException {
134         if (instance == null) {
135             instance = new JahiaDBAuditLogManagerService ();
136         }
137         return instance;
138     }
139
140
141     /**
142      * standard access method to log an Event
143      *
144      * @author Mikha�l Janson
145      * @param je a reference to the JahiaEvent object to log
146      * @param objectType an <code>int</code> representing the type of the of the logged event
147      * @param operationStr a <code>String</code> containing the message logged with the event
148      */

149     public boolean logEvent (JahiaEvent je, int objectType, String JavaDoc operationStr) {
150         long time;
151         String JavaDoc timeStr = "";
152         String JavaDoc userNameStr = "jahia";
153         String JavaDoc objTypeStr = "";
154         String JavaDoc objIDStr = "0";
155         String JavaDoc parentObjIDStr = "0";
156         String JavaDoc parentObjTypeStr = "";
157         String JavaDoc siteKey = "";
158         String JavaDoc contentStr = "";
159
160         // Get the next available entry ID
161
int entryID;
162         try {
163             entryID = mIncrementorService.autoIncrement ("jahia_audit_log");
164             // toConsole ("got new entry ID = ["+Integer.toString(entryID)+"]");
165
} catch (JahiaException ex) {
166             logger.debug ("Exception !!! Could not get a new entry ID from the incrementor DB");
167             return false;
168         }
169
170         try {
171             time = je.getEventTime ();
172             timeStr = new Long JavaDoc (je.getEventTime ()).toString ();
173             ParamBean jParams = je.getParams ();
174             if (jParams != null) { // jParams is null in Event if generated by Jahia
175
userNameStr = (String JavaDoc)jParams.getUser ().getUsername ();
176                 JahiaSite site = (JahiaSite)jParams.getSession ().getAttribute (ParamBean.SESSION_SITE);
177                 if (site != null) {
178                     siteKey = site.getSiteKey ();
179                 }
180                 objTypeStr = new Integer JavaDoc (objectType).toString ();
181                 objIDStr = Integer.toString (getObjectID (je, objectType));
182                 String JavaDoc[] parent = getParent (je, objectType);
183                 parentObjIDStr = parent[0];
184                 parentObjTypeStr = parent[1];
185                 contentStr = JahiaObjectTool.getInstance ().getObjectName (objectType, getObjectID (je, objectType), jParams);
186
187                 return insertAuditLogEntry (entryID, timeStr, userNameStr, objTypeStr, objIDStr, parentObjIDStr, parentObjTypeStr, siteKey, operationStr, contentStr);
188             }
189             return false;
190         } catch (JahiaException jex) {
191             return false;
192         }
193     } // end logEvent
194

195
196     /**
197      * utility method to retrieve log entries for a specific object type and ID
198      *
199      * @author Mikha�l Janson
200      * @param objectType an <code>int</code> representing the object type to retrieve
201      * @param objectID an <code>int</code> representing the ID of the object to retrieve logs for
202      * @return a <code>List</code> of HashMaps containing keys for time, username, operation, and their value for each logged event
203      */

204     public ArrayList JavaDoc getLog (int objectType, int objectID, ParamBean jParams) {
205         ArrayList JavaDoc logData = new ArrayList JavaDoc ();
206
207         // Get a database connection
208
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
209         if (dbConn == null) {
210             return logData;
211         }
212
213         // Have the recursive method descend down the tree
214
List JavaDoc childrenObjectList = getAllChildren (dbConn, objectType, objectID, null);
215
216         // fetch the corresponding entries from the db table
217
Statement JavaDoc stmt = null;
218         StringBuffer JavaDoc query = null;
219
220         try {
221             stmt = dbConn.createStatement ();
222             query = new StringBuffer JavaDoc("SELECT * FROM " + TABLE_NAME);
223             query.append(" WHERE (objecttype_jahia_audit_log=");
224             query.append(Integer.toString (objectType));
225             query.append(" AND objectid_jahia_audit_log=");
226             query.append(Integer.toString (objectID));
227             query.append(")");
228             if (!childrenObjectList.isEmpty ()) {
229                 for (int i = 0; i < childrenObjectList.size (); i++) {
230                     Integer JavaDoc[] thisChildObject = (Integer JavaDoc[])childrenObjectList.get (i);
231                     query.append(" OR (objecttype_jahia_audit_log=");
232                     query.append(thisChildObject[0].toString ());// type as 1st ary elt
233
query.append(" AND objectid_jahia_audit_log=");
234                     query.append(thisChildObject[1].toString ()); // id as 2nd ary elt
235
query.append(")");
236                 }
237             }
238             query.append(" ORDER BY time_jahia_audit_log DESC");
239             logger.debug("querySize=" + query.length() + " bytes");
240
241             ResultSet JavaDoc rs = stmt.executeQuery (query.toString());
242             logData = buildLogEntriesList (rs, logData, jParams);
243         } catch (SQLException JavaDoc sqlEx) {
244             logger.debug ("SQL Exception occurred!" + sqlEx.getMessage () + " for query " + query);
245         } finally {
246
247             CloseStatement (stmt);
248         }
249         return logData;
250     } // end getLog
251

252
253     /**
254      * utility method to retrieve all log entries
255      *
256      * @author Mikha�l Janson
257      * @return a <code>List</code> of HashMaps containing keys for time, username,
258      * operation, and their value for each logged event
259      */

260     public ArrayList JavaDoc getLog (ParamBean jParams) {
261         ArrayList JavaDoc logData = new ArrayList JavaDoc ();
262         // Get a database connection
263
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
264         if (dbConn == null) {
265             return logData;
266         }
267
268         // fetch the corresponding entries from the db table
269
Statement JavaDoc stmt = null;
270         String JavaDoc query = "";
271         String JavaDoc maxLogs = SettingsBean.readJahiaPropertiesFile ().getProperty ("jahiaMaxLogs");
272
273         try {
274             stmt = dbConn.createStatement ();
275             query = "SELECT * FROM " + TABLE_NAME + " ORDER BY time_jahia_audit_log DESC";
276             ResultSet JavaDoc rs = stmt.executeQuery (query);
277             logData = buildLogEntriesList (rs, logData, jParams);
278         } catch (SQLException JavaDoc sqlEx) {
279             logger.debug ("SQL Exception occurred!" + sqlEx.getMessage () + " for query " + query);
280         } finally {
281
282             CloseStatement (stmt);
283         }
284         return logData;
285     } // end getLog
286

287
288     /**
289      * utility method to convert a ResultSet into a List suitable for log display
290      *
291      * @author Mikha�l Janson
292      * @param rs a <code>ResultSet</code>
293      * @param logData an pre-initialized ArrayList
294      * @return an <code>ArrayList</code> suitable for log display
295      */

296     private ArrayList JavaDoc buildLogEntriesList (ResultSet JavaDoc rs, ArrayList JavaDoc logData, ParamBean jParams) {
297         int i = 0;
298
299         try {
300             while (rs.next ()) {
301                 int jahiaID = rs.getInt ("id_jahia_audit_log");
302                 String JavaDoc time = rs.getString ("time_jahia_audit_log");
303                 String JavaDoc username = rs.getString ("username_jahia_audit_log");
304                 String JavaDoc operation = rs.getString ("operation_jahia_audit_log");
305                 int objtype = rs.getInt ("objecttype_jahia_audit_log");
306                 int objid = rs.getInt ("objectid_jahia_audit_log");
307                 String JavaDoc sitekey = rs.getString ("site_jahia_audit_log");
308                 String JavaDoc objname = rs.getString ("content_jahia_audit_log");
309
310                 // get a human-readable data format
311
long myTime = Long.parseLong (time);
312                 java.util.Date JavaDoc myDate = new java.util.Date JavaDoc (myTime);
313                 time = DateFormat.getDateTimeInstance (3, 3).format (myDate);
314
315                 // get the object full name
316
try {
317                     JahiaObjectTool theInstance = JahiaObjectTool.getInstance ();
318
319                     // String mytest = theInstance.getObjectName (objtype, objid, jParams);
320

321                     objname = JahiaObjectTool.getInstance ().getObjectName (objtype, objid, jParams);
322                 } catch (Exception JavaDoc e) {
323                     // do nothing... keep existing objname
324
}
325
326                 HashMap JavaDoc record = new HashMap JavaDoc ();
327                 record.put ("timeStr", time);
328                 record.put ("username", username);
329                 record.put ("operation", operation);
330                 record.put ("objecttype", Integer.toString (objtype));
331                 record.put ("objectid", Integer.toString (objid));
332                 record.put ("sitekey", sitekey);
333                 record.put ("objectname", objname);
334
335                 logData.add (i, record);
336                 i++;
337             }
338         } catch (SQLException JavaDoc sqlEx) {
339             // do nothing
340
}
341         return logData;
342     } // end buildLogEntriesList
343

344
345     /**
346      * utility method to flush log entries for a specific object type and ID
347      *
348      * @author Mikha�l Janson
349      * @param flushItems an <code>ArrayList</code> of <code>Integer[2]</code> arrays
350      * with objectType in position 0 and objectID in position 1.
351      * @return the number of rows deleted, as an <code>int</code>
352      */

353     public int flushLogs (int objectType, int objectID, ParamBean jParams) {
354
355         // Get a database connection
356
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
357         if (dbConn == null) {
358             return 0;
359         }
360
361         Vector JavaDoc flushItems = getAllChildren (dbConn, objectType, objectID, null);
362         int result = 0;
363         Statement JavaDoc stmt = null;
364         String JavaDoc query = "";
365
366         try {
367             stmt = dbConn.createStatement ();
368
369             // build the query
370
query = "DELETE FROM " + TABLE_NAME + " WHERE ";
371             query += "(objecttype_jahia_audit_log=" + Integer.toString (objectType); // put me in too !
372
query += " AND objectid_jahia_audit_log=" + Integer.toString (objectID) + ")"; // (along with my children)
373
for (int i = 0; i < flushItems.size (); i++) { // loop on item list
374
Integer JavaDoc[] row = (Integer JavaDoc[])flushItems.get (i);
375                 query += " OR (objecttype_jahia_audit_log=" + row[0].toString (); // 1st ary elt is objectType
376
query += " AND objectid_jahia_audit_log=" + row[1].toString () + ")"; // 2nd ary elt is objectID
377
}
378
379             // delete the entries
380
result = stmt.executeUpdate (query);
381
382             if (result > 0) {
383
384                 // if flush succeeded, log the flush itself ;o)
385
// Get the next available entry ID
386
int entryID;
387                 try {
388                     entryID = mIncrementorService.autoIncrement ("jahia_audit_log");
389                     logger.debug ("got new entry ID = [" + Integer.toString (entryID) + "]");
390                 } catch (JahiaException ex) {
391                     logger.debug ("Exception !!! Could not get a new entry ID from the incrementor DB");
392                     return result;
393                 }
394                 String JavaDoc timeStr = Long.toString ((new java.util.Date JavaDoc ()).getTime ());
395                 String JavaDoc userNameStr = (String JavaDoc)jParams.getUser ().getUsername ();
396                 String JavaDoc objectTypeStr = Integer.toString (objectType);
397                 String JavaDoc objectIDStr = Integer.toString (objectID);
398                 String JavaDoc siteKey = "";
399                 String JavaDoc operationStr = "flushed logs ";
400
401                 // looks nicer with the name of the objecttype the logs are flushed for
402
try {
403                     operationStr += JahiaObjectTool.getInstance ().getObjectTypeName (objectType);
404                     siteKey = ((JahiaSite)jParams.getSession ().getAttribute (ParamBean.SESSION_SITE)).getSiteKey ();
405                 } catch (JahiaException je) {
406                     ;// do nothing... keep existing operationStr
407
}
408 // try {
409
// siteKey = ((JahiaSite)jParams.getSession().getAttribute(ParamBean.SESSION_SITE)).getSiteKey();
410
// } catch (JahiaSessionExpirationException jsee ) {
411
// ;
412
// }
413
insertAuditLogEntry (entryID, timeStr, userNameStr, objectTypeStr, objectIDStr, "0", "0", siteKey, operationStr, "");
414             }
415         } catch (SQLException JavaDoc sqlEx) {
416             logger.debug ("SQL Exception occured!" + sqlEx.getMessage ());
417         } finally {
418
419             CloseStatement (stmt);
420         }
421         return result;
422     } // end flushLogs
423

424
425     /**
426      * overloaded method to flush all log entries older than a given number of days
427      *
428      * @author Mikha�l Janson
429      * @param theUser a reference to the JahiaUser object representing the user requesting the flush
430      * @param maxlogsdays the number of days to keep existing log entries for
431      * @return true on success, false otherwise
432      */

433     public boolean flushLogs (JahiaUser theUser, Integer JavaDoc maxlogsdays) {
434
435         String JavaDoc oldestEntryTime = "999999999999999";
436
437         // Get a database connection
438
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
439         if (dbConn == null) {
440             return false;
441         }
442         Statement JavaDoc stmt = null;
443         String JavaDoc query = "";
444
445
446         if (maxlogsdays != null) {
447             oldestEntryTime = Long.toString (System.currentTimeMillis () - (maxlogsdays.intValue () * 86400000));
448             oldestEntryTime = padTimeString (oldestEntryTime);
449         }
450
451         try {
452
453             stmt = dbConn.createStatement ();
454
455             // build the query
456
query = "DELETE FROM " + TABLE_NAME;
457             query += " WHERE time_jahia_audit_log<" + "'" + oldestEntryTime + "'";
458
459             // delete the entries
460
stmt.executeUpdate (query);
461
462             // check if there are any older records left in the table
463
query = "SELECT id_jahia_audit_log FROM " + TABLE_NAME;
464             query += " WHERE time_jahia_audit_log<" + "'" + oldestEntryTime + "'";
465
466             ResultSet JavaDoc rs = stmt.executeQuery (query);
467
468             // log the flush itself if it succeeded
469
if (!rs.next ()) {
470
471                 // Get the next available entry ID
472
int entryID;
473                 try {
474                     entryID = mIncrementorService.autoIncrement ("jahia_audit_log");
475                     logger.debug ("got new entry ID = [" + Integer.toString (entryID) + "]");
476                 } catch (JahiaException ex) {
477                     logger.debug ("Exception !!! Could not get a new entry ID from the incrementor DB");
478                     return false;
479                 }
480                 String JavaDoc timeStr = Long.toString ((new java.util.Date JavaDoc ()).getTime ());
481                 String JavaDoc userNameStr = theUser.getUsername ();
482                 String JavaDoc objectTypeStr = Integer.toString (JahiaObjectTool.SERVER_TYPE);
483                 String JavaDoc objectIDStr = "0";
484                 String JavaDoc operationStr = "";
485                 if (maxlogsdays != null) {
486                     operationStr = "flushed logs > " + maxlogsdays + " days";
487                 } else {
488                     operationStr = "flushed all logs ";
489                 }
490
491                 insertAuditLogEntry (entryID, timeStr, userNameStr, objectTypeStr, objectIDStr, "0", "0", "", operationStr, "");
492
493             }
494         } catch (SQLException JavaDoc sqlEx) {
495             logger.debug ("An SQL Exception occurred: " + sqlEx.getMessage ());
496         } finally {
497
498             CloseStatement (stmt);
499         }
500         return true;
501     } // end flushLogs ( user, maxlogsdays )
502

503
504     /**
505      * utility method to flush all log entries of a site
506      *
507      * @author Mikha�l Janson
508      * @param theUser a reference to the JahiaUser object representing the administrator user requesting the flush
509      * @return true on success, false on any error
510      */

511     public boolean flushSiteLogs (JahiaUser theUser, String JavaDoc siteKey) {
512
513
514         // Get a database connection
515
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
516         if (dbConn == null) {
517             return false;
518         }
519         Statement JavaDoc stmt = null;
520         String JavaDoc query = "";
521
522
523         try {
524             stmt = dbConn.createStatement ();
525             // build the query
526
query = "DELETE FROM " + TABLE_NAME + " WHERE site_jahia_audit_log='" + siteKey + "'";
527             // delete the entries
528
stmt.executeUpdate (query);
529         } catch (SQLException JavaDoc sqlEx) {
530             logger.debug ("SQL Exception occured!" + sqlEx.getMessage ());
531         } finally {
532
533             CloseStatement (stmt);
534         }
535         return true;
536     } // end flushSiteLogs ( user, siteID )
537

538
539     /**
540      * write a log entry to the database
541      *
542      * @author Mikha�l Janson
543      * @param entryID
544      * @param time
545      * @param userNameStr
546      * @param objectTypeStr
547      * @param objectIDStr
548      * @param operationStr
549      * @param contentStr
550      */

551     private boolean insertAuditLogEntry (int entryID,
552                                          String JavaDoc timeStr,
553                                          String JavaDoc userNameStr,
554                                          String JavaDoc objectTypeStr,
555                                          String JavaDoc objectIDStr,
556                                          String JavaDoc parentObjIDStr,
557                                          String JavaDoc parentTypeStr,
558                                          String JavaDoc siteKey,
559                                          String JavaDoc operationStr,
560                                          String JavaDoc contentStr) {
561         // Get a database connection
562
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
563         if (dbConn == null) {
564             return false;
565         }
566         // set default values
567
int maxLogs = 500;
568         int numRows = 0;
569         boolean result = true;
570         Statement JavaDoc statement = null;
571         String JavaDoc query = "";
572
573
574         // Milliseconds time is stored as text in the database.
575
// To ensure correct sorting, force the string length to 15 positions,
576
// padding it with initial "0"s if needed.
577
timeStr = padTimeString (timeStr);
578
579         try {
580             statement = dbConn.createStatement ();
581
582             // check if we want to FIFO old entries
583
maxLogs = Integer.parseInt (SettingsBean.readJahiaPropertiesFile ().getProperty ("jahiaMaxLogs"));
584             query = "SELECT COUNT(*) AS numRows FROM " + TABLE_NAME;
585             ResultSet JavaDoc rs = statement.executeQuery (query);
586             if (rs.next ()) {
587                 numRows = rs.getInt ("numRows");
588             }
589
590             if ((numRows + 1) > maxLogs) {
591                 deleteOldestRow ();
592             }
593
594             // insert current entry
595
query = "INSERT INTO " + TABLE_NAME + " (id_jahia_audit_log, time_jahia_audit_log, username_jahia_audit_log, objecttype_jahia_audit_log, operation_jahia_audit_log, objectid_jahia_audit_log, parentid_jahia_audit_log, parenttype_jahia_audit_log, site_jahia_audit_log, content_jahia_audit_log ) VALUES ("
596                     + Integer.toString (entryID)
597                     + ",'" + timeStr
598                     + "','" + userNameStr
599                     + "'," + objectTypeStr
600                     + ",'" + operationStr
601                     + "'," + objectIDStr
602                     + "," + parentObjIDStr
603                     + "," + parentTypeStr
604                     + ",'" + siteKey
605                     + "','" + contentStr + "')";
606
607             statement.executeUpdate (query);
608         } catch (SQLException JavaDoc sqlEx) {
609             logger.debug ("SQL Exception occured!" + sqlEx.getMessage ());
610             result = false;
611         } catch (NumberFormatException JavaDoc nfe) {
612             // do nothing, keep default maxLogs
613
} finally {
614
615             CloseStatement (statement);
616         }
617         return result;
618     }
619
620
621     /**
622      * get the object ID for an Event to be logged, according to the object type
623      *
624      * @author Mikha�l Janson
625      * @param je a reference to the JahiaEvent object to log
626      * @param objectType an <code>int</code> representing the type of the of the logged event
627      * @return the objectID, as an <code>int</code>
628      */

629     private int getObjectID (JahiaEvent je, int objectType)
630             throws JahiaException {
631         try {
632             switch (objectType) {
633
634                 case FIELD_TYPE:
635                     return ((JahiaField)je.getObject ()).getID ();
636                 case CONTAINER_TYPE:
637                     return ((JahiaContainer)je.getObject ()).getID ();
638                 case CONTAINERLIST_TYPE:
639                     return ((JahiaContainerList)je.getObject ()).getID ();
640                 case PAGE_TYPE:
641                     return ((JahiaPage)je.getObject ()).getID ();
642                 case TEMPLATE_TYPE:
643                     return ((JahiaPageDefinition)je.getObject ()).getID ();
644                 default:
645                     throw new JahiaException (MSG_INTERNAL_ERROR,
646                             "Incompatible Object Type passed to JahiaAuditLogManager",
647                             JahiaException.SERVICE_ERROR,
648                             JahiaException.CRITICAL_SEVERITY);
649             }
650         } catch (Exception JavaDoc e) {
651             logger.debug ("EXCEPTION MESSAGE :" + e.getMessage ());
652             throw new JahiaException (MSG_INTERNAL_ERROR,
653                     "Exception occurred while retrieving Event Object ID",
654                     JahiaException.SERVICE_ERROR,
655                     JahiaException.CRITICAL_SEVERITY);
656         }
657     } // end getObjectID
658

659
660     /**
661      * get object ID Type for the parent object, by the objectID of a child
662      *
663      * @author Mikha�l Janson
664      * @param je a reference to the JahiaEvent object to log
665      * @param objectType an <code>int</code> representing the type of the of the logged event
666      * @return the objectID, as a <code>String</code>
667      */

668     private String JavaDoc[] getParent (JahiaEvent je, int objectType)
669             throws JahiaException {
670         String JavaDoc[] parent = new String JavaDoc[2];
671         try {
672             switch (objectType) {
673
674                 case FIELD_TYPE:
675                     if (((JahiaField)je.getObject ()).getctnid () == 0) {
676                         parent[0] = Integer.toString (((JahiaField)je.getObject ()).getPageID ());
677                         parent[1] = Integer.toString (PAGE_TYPE);
678                         return parent;
679                     } else {
680                         parent[0] = Integer.toString (((JahiaField)je.getObject ()).getctnid ());
681                         parent[1] = Integer.toString (CONTAINER_TYPE);
682                         return parent;
683                     }
684
685                 case CONTAINER_TYPE:
686                     parent[0] = Integer.toString (((JahiaContainer)je.getObject ()).getListID ());
687                     parent[1] = Integer.toString (CONTAINERLIST_TYPE);
688                     return parent;
689
690                 case CONTAINERLIST_TYPE:
691                     if (((JahiaContainerList)je.getObject ()).getParentEntryID () == 0) {
692                         parent[0] = Integer.toString (((JahiaContainerList)je.getObject ()).getPageID ());
693                         parent[1] = Integer.toString (PAGE_TYPE);
694                         return parent;
695                     } else {
696                         parent[0] = Integer.toString (((JahiaContainerList)je.getObject ()).getParentEntryID ());
697                         parent[1] = Integer.toString (CONTAINER_TYPE);
698                         return parent;
699                     }
700
701                 case PAGE_TYPE:
702                     parent[0] = Integer.toString (((JahiaPage)je.getObject ()).getParentID ());
703                     parent[1] = Integer.toString (PAGE_TYPE);
704                     return parent;
705
706                 case TEMPLATE_TYPE:
707                     parent[0] = "-1"; // dummy value
708
parent[1] = Integer.toString (TEMPLATE_TYPE);
709                     return parent;
710
711                 default:
712                     throw new JahiaException (MSG_INTERNAL_ERROR,
713                             "Incompatible Object Type passed to JahiaAuditLogManager",
714                             JahiaException.SERVICE_ERROR,
715                             JahiaException.CRITICAL_SEVERITY);
716             }
717         } catch (Exception JavaDoc e) {
718             logger.debug ("EXCEPTION MESSAGE :" + e.getMessage ());
719             throw new JahiaException (MSG_INTERNAL_ERROR,
720                     "Exception occurred while retrieving Event Object ID",
721                     JahiaException.SERVICE_ERROR,
722                     JahiaException.CRITICAL_SEVERITY);
723         }
724     }
725
726
727     /**
728      * get IDs of objects contained in an object
729      *
730      * @author Mikha�l Janson
731      * @param dbconn a database Connection
732      * @param objectType
733      * @
734      * @return an <code>ArrayList</code> of log entry IDs
735      */

736     private Vector JavaDoc getChildrenList (Connection JavaDoc dbConn, int objectType, int objectID) {
737
738         Statement JavaDoc stmt = null;
739         ResultSet JavaDoc rs = null;
740         Vector JavaDoc childrenVect = new Vector JavaDoc ();
741         String JavaDoc table = "";
742         String JavaDoc objectWord = "";
743         String JavaDoc query = "";
744
745         // get list of children...
746
try {
747             stmt = dbConn.createStatement ();
748             Set JavaDoc addedChilds = new HashSet JavaDoc ();
749
750             switch (objectType) {
751
752                 // no Children...
753
case LoggingEventListener.FIELD_TYPE:
754                     break;
755
756                     // Children can be CONTAINER...
757
case LoggingEventListener.CONTAINERLIST_TYPE:
758                     objectWord = "list";
759                     table = "jahia_ctn_entries";
760                     query = makeQuery (table, objectWord, objectID);
761                     rs = stmt.executeQuery (query);
762                     while (rs.next ()) {
763                         Integer JavaDoc[] child = new Integer JavaDoc[2];
764                         child[0] = new Integer JavaDoc (JahiaObjectTool.CONTAINER_TYPE);
765                         child[1] = new Integer JavaDoc (rs.getString ("id_" + table));
766                         if (!addedChilds.contains ((Integer JavaDoc)child[1])) {
767                             childrenVect.addElement (child);
768                         }
769                     }
770                     break;
771
772                     // Children can be FIELD or CONTAINERLIST...
773
case LoggingEventListener.CONTAINER_TYPE:
774                     objectWord = "ctn";
775                     table = "jahia_fields_data";
776                     query = makeQuery (table, objectWord, objectID);
777                     rs = stmt.executeQuery (query);
778
779                     // child found in fields...
780
if (rs.next ()) {
781                         while (rs.next ()) {
782                             Integer JavaDoc[] child = new Integer JavaDoc[2];
783                             child[0] = new Integer JavaDoc (JahiaObjectTool.FIELD_TYPE);
784                             child[1] = new Integer JavaDoc (rs.getString ("id_" + table));
785                             if (!addedChilds.contains ((Integer JavaDoc)child[1])) {
786                                 childrenVect.addElement (child);
787                             }
788                         }
789
790                         // no child found in fields... look in container lists...
791
} else {
792                         table = "jahia_ctn_lists";
793                         query = makeQuery (table, objectWord, objectID);
794                         rs = stmt.executeQuery (query);
795                         while (rs.next ()) {
796                             Integer JavaDoc[] child = new Integer JavaDoc[2];
797                             child[0] = new Integer JavaDoc (JahiaObjectTool.CONTAINERLIST_TYPE);
798                             child[1] = new Integer JavaDoc (rs.getString ("id_" + table));
799                             if (!addedChilds.contains ((Integer JavaDoc)child[1])) {
800                                 childrenVect.addElement (child);
801                             }
802                         }
803                     }
804                     break;
805
806                     // Children can be PAGE, FIELD or CONTAINERLIST...
807
case LoggingEventListener.PAGE_TYPE:
808                     objectWord = "page";
809                     table = "jahia_fields_data";
810                     query = makeQuery (table, objectWord, objectID);
811                     rs = stmt.executeQuery (query);
812
813                     // look in fields...
814
while (rs.next ()) {
815                         Integer JavaDoc[] child = new Integer JavaDoc[2];
816                         child[0] = new Integer JavaDoc (JahiaObjectTool.FIELD_TYPE);
817                         child[1] = new Integer JavaDoc (rs.getString ("id_" + table));
818                         if (!addedChilds.contains ((Integer JavaDoc)child[1])) {
819                             childrenVect.addElement (child);
820                         }
821                     }
822                     addedChilds.clear ();
823
824                     // then look in container lists...
825
table = "jahia_ctn_lists";
826                     query = makeQuery (table, objectWord, objectID);
827                     rs = stmt.executeQuery (query);
828                     while (rs.next ()) {
829                         Integer JavaDoc[] child = new Integer JavaDoc[2];
830                         child[0] = new Integer JavaDoc (LoggingEventListener.CONTAINERLIST_TYPE);
831                         child[1] = new Integer JavaDoc (rs.getString ("id_" + table));
832                         if (!addedChilds.contains ((Integer JavaDoc)child[1])) {
833                             childrenVect.addElement (child);
834                         }
835                     }
836                     addedChilds.clear ();
837
838                     /*
839                     // then look in pages...
840                     objectWord = "parent";
841                     table = "jahia_pages_data";
842                     query = makeQuery (table, objectWord, objectID);
843                     rs = stmt.executeQuery (query);
844                     while (rs.next ()) {
845                         Integer[] child = new Integer[2];
846                         child[0] = new Integer (JahiaObjectTool.PAGE_TYPE);
847                         child[1] = new Integer (rs.getString ("id_" + table));
848                         if (!addedChilds.contains ((Integer)child[1])) {
849                             childrenVect.addElement (child);
850                         }
851                     }
852                     */

853                     break;
854             }
855         } catch (SQLException JavaDoc sqlEx) {
856             logger.debug ("SQL Exception occured!", sqlEx);
857         } finally {
858             CloseStatement (stmt);
859         }
860
861         return childrenVect;
862     }// end getChildrenList
863

864
865     /**
866      * compose a full multi-level list of children
867      *
868      * @author Mikha�l Janson
869      * @param dbconn a database Connection
870      * @param objectType
871      * @param objectID
872      * @param prevChildrenList
873      * @return an <code>ArrayList</code> of log entry IDs
874      */

875     private Vector JavaDoc getAllChildren (Connection JavaDoc dbConn, int objectType, int objectID, Vector JavaDoc prevChildrenList) {
876         Vector JavaDoc fullChildrenList = (prevChildrenList == null) ? new Vector JavaDoc () : prevChildrenList; // initialize from previous if not null
877
Vector JavaDoc tempChildrenList = getChildrenList (dbConn, objectType, objectID); // create sublist on current level
878
if (!tempChildrenList.isEmpty ()) { // CHILDREN FOUND ->
879
for (int i = 0; i < tempChildrenList.size (); i++) { // loop on children list
880
fullChildrenList.add (tempChildrenList.get (i)); // add child to Full List
881
Integer JavaDoc[] newChild = (Integer JavaDoc[])tempChildrenList.get (i);
882                 Integer JavaDoc newObjType = newChild[0];
883                 Integer JavaDoc newObjID = newChild[1];
884                 getAllChildren (dbConn, newObjType.intValue (), newObjID.intValue (), fullChildrenList); // call myself !
885
}
886         }
887         return fullChildrenList;
888     }// end getAllChildren
889

890
891     /**
892      * compose a JDBC query to look for an objectID in a table field, given a wordmark to be followed by "id_" and the table name.
893      *
894      * @author Mikha�l Janson
895      * @param tableName name of the SQL table to perform the query on
896      * @param objectWord the wordmark matching a <code>String</code> followed by "id_" and the table name
897      * @param objectID
898      * @return the SQL query string
899      */

900     private String JavaDoc makeQuery (String JavaDoc tableName, String JavaDoc objectWord, int objectID) {
901         StringBuffer JavaDoc buf = new StringBuffer JavaDoc ();
902
903         buf.append ("SELECT DISTINCT ").append ("id_").append (tableName);
904         buf.append (", workflow_state FROM ").append (tableName);
905         buf.append (" WHERE ").append (objectWord).append ("id_").append (tableName).append ("=").append (Integer.toString (objectID));
906         if ("parent".equals (objectWord)) {
907             buf.append (" AND workflow_state=1 "); // we want active children
908
} else {
909             buf.append (" AND ( workflow_state=1 OR"); // we want active and nor marked for delete
910
buf.append (" (workflow_state>1 AND version_id <> -1) ) ");
911         }
912         buf.append (" ORDER BY workflow_state DESC ");
913         return buf.toString ();
914     }
915
916
917     /**
918      * delete the n oldest rows in the db
919      *
920      * @author Mikha�l Janson
921      * @param maxLogs the number of rows to delete
922      * @return the number of rows deleted
923      */

924     public int enforceMaxLogs (int maxLogs) {
925
926         int result = 0;
927
928         // no limit is maxLogs is set to 0
929
if (maxLogs == 0) {
930             return 0;
931         }
932
933         // Get a database connection
934
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
935         if (dbConn == null) {
936             return result;
937         }
938
939         // initialize default values
940
Statement JavaDoc stmt = null;
941         int numRows = 0;
942         String JavaDoc query = "";
943
944         // compare number of rows currently in table with the maxLogs property value
945
try {
946             stmt = dbConn.createStatement ();
947             query = "SELECT COUNT(*) AS numRows FROM " + TABLE_NAME;
948             ResultSet JavaDoc rs = stmt.executeQuery (query);
949             if (rs.next ()) {
950                 numRows = rs.getInt ("numRows");
951             }
952
953             int numDeletes = numRows - maxLogs;
954
955             // if rows need to be deleted, get the highest ID to be deleted
956
if (numDeletes > 0) {
957
958                 // build the query
959
query = "SELECT id_jahia_audit_log FROM " + TABLE_NAME;
960                 rs = stmt.executeQuery (query);
961                 for (int i = 0; i < (numDeletes - 1); i++) {
962                     rs.next ();
963                 }
964                 if (rs.next ()) {
965                     String JavaDoc victimID = rs.getString ("id_jahia_audit_log");
966
967                     // build and execute new query to delete everything up to and including the victim row
968
query = "DELETE FROM " + TABLE_NAME + " WHERE id_jahia_audit_log<" + victimID + " OR id_jahia_audit_log=" + victimID;
969                     result = stmt.executeUpdate (query);
970                 }
971             }
972         } catch (SQLException JavaDoc sqlEx) {
973             logger.debug ("SQL Exception occured! " + sqlEx.getMessage ());
974         } finally {
975
976             CloseStatement (stmt);
977         }
978         return result;
979     } // end deleteOldestRows
980

981
982     /**
983      * delete the oldest row in the table
984      *
985      * @author Mikha�l Janson
986      */

987     public boolean deleteOldestRow () {
988
989         boolean result = false;
990
991         // Get a database connection
992
Connection JavaDoc dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
993         if (dbConn == null) {
994             return result;
995         }
996         Statement JavaDoc stmt = null;
997         String JavaDoc query = "";
998
999         try {
1000            stmt = dbConn.createStatement ();
1001            // build the query
1002
query = "SELECT MIN(id_jahia_audit_log) AS minID FROM " + TABLE_NAME;
1003            ResultSet JavaDoc rs = stmt.executeQuery (query);
1004            if (rs.next ()) {
1005                String JavaDoc victimID = rs.getString ("minID");
1006
1007                // build and execute new query to delete the victim row
1008
query = "DELETE FROM " + TABLE_NAME + " WHERE id_jahia_audit_log=" + victimID;
1009                if (stmt.executeUpdate (query) > 0) {
1010                    result = true;
1011                }
1012            }
1013        } catch (SQLException JavaDoc sqlEx) {
1014            logger.debug ("SQL Exception occured! " + sqlEx.getMessage ());
1015            result = false;
1016        } finally {
1017
1018            CloseStatement (stmt);
1019        }
1020        return result;
1021    } // end deleteOldestRow
1022

1023
1024    //--------------------------------------------------------------------------
1025
/**
1026     * return a DOM document of all logs of a site
1027     *
1028     * @param String the site key
1029     *
1030     * @return JahiaDOMObject a DOM representation of this object
1031     *
1032     * @author NK
1033     */

1034    public JahiaDOMObject getLogsAsDOM (String JavaDoc siteKey)
1035            throws JahiaException {
1036
1037        if (siteKey == null) {
1038            return null;
1039        }
1040
1041        Connection JavaDoc dbConn = null;
1042        Statement JavaDoc statement = null;
1043
1044        String JavaDoc output = null;
1045        JahiaDBDOMObject dom = null;
1046
1047        try {
1048            String JavaDoc sqlQuery = "SELECT * FROM jahia_audit_log where site_jahia_audit_log='" + siteKey + "'";
1049
1050            dbConn = org.jahia.services.database.ConnectionDispenser.getConnection ();
1051            statement = dbConn.createStatement ();
1052            if (statement != null) {
1053                ResultSet JavaDoc rs = statement.executeQuery (sqlQuery);
1054                if (rs != null) {
1055                    dom = new JahiaDBDOMObject ();
1056                    dom.addTable ("jahia_audit_log", rs);
1057                    return dom;
1058                }
1059            }
1060        } catch (SQLException JavaDoc se) {
1061            String JavaDoc errorMsg = "Error in getLogsAsDOM(int siteID) : " + se.getMessage ();
1062            logger.debug (errorMsg);
1063            throw new JahiaException ("Cannot load logs from the database",
1064                    errorMsg, JahiaException.DATABASE_ERROR,
1065                    JahiaException.CRITICAL_SEVERITY);
1066        } finally {
1067
1068            CloseStatement (statement);
1069        }
1070
1071        return dom;
1072    }
1073
1074    //--------------------------------------------------------------------------
1075
/**
1076     * Pad a string with initial "0"s to obtain a length of 15 positions
1077     *
1078     * @param String the String to pad
1079     *
1080     * @return String the padded String
1081     *
1082     * @author NK
1083     */

1084
1085    private String JavaDoc padTimeString (String JavaDoc timeStr) {
1086        int timeStrLen = timeStr.length ();
1087        if (timeStrLen < 15) {
1088            StringBuffer JavaDoc buf = new StringBuffer JavaDoc ();
1089            for (int i = timeStrLen; i < 15; i++) {
1090                buf.append ("0");
1091            }
1092            timeStr = buf.append (timeStr).toString ();
1093        }
1094        return timeStr;
1095    }
1096
1097
1098    //-------------------------------------------------------------------------
1099
private void CloseStatement (Statement JavaDoc statement) {
1100        // Close the opened statement
1101
try {
1102            if (statement != null) {
1103                statement.close ();
1104            }
1105        } catch (SQLException JavaDoc se) {
1106            // FIXME -MJ- : Don't know yet what to do with this exception.
1107
// It should be logged somewhere !
1108
}
1109    }
1110
1111}
1112
Popular Tags