KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > dataobjs > DBAudit


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.dataobjs;
34
35 import java.io.FileWriter JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.io.LineNumberReader JavaDoc;
38 import java.io.FileReader JavaDoc;
39 import java.io.BufferedReader JavaDoc;
40
41 import java.sql.PreparedStatement JavaDoc;
42 import java.sql.SQLException JavaDoc;
43 import java.sql.Timestamp JavaDoc;
44 import java.sql.Types JavaDoc;
45
46 import java.util.TreeMap JavaDoc;
47 import java.util.Iterator JavaDoc;
48
49 import com.knowgate.jdc.JDCConnection;
50 import com.knowgate.misc.Gadgets;
51
52 /**
53  * Keeps an operations log at a file or database table.
54  * @author Sergio Montoro ten
55  * @version 3.0
56  */

57
58 public class DBAudit {
59
60   protected void finalize() throws IOException JavaDoc {
61     if (sAuditFile!="") oLogWriter.close();
62   }
63
64   // ----------------------------------------------------------
65

66   /**
67    * Write a log entry into k_auditing database table
68    * @param oConn Database connection, if null then data if dumped to a flat file.
69    * @param iIdEntity - Internal ClassId short nombre for audited class.
70    * @param sCoOp - Operation Code (4 alphanumeric digits)
71    * @param sGUUser - GUID of user performing the operation (máx. 32 characters)
72    * @param sGUEntity1 - GUID of primary entity (or source entitity) for the operation (máx. 32 characters)
73    * @param sGUEntity2 - GUID of secondary entity (or target entitity) for the operation (máx. 32 characters)
74    * @param iIdTransact - Transaction Identifier
75    * @param iIPAddr - User IP address
76    * @param sTxParams1 - Aditional parameters related to entity 1 (máx 255 characters)
77    * @param sTxParams2 - Aditional parameters related to entity 2 (máx 255 characters)
78    * @throws SQLException
79    * @throws SecurityException
80    */

81
82   public static void log(JDCConnection oConn, short iIdEntity, String JavaDoc sCoOp, String JavaDoc sGUUser, String JavaDoc sGUEntity1, String JavaDoc sGUEntity2, int iIdTransact, int iIPAddr, String JavaDoc sTxParams1, String JavaDoc sTxParams2)
83     throws SQLException JavaDoc {
84     PreparedStatement JavaDoc oStmt;
85
86     if (sCoOp==null) throw new SQLException JavaDoc("DBAudit.log() operation code cannot be null", "23000", 23000);
87     if (sCoOp.length()>4) throw new SQLException JavaDoc("DBAudit.log() operation code " + sCoOp + " cannot be longer than 4 characters", "01004", 1004);
88     if (sGUUser==null) throw new SQLException JavaDoc("DBAudit.log() user GUID cannot be null", "23000", 23000);
89     if (sGUUser.length()>32) throw new SQLException JavaDoc("DBAudit.log() user GUID cannot be longer than 32 characters", "23000", 23000);
90     if (sGUEntity1==null) throw new SQLException JavaDoc("DBAudit.log() user entity GUID cannot be null", "23000", 23000);
91     if (sGUEntity1.length()>32) throw new SQLException JavaDoc("DBAudit.log() entity GUID cannot be longer than 32 characters", "23000", 23000);
92
93     if (null==oConn) {
94         writeLog (iIdEntity, sCoOp, sGUUser, sGUEntity1, sGUEntity2, iIdTransact, String.valueOf(iIPAddr), sTxParams1, sTxParams2);
95     }
96     else {
97       oStmt = oConn.prepareStatement("INSERT INTO k_auditing VALUES (?,?,?,?,?,?,?,?,?,?)");
98       oStmt.setShort (1, iIdEntity);
99       oStmt.setString (2, sCoOp);
100       oStmt.setString (3, sGUUser);
101       oStmt.setTimestamp(4, new Timestamp JavaDoc(new java.util.Date JavaDoc().getTime()));
102       oStmt.setString (5, sGUEntity1);
103       if (null==sGUEntity2)
104         oStmt.setNull (6, Types.VARCHAR);
105       else
106         oStmt.setString (6, sGUEntity2);
107       oStmt.setInt (7, iIdTransact);
108       oStmt.setInt (8, iIPAddr);
109       if (null==sTxParams1)
110         oStmt.setNull (9, Types.VARCHAR);
111       else
112         oStmt.setString (9, Gadgets.left(sTxParams1,100));
113       if (null==sTxParams2)
114         oStmt.setNull (10, Types.VARCHAR);
115       else
116         oStmt.setString (10, Gadgets.left(sTxParams2, 100));
117
118       oStmt.execute();
119       oStmt.close();
120     } // fi (oConn)
121
} // log()
122

123   // ----------------------------------------------------------
124

125   /**
126    * Write a log entry into javatrx.txt file
127    * @param iIdEntity - Internal ClassId short nombre for audited class.
128    * @param sCoOp - Operation Code (4 alphanumeric digits)
129    * @param sGUUser - GUID of user performing the operation (máx. 32 characters)
130    * @param sGUEntity1 - GUID of primary entity (or source entitity) for the operation (máx. 32 characters)
131    * @param sGUEntity2 - GUID of secondary entity (or target entitity) for the operation (máx. 32 characters)
132    * @param iIdTransact - Transaction Identifier
133    * @param iIPAddr - User IP address
134    * @param sTxParams1 - Aditional parameters related to entity 1 (máx 255 characters)
135    * @param sTxParams2 - Aditional parameters related to entity 2 (máx 255 characters)
136    * @throws SecurityException if there aren't sufficient permissions for writting at javatrc.txt file
137    */

138   public static void log (short iIdEntity, String JavaDoc sCoOp, String JavaDoc sGUUser, String JavaDoc sGUEntity1, String JavaDoc sGUEntity2, int iIdTransact, String JavaDoc sIPAddr, String JavaDoc sTxParams1, String JavaDoc sTxParams2) {
139
140     writeLog (iIdEntity, sCoOp, sGUUser, sGUEntity1, sGUEntity2, iIdTransact, sIPAddr, sTxParams1, sTxParams2);
141   } // log()
142

143   // ----------------------------------------------------------
144

145   /**
146    * Set path to log output file
147    * @param sFilePath Physical file path
148    * @throws IOException
149    */

150   public static void setAuditFile(String JavaDoc sFilePath) throws IOException JavaDoc {
151     if (sAuditFile!="") oLogWriter.close();
152     sAuditFile = "";
153     oLogWriter = new FileWriter JavaDoc(sFilePath, true);
154     sAuditFile = sFilePath;
155   } // setAuditFile
156

157   // ----------------------------------------------------------
158

159   /**
160    * Write an operation line to the log file
161    * @param sTransactId Transaction Identifier
162    * @param sUserId GUID of user performing the operation (máx. 32 characters)
163    * @param sObject GUID of primary entity for the operation
164    * @param sOpCode Operation code (máx. 4 characters)
165    * @param sParams Aditional parameters related to entity 1 (máx 255 characters)
166    * @throws SecurityException if there aren't sufficient permissions for writting at javatrc.txt file
167    */

168   private static void writeLog (short iIdEntity, String JavaDoc sCoOp, String JavaDoc sUserId, String JavaDoc sGUEntity1, String JavaDoc sGUEntity2, int iIdTransact, String JavaDoc sIPAddr, String JavaDoc sTxParams1, String JavaDoc sTxParams2)
169     throws SecurityException JavaDoc {
170     try {
171       if (null==oLogWriter)
172         if (sOSName.startsWith("Windows"))
173           setAuditFile("C:\\javaudit.txt");
174         else
175           setAuditFile("/tmp/javaudit.txt");
176
177       oLogWriter.write (new java.util.Date JavaDoc().toString() + ";" + String.valueOf(iIdEntity) + ";" + sCoOp + ";" + sUserId + ";" + sGUEntity1 + ";" + sGUEntity2 + ";" + String.valueOf(iIdTransact) + ";" + sIPAddr + ";" + sTxParams1 + ";" + sTxParams2 + "\n");
178
179     }
180     catch (IOException JavaDoc ioe) { }
181     catch (NullPointerException JavaDoc npe) {}
182
183   } // writeLog()
184

185   // ----------------------------------------------------------
186

187   public static String JavaDoc analyze(String JavaDoc sFile) throws IOException JavaDoc {
188
189     int f, s, e;
190     StringBuffer JavaDoc oReport = new StringBuffer JavaDoc(4096);
191     String JavaDoc sLine, sOpCode = null, sEntity = null;
192
193     TreeMap JavaDoc oOpen = new TreeMap JavaDoc();
194     Integer JavaDoc oCount;
195
196     LineNumberReader JavaDoc lnr;
197
198     FileReader JavaDoc oReader = new FileReader JavaDoc(sFile);
199     BufferedReader JavaDoc oBuffer = new BufferedReader JavaDoc(oReader);
200     LineNumberReader JavaDoc oLines = new LineNumberReader JavaDoc(oBuffer);
201
202     while ((sLine = oLines.readLine())!=null) {
203       f = 0;
204       s = -1;
205       while ((s=sLine.indexOf(';',s+1))!=-1) {
206         f++;
207         switch (f) {
208           case 2:
209             sOpCode = sLine.substring(s, sLine.indexOf(';', s+1));
210             break;
211           case 4:
212             sEntity = sLine.substring(s, sLine.indexOf(';', s+1));
213
214             if (sOpCode.equals("ODBC") || sOpCode.equals("OJSP")) {
215               oCount = (Integer JavaDoc) oOpen.get(sEntity);
216               if (oCount==null) {
217                 oCount = new Integer JavaDoc(1);
218                 oOpen.put(sEntity, oCount);
219               }
220               else {
221                 oCount = new Integer JavaDoc(oCount.intValue()+1);
222                 oOpen.remove(sEntity);
223                 oOpen.put(sEntity, oCount);
224               }
225             } // fi (sOpCode==ODBC)
226
else if (sOpCode.equals("CDBC") || sOpCode.equals("CJSP")) {
227               oCount = (Integer JavaDoc) oOpen.get(sEntity);
228               if (oCount==null) {
229                 oCount = new Integer JavaDoc(-1);
230                 oOpen.put(sEntity, oCount);
231               }
232               else {
233                 oCount = new Integer JavaDoc(oCount.intValue()-1);
234                 oOpen.remove(sEntity);
235                 oOpen.put(sEntity, oCount);
236               }
237             }
238             break;
239         } // switch(f)
240
} // wend
241
if (f%10==0) System.out.print('.');
242     } // wend
243

244     System.out.print("\n");
245
246     oReader.close();
247     oLines.close();
248     oBuffer.close();
249
250     Iterator JavaDoc oKeys = oOpen.keySet().iterator();
251
252     while (oKeys.hasNext()) {
253       sEntity = (String JavaDoc) oKeys.next();
254       oCount = (Integer JavaDoc) oOpen.get(sEntity);
255
256       if (oCount.intValue()!=0) {
257         oReport.append(sEntity + " open/close mismatch " + oCount.toString() + "\n");
258       }
259     } // wend
260

261     return oReport.toString();
262   }
263
264   // ----------------------------------------------------------
265

266   private static void printUsage() {
267     System.out.println("");
268     System.out.println("Usage:\n");
269     System.out.println("DBAudit analyze <file_path>");
270   }
271
272   public static void main(String JavaDoc[] argv) throws IOException JavaDoc {
273
274     if (argv.length<2)
275       printUsage();
276     else if (!argv[0].equals("analyze"))
277       printUsage();
278     else
279       System.out.print(DBAudit.analyze(argv[1]));
280
281   }
282   // ----------------------------------------------------------
283

284   private static String JavaDoc sOSName = System.getProperty("os.name");
285
286   private static String JavaDoc sAuditFile = "";
287
288   private static FileWriter JavaDoc oLogWriter = null;
289
290 } // DBAudit
291
Popular Tags