Project

General

Profile

« Previous | Next » 

Revision 2111

Added by Matt Jones about 20 years ago

Partial implementation of a query facility for the access log. Need to fix problems with the date filtering, and tie this into the servlet action when completed and tested.

View differences:

test/edu/ucsb/nceas/metacattest/EventLogTest.java
26 26
import java.io.File;
27 27
import java.io.FileNotFoundException;
28 28
import java.io.IOException;
29
import java.sql.Timestamp;
30
import java.text.ParseException;
31
import java.text.SimpleDateFormat;
32
import java.util.Date;
29 33

  
30 34
import edu.ucsb.nceas.metacat.DBConnectionPool;
31 35
import edu.ucsb.nceas.metacat.EventLog;
......
67 71
        assertTrue(logger != null);
68 72
    }
69 73

  
74
    /**
75
     * Test whether the log method can properly insert a log record.
76
     */
70 77
    public void testLog()
71 78
    {
72
        EventLog.getInstance().log("192.168.1.103", "public", "test.1", "read");
79
        EventLog.getInstance().log("192.168.1.103", "public", "test.2.1", "read");
73 80
        assertTrue(1 == 1);
74 81
    }
75 82

  
83
    /**
84
     * Test whether getReport returns correct reports.
85
     */
86
    public void testGetReport()
87
    {
88
        String[] principals = {"jones", "public", "someone"};
89
        String[] ipList = {"192.168.1.103", "192.168.1.104"};
90
        String[] docList = {"test.2.1", "test.2"};
91
        String[] eventList = {"read", "insert", "update"};
92
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
93
        Timestamp startDate = null;
94
        Timestamp endDate = null;
95
        try {
96
            startDate = new Timestamp((format.parse("2004-04-07 09:32:00")).getTime());
97
            endDate = new Timestamp((format.parse("2004-04-07 09:50:00")).getTime());
98
        } catch (ParseException e) {
99
            System.out.println("Failed to created endDate from format.");
100
        }
101
        String report = EventLog.getInstance().getReport(ipList, principals, docList, 
102
                        eventList, null, null);
103
        System.out.println(report);
104
        report = EventLog.getInstance().getReport(null, null, null, 
105
                        null, startDate, endDate);
106
        System.out.println(report);
107
    }
76 108
}
src/edu/ucsb/nceas/metacat/EventLog.java
24 24
package edu.ucsb.nceas.metacat;
25 25

  
26 26
import java.sql.PreparedStatement;
27
import java.sql.ResultSet;
27 28
import java.sql.SQLException;
28 29
import java.sql.Timestamp;
29 30
import java.util.Date;
......
118 119
        int serialNumber = -1;
119 120
        try {
120 121
            // Get a database connection from the pool
121
            dbConn = DBConnectionPool.getDBConnection("EventLog.writeLog");
122
            dbConn = DBConnectionPool.getDBConnection("EventLog.insertLogEntry");
122 123
            serialNumber = dbConn.getCheckOutSerialNumber();
123 124
            
124 125
            // Execute the insert statement
......
137 138
    
138 139
    /**
139 140
     * Get a report of the log events that match a set of filters.  The
140
     * filter parameters can be omitted null; log records are subset based on
141
     * filter parameters can be null; log records are subset based on
141 142
     * non-null filter parameters.
142 143
     * 
143 144
     * @param ipAddress the internet protocol address for the event
144 145
	 * @param principal the principal for the event (a username, etc)
145 146
	 * @param docid the identifier of the document to which the event applies
146 147
	 * @param event the string code for the event
147
	 * @param startDate the date on which the event was logged
148
	 * @param endDate the 
148
	 * @param startDate beginning of date range for query
149
	 * @param endDate end of date range for query
150
	 * @return an XML-formatted report of the access log entries
149 151
     */
150
    public void getReport(String ipAddress, String principal, String docid,
151
            String event, Timestamp dateLogged)
152
    public String getReport(String[] ipAddress, String[] principal, String[] docid,
153
            String[] event, Timestamp startDate, Timestamp endDate)
152 154
    {
155
        StringBuffer resultDoc = new StringBuffer();
156
        StringBuffer query = new StringBuffer();
157
        query.append("select entryid, ip_address, principal, docid, "
158
            + "event, date_logged from access_log");
159
//                        + ""
160
//                        + "event, date_logged) " + "values (" + "'"
161
//                        + logData.getIpAddress() + "', " + "'"
162
//                        + logData.getPrincipal() + "', " + "'"
163
//                        + logData.getDocid() + "', " + "'" + logData.getEvent()
164
//                        + "', " + " ? " + ")";
165
        if (ipAddress != null || principal != null || docid != null
166
                        || event != null || startDate != null || endDate != null) {
167
            query.append(" where ");
168
        }
169
        boolean clauseAdded = false;
170
        int startIndex = 0;
171
        int endIndex = 0;
172
        
173
        if (ipAddress != null) {
174
            query.append(formatSqlClause(clauseAdded, "ip_address", ipAddress));
175
            clauseAdded = true;
176
        }
177
        if (principal != null) {
178
            query.append(formatSqlClause(clauseAdded, "principal", principal));
179
            clauseAdded = true;
180
        }
181
        if (docid != null) {
182
            query.append(formatSqlClause(clauseAdded, "docid", docid));
183
            clauseAdded = true;
184
        }
185
        if (event != null) {
186
            query.append(formatSqlClause(clauseAdded, "event", event));
187
            clauseAdded = true;
188
        }
189
        if (startDate != null) {
190
            if (clauseAdded) {
191
                query.append(" and ");
192
            }
193
            query.append("date_logged > ?");
194
            clauseAdded = true;
195
            startIndex++;
196
        }
197
        if (endDate != null) {
198
            if (clauseAdded) {
199
                query.append(" and ");
200
            }
201
            query.append("date_logged < ?");
202
            clauseAdded = true;
203
            endIndex = startIndex + 1;
204
        }
205
        DBConnection dbConn = null;
206
        int serialNumber = -1;
207
        try {
208
            // Get a database connection from the pool
209
            dbConn = DBConnectionPool.getDBConnection("EventLog.getReport");
210
            serialNumber = dbConn.getCheckOutSerialNumber();
211

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

  
297
        return rec.toString();
298
    }
299
    
300
    /**
301
     * Return an XML formatted element for a given name/value pair.
302
     * 
303
     * @param name the name of the xml element
304
     * @param value the content of the xml element
305
     * @return the formatted XML element as a String
306
     */
307
    private String formatXmlElement(String name, String value)
308
    {
309
        return "<" + name + ">" + value + "</" + name + ">";
310
    }
154 311
}

Also available in: Unified diff