Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2004 Regents of the University of California and the
4
 *             National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: daigle $'
7
 *     '$Date: 2009-08-04 14:32:58 -0700 (Tue, 04 Aug 2009) $'
8
 * '$Revision: 5015 $'
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 2 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
 */
24
package edu.ucsb.nceas.metacat;
25

    
26
import java.sql.PreparedStatement;
27
import java.sql.ResultSet;
28
import java.sql.SQLException;
29
import java.sql.Timestamp;
30
import java.util.Date;
31

    
32
import org.apache.log4j.Logger;
33

    
34
import edu.ucsb.nceas.metacat.database.DBConnection;
35
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
36

    
37
/**
38
 * EventLog is used to intialize and store a log of events that occur in an
39
 * application. The events are registered with the logger as they occur, but
40
 * EventLog writes them to permenant storage when it is most convenient or
41
 * efficient. EventLog is a Singleton as there should always be only one object
42
 * for these logging events.
43
 * 
44
 * TODO: Logging to the database needn't be synchronous with the event.  
45
 * Instead, a separate thread can be launched that periodically sleeps and only
46
 * wakes periodically to see if metacat is idle.  The log event can be cached
47
 * and inserted later when the thread wakes and finds metacat idle.
48
 * 
49
 * TODO: Write a function that archives a part of the log table to an 
50
 * external text file so that the log table doesn't get to big.  This 
51
 * function should be able to be called manually or on a schedule. 
52
 * 
53
 * TODO: Write an access function that returns an XML report for a
54
 * specific subset of events.  Users should be able to query on
55
 * principal, docid/rev, date, event, and possibly other fields.
56
 * 
57
 * @author jones
58
 */
59
public class EventLog
60
{
61
    /**
62
     * The single instance of the event log that is always returned.
63
     */
64
    private static EventLog self = null;
65
    private Logger logMetacat = Logger.getLogger(EventLog.class);
66

    
67
    /**
68
     * A private constructor that initializes the class when getInstance() is
69
     * called.
70
     */
71
    private EventLog()
72
    {
73
    }
74

    
75
    /**
76
     * Return the single instance of the event log after initializing it if it
77
     * wasn't previously initialized.
78
     * 
79
     * @return the single EventLog instance
80
     */
81
    public static EventLog getInstance()
82
    {
83
        if (self == null) {
84
            self = new EventLog();
85
        }
86
        return self;
87
    }
88

    
89
    /**
90
     * Log an event of interest to the application. The information logged can
91
     * include basic identification information about the principal or computer
92
     * that initiated the event.
93
     * 
94
     * @param ipAddress the internet protocol address for the event
95
	 * @param principal the principal for the event (a username, etc)
96
	 * @param docid the identifier of the document to which the event applies
97
	 * @param event the string code for the event
98
     */
99
    public void log(String ipAddress, String principal, String docid,
100
			String event)
101
    {
102
        EventLogData logData = new EventLogData(ipAddress, principal, docid,
103
                event);
104
        insertLogEntry(logData);
105
    }
106
    
107
    /**
108
     * Insert a single log event record to the database.
109
     * 
110
     * @param logData the data to be logged when an event occurs
111
     */
112
    private void insertLogEntry(EventLogData logData)
113
    {
114
        String insertString = "insert into access_log"
115
                + "(ip_address, principal, docid, "
116
                + "event, date_logged) "
117
                + "values ("
118
                + "'" + logData.getIpAddress() + "', " 
119
                + "'" + logData.getPrincipal() + "', "
120
                + "'" + logData.getDocid() + "', "
121
                + "'" + logData.getEvent() + "', "
122
                + " ? " + ")"; 
123

    
124
        DBConnection dbConn = null;
125
        int serialNumber = -1;
126
        try {
127
            // Get a database connection from the pool
128
            dbConn = DBConnectionPool.getDBConnection("EventLog.insertLogEntry");
129
            serialNumber = dbConn.getCheckOutSerialNumber();
130
            
131
            // Execute the insert statement
132
            PreparedStatement stmt = dbConn.prepareStatement(insertString);
133
            stmt.setTimestamp(1, new Timestamp(new Date().getTime()));
134
            stmt.executeUpdate();
135
            stmt.close();
136
        } catch (SQLException e) {
137
        	logMetacat.error("Error while logging event to database: " 
138
                    + e.getMessage());
139
        } finally {
140
            // Return database connection to the pool
141
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
142
        }
143
    }
144
    
145
    /**
146
     * Get a report of the log events that match a set of filters.  The
147
     * filter parameters can be null; log records are subset based on
148
     * non-null filter parameters.
149
     * 
150
     * @param ipAddress the internet protocol address for the event
151
	 * @param principal the principal for the event (a username, etc)
152
	 * @param docid the identifier of the document to which the event applies
153
	 * @param event the string code for the event
154
	 * @param startDate beginning of date range for query
155
	 * @param endDate end of date range for query
156
	 * @return an XML-formatted report of the access log entries
157
     */
158
    public String getReport(String[] ipAddress, String[] principal, String[] docid,
159
            String[] event, Timestamp startDate, Timestamp endDate)
160
    {
161
        StringBuffer resultDoc = new StringBuffer();
162
        StringBuffer query = new StringBuffer();
163
        query.append("select entryid, ip_address, principal, docid, "
164
            + "event, date_logged from access_log");
165
//                        + ""
166
//                        + "event, date_logged) " + "values (" + "'"
167
//                        + logData.getIpAddress() + "', " + "'"
168
//                        + logData.getPrincipal() + "', " + "'"
169
//                        + logData.getDocid() + "', " + "'" + logData.getEvent()
170
//                        + "', " + " ? " + ")";
171
        if (ipAddress != null || principal != null || docid != null
172
                        || event != null || startDate != null || endDate != null) {
173
            query.append(" where ");
174
        }
175
        boolean clauseAdded = false;
176
        int startIndex = 0;
177
        int endIndex = 0;
178
        
179
        if (ipAddress != null) {
180
            query.append(generateSqlClause(clauseAdded, "ip_address", ipAddress));
181
            clauseAdded = true;
182
        }
183
        if (principal != null) {
184
            query.append(generateSqlClause(clauseAdded, "principal", principal));
185
            clauseAdded = true;
186
        }
187
        if (docid != null) {
188
            query.append(generateSqlClause(clauseAdded, "docid", docid));
189
            clauseAdded = true;
190
        }
191
        if (event != null) {
192
            query.append(generateSqlClause(clauseAdded, "event", event));
193
            clauseAdded = true;
194
        }
195
        if (startDate != null) {
196
            if (clauseAdded) {
197
                query.append(" and ");
198
            }
199
            query.append("date_logged > ?");
200
            clauseAdded = true;
201
            startIndex++;
202
        }
203
        if (endDate != null) {
204
            if (clauseAdded) {
205
                query.append(" and ");
206
            }
207
            query.append("date_logged < ?");
208
            clauseAdded = true;
209
            endIndex = startIndex + 1;
210
        }
211
        DBConnection dbConn = null;
212
        int serialNumber = -1;
213
        try {
214
            // Get a database connection from the pool
215
            dbConn = DBConnectionPool.getDBConnection("EventLog.getReport");
216
            serialNumber = dbConn.getCheckOutSerialNumber();
217

    
218
            // Execute the query statement
219
            PreparedStatement stmt = dbConn.prepareStatement(query.toString());
220
            if (startIndex > 0) {
221
                stmt.setTimestamp(startIndex, startDate); 
222
            }
223
            if (endIndex > 0) {
224
                stmt.setTimestamp(endIndex, endDate);
225
            }
226
            stmt.execute();
227
            ResultSet rs = stmt.getResultSet();
228
            //process the result and return it as an XML document
229
            resultDoc.append("<?xml version=\"1.0\"?>\n");
230
            resultDoc.append("<log>\n");
231
            while (rs.next()) {
232
                resultDoc.append(generateXmlRecord(rs.getString(1), rs.getString(2),
233
                                rs.getString(3), rs.getString(4), 
234
                                rs.getString(5), rs.getTimestamp(6)));
235
            }
236
            resultDoc.append("</log>");
237
            stmt.close();
238
        } catch (SQLException e) {
239
        	logMetacat.info("Error while logging event to database: "
240
                            + e.getMessage());
241
        } finally {
242
            // Return database connection to the pool
243
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
244
        }
245
        return resultDoc.toString();
246
    }
247
    
248
    /**
249
     * Utility method to help build a SQL query from an array of values.  For each
250
     * value in the array an 'OR' clause is constructed.
251
     * 
252
     * @param addOperator a flag indicating whether to add an 'AND' operator 
253
     *                    to the clause
254
     * @param column the name of the column to filter against
255
     * @param values the values to match in the SQL query
256
     * @return a String representation of the SQL query clause
257
     */
258
    private String generateSqlClause(boolean addOperator, String column, 
259
            String[] values)
260
    {
261
        StringBuffer clause = new StringBuffer();
262
        if (addOperator) {
263
            clause.append(" and ");
264
        }
265
        clause.append("(");
266
        for (int i = 0; i < values.length; i++) {
267
            if (i > 0) {
268
                clause.append(" or ");
269
            }
270
            clause.append(column);
271
            clause.append(" like '");
272
            clause.append(values[i]);
273
            clause.append("'");
274
        }
275
        clause.append(")");
276
        return clause.toString();
277
    }
278
    
279
    /**
280
     * Format each returned log record as an XML structure.
281
     * 
282
     * @param entryId the identifier of the log entry
283
     * @param ipAddress the internet protocol address for the event
284
	 * @param principal the principal for the event (a username, etc)
285
	 * @param docid the identifier of the document to which the event applies
286
	 * @param event the string code for the event
287
     * @param dateLogged the date on which the event occurred
288
     * @return String containing the formatted XML
289
     */
290
    private String generateXmlRecord(String entryId, String ipAddress, 
291
            String principal, String docid, String event, Timestamp dateLogged)
292
    {
293
        StringBuffer rec = new StringBuffer();
294
        rec.append("<logEntry>");
295
        rec.append(generateXmlElement("entryid", entryId));
296
        rec.append(generateXmlElement("ipAddress", ipAddress));
297
        rec.append(generateXmlElement("principal", principal));
298
        rec.append(generateXmlElement("docid", docid));
299
        rec.append(generateXmlElement("event", event));
300
        rec.append(generateXmlElement("dateLogged", dateLogged.toString()));
301
        rec.append("</logEntry>\n");
302

    
303
        return rec.toString();
304
    }
305
    
306
    /**
307
     * Return an XML formatted element for a given name/value pair.
308
     * 
309
     * @param name the name of the xml element
310
     * @param value the content of the xml element
311
     * @return the formatted XML element as a String
312
     */
313
    private String generateXmlElement(String name, String value)
314
    {
315
        return "<" + name + ">" + value + "</" + name + ">";
316
    }
317
}
(35-35/62)