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: leinfelder $'
7
 *     '$Date: 2010-12-07 14:03:16 -0800 (Tue, 07 Dec 2010) $'
8
 * '$Revision: 5693 $'
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, boolean anonymous)
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(
233
                		generateXmlRecord(
234
                				rs.getString(1), //id
235
                				anonymous ? "" : rs.getString(2), //ip
236
                				anonymous ? "" : rs.getString(3), //principal
237
                                rs.getString(4), 
238
                                rs.getString(5), 
239
                                rs.getTimestamp(6)));
240
            }
241
            resultDoc.append("</log>");
242
            stmt.close();
243
        } catch (SQLException e) {
244
        	logMetacat.info("Error while logging event to database: "
245
                            + e.getMessage());
246
        } finally {
247
            // Return database connection to the pool
248
            DBConnectionPool.returnDBConnection(dbConn, serialNumber);
249
        }
250
        return resultDoc.toString();
251
    }
252
    
253
    /**
254
     * Utility method to help build a SQL query from an array of values.  For each
255
     * value in the array an 'OR' clause is constructed.
256
     * 
257
     * @param addOperator a flag indicating whether to add an 'AND' operator 
258
     *                    to the clause
259
     * @param column the name of the column to filter against
260
     * @param values the values to match in the SQL query
261
     * @return a String representation of the SQL query clause
262
     */
263
    private String generateSqlClause(boolean addOperator, String column, 
264
            String[] values)
265
    {
266
        StringBuffer clause = new StringBuffer();
267
        if (addOperator) {
268
            clause.append(" and ");
269
        }
270
        clause.append("(");
271
        for (int i = 0; i < values.length; i++) {
272
            if (i > 0) {
273
                clause.append(" or ");
274
            }
275
            clause.append(column);
276
            clause.append(" like '");
277
            clause.append(values[i]);
278
            clause.append("'");
279
        }
280
        clause.append(")");
281
        return clause.toString();
282
    }
283
    
284
    /**
285
     * Format each returned log record as an XML structure.
286
     * 
287
     * @param entryId the identifier of the log entry
288
     * @param ipAddress the internet protocol address for the event
289
	 * @param principal the principal for the event (a username, etc)
290
	 * @param docid the identifier of the document to which the event applies
291
	 * @param event the string code for the event
292
     * @param dateLogged the date on which the event occurred
293
     * @return String containing the formatted XML
294
     */
295
    private String generateXmlRecord(String entryId, String ipAddress, 
296
            String principal, String docid, String event, Timestamp dateLogged)
297
    {
298
        StringBuffer rec = new StringBuffer();
299
        rec.append("<logEntry>");
300
        rec.append(generateXmlElement("entryid", entryId));
301
        rec.append(generateXmlElement("ipAddress", ipAddress));
302
        rec.append(generateXmlElement("principal", principal));
303
        rec.append(generateXmlElement("docid", docid));
304
        rec.append(generateXmlElement("event", event));
305
        rec.append(generateXmlElement("dateLogged", dateLogged.toString()));
306
        rec.append("</logEntry>\n");
307

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