KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > sqlprofiler > gui > ProfileStatementTableModel


1 /*
2  * Copyright (C) Jahia Ltd. All rights reserved.
3  *
4  * This software is published under the terms of the Jahia Open Software
5  * License version 1.1, a copy of which has been included with this
6  * distribution in the LICENSE.txt file.
7  */

8 package org.jahia.sqlprofiler.gui;
9
10 import javax.swing.table.*;
11 import java.util.*;
12 import org.jahia.sqlprofiler.QueryEntry;
13 import java.text.DateFormat JavaDoc;
14 import javax.swing.JTable JavaDoc;
15 import java.awt.event.*;
16 import javax.swing.*;
17 import org.jahia.sqlprofiler.QueryStatistics;
18 import java.io.StringWriter JavaDoc;
19 import java.io.PrintWriter JavaDoc;
20 import org.jahia.sqlprofiler.QueryStatEntry;
21 import java.text.NumberFormat JavaDoc;
22 import java.io.FileWriter JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.text.SimpleDateFormat JavaDoc;
25
26 /**
27  * <p>Title: SQL Profiler</p>
28  * <p>Description: </p>
29  * <p>Copyright: Copyright (c) 2003</p>
30  * <p>Company: Jahia Ltd</p>
31  * @author Serge Huber
32  * @author Jean-Philippe Valentin
33  * @version 1.0
34  *
35  * 11/14/2003 : Add save table profile statistics as report file CSV by Jean-Philippe VALENTIN (JPV)
36  */

37
38 public class ProfileStatementTableModel extends AbstractTableModel
39     implements Comparator {
40
41     private QueryStatistics queryStats = new QueryStatistics();
42
43     private static final org.apache.log4j.Logger logger = org.apache.log4j.
44         Logger.getLogger(ProfileStatementTableModel.class);
45
46     private LoggerTableModel loggerModel;
47     private JLabel statementCountValueLabel = null;
48
49     private ArrayList queryEntries = new ArrayList();
50     private SortedSet sortedQueryEntries = new TreeSet();
51     protected int currCol = 0;
52     protected Vector ascendCol = new Vector(); // this vector stores the state (ascending or descending) of each column
53
protected Integer JavaDoc one = new Integer JavaDoc(1);
54     protected Integer JavaDoc minusOne = new Integer JavaDoc( -1);
55
56     private long lowestQueryTime = Long.MAX_VALUE;
57     private long highestQueryTime = Long.MIN_VALUE;
58     private long totalQueryTime = 0;
59
60     // String logEntry = now + "|"+ elapsed + "|"+(connectionId==-1 ? "" : String.valueOf(connectionId))+"|"+category+"|"+prepared+"|"+sql;
61
private static final String JavaDoc[] COLUMN_NAMES = {
62         "Date", "Time[ms]", "ID", "Category", "Prepared", "SQL"};
63
64     private static final SimpleDateFormat JavaDoc DATE_FORMATTER = new SimpleDateFormat JavaDoc ("yyyy.MM.dd hh:mm:ss.SSS");
65     private javax.swing.JLabel JavaDoc statementTimeValueLabel;
66     private ProfileResultTableModel profileResultModel;
67
68     public ProfileStatementTableModel(LoggerTableModel loggerModel) {
69         this.loggerModel = loggerModel;
70         for (int i = 0; i < COLUMN_NAMES.length; i++) {
71             if (i == 0) {
72                 ascendCol.add(minusOne);
73             } else {
74                 ascendCol.add(one);
75             }
76         }
77     }
78
79     public void processP6Event(String JavaDoc eventText) {
80         try {
81             QueryEntry queryEntry = new QueryEntry(eventText);
82             addQuery(queryEntry);
83             queryStats.processSQL(queryEntry);
84         } catch (NoSuchElementException nsee) {
85             logger.error("Error while parsing p6spy format", nsee);
86         }
87     }
88
89     public void displayOccurenceStats(boolean displayQueries) {
90         StringWriter JavaDoc strWriter = new StringWriter JavaDoc();
91         PrintWriter JavaDoc ptrWriter = new PrintWriter JavaDoc(strWriter);
92
93         profileResultModel.clear();
94
95         Set sortedQueryStats = queryStats.getQueryStatsByOccurence();
96
97         Iterator queryStatByOccurenceIter = queryStats.getQueryStatsByOccurence().
98             iterator();
99         while (queryStatByOccurenceIter.hasNext()) {
100             QueryStatEntry curQueryStat = (QueryStatEntry)
101                 queryStatByOccurenceIter.next();
102             double curPercentage = 0.0;
103             if (queryStats.getTotalElapsedQueryTime() > 0) {
104                 curPercentage = (100.0 * curQueryStat.getTotalElapsedTime()) /
105                     queryStats.getTotalElapsedQueryTime();
106             } else {
107                 curPercentage = (100.0 *
108                                  curQueryStat.getOccurences()) /
109                     queryStats.getOccurenceCount();
110             }
111             NumberFormat JavaDoc nf = NumberFormat.getInstance();
112             nf.setMaximumFractionDigits(2);
113             ProfileReportResult profileResult = new ProfileReportResult();
114             profileResult.setPercentage(curPercentage);
115             profileResult.setOccurences(curQueryStat.getOccurences());
116             profileResult.setTotalElapsedTime(curQueryStat.getTotalElapsedTime());
117             profileResult.setTableNames(curQueryStat.getTableNames());
118             profileResult.setColumnNames(curQueryStat.getColumnNames());
119
120             profileResultModel.addProfileReportResult(profileResult);
121             /*
122                          ptrWriter.println(nf.format(curPercentage) +
123                               "% Occurences=" + curQueryStat.getOccurences() +
124                  " Total time=" + curQueryStat.getTotalElapsedTime() +
125                               " Table(s)=" + curQueryStat.getTableNames() +
126                               " Column(s)=" + curQueryStat.getColumnNames() +
127                               "<br>");
128                          if (displayQueries) {
129                 Iterator queryIter = curQueryStat.getQueries().iterator();
130                 while (queryIter.hasNext()) {
131                     String curQuery = (String) queryIter.next();
132                     ptrWriter.println(" " + curQuery + "<br>");
133                 }
134                          }
135              */

136         }
137         profileResultModel.fireTableDataChanged();
138     }
139
140     public void saveSQLIndexFile(String JavaDoc indexesFileName) {
141         logger.debug("Writing indexes SQL to file [" + indexesFileName +
142                      "]...");
143         try {
144             FileWriter JavaDoc fileWriter = new FileWriter JavaDoc(indexesFileName);
145             PrintWriter JavaDoc writer = new PrintWriter JavaDoc(fileWriter);
146             Map generatedIndexes = queryStats.getGeneratedIndexes();
147             Iterator indexNameIter = generatedIndexes.
148                 keySet().iterator();
149             while (indexNameIter.hasNext()) {
150                 String JavaDoc curIndexName = (String JavaDoc) indexNameIter.next();
151                 String JavaDoc indexSql = (String JavaDoc) generatedIndexes.
152                     get(curIndexName);
153                 writer.println(indexSql);
154             }
155             writer.flush();
156             writer.close();
157         } catch (IOException JavaDoc ioe) {
158             ioe.printStackTrace();
159         }
160         logger.debug("done.");
161
162     }
163
164 //JPV : method called on the button to save SQL table profile statistics generated in a file
165
public void saveReportFile(String JavaDoc reportFileName) {
166         logger.debug("Writing report to file [" + reportFileName +
167                      "]...");
168         try {
169             FileWriter JavaDoc fileWriter = new FileWriter JavaDoc(reportFileName);
170             PrintWriter JavaDoc writer = new PrintWriter JavaDoc(fileWriter);
171            
172              Set sortedQueryStats = queryStats.getQueryStatsByOccurence();
173
174              Iterator queryStatByOccurenceIter = queryStats.getQueryStatsByOccurence().iterator();
175
176              while (queryStatByOccurenceIter.hasNext()) {
177                 QueryStatEntry curQueryStat = (QueryStatEntry) queryStatByOccurenceIter.next();
178                 double curPercentage = 0.0;
179                 if (queryStats.getTotalElapsedQueryTime() > 0) {
180                     curPercentage = (100.0 * curQueryStat.getTotalElapsedTime()) /
181                     queryStats.getTotalElapsedQueryTime();
182                 } else {
183                     curPercentage = (100.0 *
184                                  curQueryStat.getOccurences()) /
185                                  queryStats.getOccurenceCount();
186                 }
187                 NumberFormat JavaDoc nf = NumberFormat.getInstance();
188                 nf.setMaximumFractionDigits(2);
189
190                 //Find throws SQL Statement Attach to curQueryStat
191
Set setQueries = curQueryStat.getQueries();
192                 Iterator setQueriesIter = setQueries.iterator();
193                 QueryEntry querySQL = (QueryEntry) setQueriesIter.next();
194
195                 //First get prepared statement or Sql Statement if null
196
String JavaDoc strQuerySQL = querySQL.getPreparedSQL();
197                 if (strQuerySQL == null)
198                 { strQuerySQL = querySQL.getSqlStatement(); }
199 /*
200                 while (setQueriesIter.hasNext()) {
201                     QueryEntry querySQL = (QueryEntry) setQueriesIter.next();
202                     writer.println(querySQL.getSqlStatement());
203                 }
204 */

205                 writer.println(curPercentage + "," +
206                                curQueryStat.getTotalElapsedTime() + "," +
207                                curQueryStat.getOccurences() + ",\"" +
208                                curQueryStat.getTableNames() + "\",\"" +
209                                curQueryStat.getColumnNames() + "\",\"" +
210                                strQuerySQL + "\""
211                               );
212              }
213             writer.flush();
214             writer.close();
215         } catch (IOException JavaDoc ioe) {
216             ioe.printStackTrace();
217         }
218         logger.debug("done.");
219
220     }
221 //End JPV
222

223     public int getRowCount() {
224         return queryEntries.size();
225     }
226
227     public int getColumnCount() {
228         return COLUMN_NAMES.length;
229     }
230
231     public String JavaDoc getColumnName(int aCol) {
232         // does not need to be synchronized
233
return COLUMN_NAMES[aCol];
234     }
235
236     public void addQuery(QueryEntry queryEntry) {
237         queryEntry.setReceptionRank(queryEntries.size());
238         queryEntries.add(queryEntry);
239         sortedQueryEntries.add(queryEntry);
240         long entryTime = queryEntry.getTime();
241         if (entryTime > highestQueryTime) {
242             highestQueryTime = entryTime;
243         }
244         if (entryTime < lowestQueryTime) {
245             lowestQueryTime = entryTime;
246         }
247         if (queryEntry.getElapsedTime() > 0) {
248             totalQueryTime += queryEntry.getElapsedTime();
249         }
250     }
251
252     public void updateQueryStatsDisplay() {
253         if (statementCountValueLabel != null) {
254             statementCountValueLabel.setText(Integer.toString(queryEntries.size()));
255         }
256         if (statementTimeValueLabel != null) {
257             statementTimeValueLabel.setText(Long.toString(totalQueryTime));
258         }
259     }
260
261     public void clear() {
262         queryEntries.clear();
263         sortedQueryEntries.clear();
264         lowestQueryTime = Long.MAX_VALUE;
265         highestQueryTime = Long.MIN_VALUE;
266         totalQueryTime = 0;
267         currCol = 0;
268         if (statementCountValueLabel != null) {
269             statementCountValueLabel.setText(Integer.toString(queryEntries.size()));
270         }
271         if (statementTimeValueLabel != null) {
272             statementTimeValueLabel.setText("0");
273         }
274         queryStats.clear();
275     }
276
277     public Object JavaDoc getValueAt(int rowIndex, int columnIndex) {
278
279         QueryEntry curQueryEntry = (QueryEntry) queryEntries.get(rowIndex);
280         return getFormattedQueryEntryColumn(curQueryEntry, columnIndex);
281     }
282
283     private Object JavaDoc getFormattedQueryEntryColumn(QueryEntry curQueryEntry,
284                                        int columnIndex) {
285         Object JavaDoc result = null;
286         switch (columnIndex) {
287             case 0:
288                 result = DATE_FORMATTER.format(new Date(curQueryEntry.getTime()));
289                 break;
290             case 1:
291                 result = new Long JavaDoc(curQueryEntry.getElapsedTime());
292                 break;
293             case 2:
294                 result = curQueryEntry.getConnectionID();
295                 break;
296             case 3:
297                 result = curQueryEntry.getCategory();
298                 break;
299             case 4:
300                 result = curQueryEntry.getPreparedSQL();
301                 break;
302             case 5:
303                 result = curQueryEntry.getSqlStatement();
304                 break;
305
306         }
307         return result;
308     }
309
310     private Object JavaDoc getRawQueryEntryColumn(QueryEntry curQueryEntry,
311                                        int columnIndex) {
312         Object JavaDoc result = null;
313         switch (columnIndex) {
314             case 0:
315                 result = new Date(curQueryEntry.getTime());
316                 break;
317             case 1:
318                 result = new Long JavaDoc(curQueryEntry.getElapsedTime());
319                 break;
320             case 2:
321                 result = curQueryEntry.getConnectionID();
322                 break;
323             case 3:
324                 result = curQueryEntry.getCategory();
325                 break;
326             case 4:
327                 result = curQueryEntry.getPreparedSQL();
328                 break;
329             case 5:
330                 result = curQueryEntry.getSqlStatement();
331                 break;
332
333         }
334         return result;
335     }
336
337     /*
338      * This method is the implementation of the Comparator interface.
339      * It is used for sorting the rows
340      */

341     public int compare(Object JavaDoc v1, Object JavaDoc v2) {
342
343         // the comparison is between 2 vectors, each representing a row
344
// the comparison is done between 2 objects from the different rows that are in the column that is being sorted
345

346         int ascending = ( (Integer JavaDoc) ascendCol.get(currCol)).intValue();
347         if (v1 == null && v2 == null) {
348             return 0;
349         } else if (v2 == null) { // Define null less than everything.
350
return 1 * ascending;
351         } else if (v1 == null) {
352             return -1 * ascending;
353         }
354
355         QueryEntry left = (QueryEntry) v1;
356         QueryEntry right = (QueryEntry) v2;
357
358         Object JavaDoc o1 = getRawQueryEntryColumn(left, currCol);
359         Object JavaDoc o2 = getRawQueryEntryColumn(right, currCol);
360
361         // If both values are null, return 0.
362
if (o1 == null && o2 == null) {
363             return 0;
364         } else if (o2 == null) { // Define null less than everything.
365
return 1 * ascending;
366         } else if (o1 == null) {
367             return -1 * ascending;
368         }
369
370         if (o1 instanceof Number JavaDoc && o2 instanceof Number JavaDoc) {
371             Number JavaDoc n1 = (Number JavaDoc) o1;
372             double d1 = n1.doubleValue();
373             Number JavaDoc n2 = (Number JavaDoc) o2;
374             double d2 = n2.doubleValue();
375
376             if (d1 == d2) {
377                 return 0;
378             } else if (d1 > d2) {
379                 return 1 * ascending;
380             } else {
381                 return -1 * ascending;
382             }
383
384         } else if (o1 instanceof Boolean JavaDoc && o2 instanceof Boolean JavaDoc) {
385             Boolean JavaDoc bool1 = (Boolean JavaDoc) o1;
386             boolean b1 = bool1.booleanValue();
387             Boolean JavaDoc bool2 = (Boolean JavaDoc) o2;
388             boolean b2 = bool2.booleanValue();
389
390             if (b1 == b2) {
391                 return 0;
392             } else if (b1) {
393                 return 1 * ascending;
394             } else {
395                 return -1 * ascending;
396             }
397
398         } else if (o1 instanceof Date && o2 instanceof Date) {
399
400             Date date1 = (Date) o1;
401             Date date2 = (Date) o2;
402             return date1.compareTo(date2) * ascending;
403
404         } else {
405             // default case
406
if (o1 instanceof Comparable JavaDoc && o2 instanceof Comparable JavaDoc) {
407                 Comparable JavaDoc c1 = (Comparable JavaDoc) o1;
408                 Comparable JavaDoc c2 = (Comparable JavaDoc) o2; // superflous cast, no need for it!
409

410                 try {
411                     return c1.compareTo(c2) * ascending;
412                 } catch (ClassCastException JavaDoc cce) {
413                     // forget it... we'll deal with them like 2 normal objects below.
414
}
415             }
416
417             String JavaDoc s1 = o1.toString();
418             String JavaDoc s2 = o2.toString();
419             return s1.compareTo(s2) * ascending;
420         }
421     }
422
423     /*
424      * This method sorts the rows using Java's Collections class.
425      * After sorting, it changes the state of the column -
426          * if the column was ascending, its new state is descending, and vice versa.
427      */

428     public void sort() {
429         Integer JavaDoc val = (Integer JavaDoc) ascendCol.get(currCol);
430         ascendCol.remove(currCol);
431         if (val.equals(one)) // change the state of the column
432
ascendCol.add(currCol, minusOne);
433         else
434             ascendCol.add(currCol, one);
435         Collections.sort(queryEntries, this);
436     }
437
438     public void sortByColumn(int column) {
439         this.currCol = column;
440         sort();
441         fireTableDataChanged();
442     }
443
444     // Add a mouse listener to the Table to trigger a table sort
445
// when a column heading is clicked in the JTable.
446
public void addMouseListenerToHeaderInTable(JTable JavaDoc table) {
447         final ProfileStatementTableModel sorter = this;
448         final JTable JavaDoc tableView = table;
449         tableView.setColumnSelectionAllowed(false);
450         MouseAdapter listMouseListener = new MouseAdapter() {
451             public void mouseClicked(MouseEvent e) {
452                 TableColumnModel columnModel = tableView.getColumnModel();
453                 int viewColumn = columnModel.getColumnIndexAtX(e.getX());
454                 int column = tableView.convertColumnIndexToModel(viewColumn);
455                 if (e.getClickCount() == 1 && column != -1) {
456                     int shiftPressed = e.getModifiers() & InputEvent.SHIFT_MASK;
457                     boolean ascending = (shiftPressed == 0);
458                     sorter.sortByColumn(column);
459                 }
460             }
461         };
462         JTableHeader th = tableView.getTableHeader();
463         th.addMouseListener(listMouseListener);
464     }
465
466     public void sortAndUpdateTable() {
467         Collections.sort(queryEntries, this);
468         fireTableDataChanged();
469     }
470
471     public JLabel getStatementCountValueLabel() {
472         return statementCountValueLabel;
473     }
474
475     public QueryEntry getStatementDetails(int rowIndex) {
476         return (QueryEntry) queryEntries.get(rowIndex);
477     }
478
479     public void setStatementCountValueLabel(JLabel statementCountValueLabel) {
480         this.statementCountValueLabel = statementCountValueLabel;
481     }
482
483     public javax.swing.JLabel JavaDoc getStatementTimeValueLabel() {
484         return statementTimeValueLabel;
485     }
486
487     public void setStatementTimeValueLabel(javax.swing.JLabel JavaDoc
488                                            statementTimeValueLabel) {
489         this.statementTimeValueLabel = statementTimeValueLabel;
490     }
491
492     public ProfileResultTableModel getProfileResultModel() {
493         return profileResultModel;
494     }
495
496     public void setProfileResultModel(ProfileResultTableModel
497                                       profileResultModel) {
498         this.profileResultModel = profileResultModel;
499     }
500
501     public long getLowestQueryTime() {
502         return lowestQueryTime;
503     }
504
505     public long getHighestQueryTime() {
506         return highestQueryTime;
507     }
508
509     public ArrayList getQueriesBetweenTime(long lowTime, long highTime) {
510         ArrayList resultList = new ArrayList();
511         for (int i=0; i < queryEntries.size(); i++) {
512             QueryEntry curEntry = (QueryEntry) queryEntries.get(i);
513             long entryTime = curEntry.getTime();
514             if ( (entryTime >= lowTime) && (entryTime <= highTime)) {
515                 resultList.add(curEntry);
516             }
517         }
518         return resultList;
519     }
520
521     public ArrayList getQueryEntries() {
522         return queryEntries;
523     }
524
525     public SortedSet getSortedQueryEntries() {
526         return sortedQueryEntries;
527     }
528
529 }
Popular Tags