~ubuntu-branches/ubuntu/precise/weka/precise

« back to all changes in this revision

Viewing changes to weka/experiment/DatabaseResultListener.java

  • Committer: Bazaar Package Importer
  • Author(s): Soeren Sonnenburg
  • Date: 2008-02-24 09:18:45 UTC
  • Revision ID: james.westby@ubuntu.com-20080224091845-1l8zy6fm6xipbzsr
Tags: upstream-3.5.7+tut1
ImportĀ upstreamĀ versionĀ 3.5.7+tut1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 *    This program is free software; you can redistribute it and/or modify
 
3
 *    it under the terms of the GNU General Public License as published by
 
4
 *    the Free Software Foundation; either version 2 of the License, or
 
5
 *    (at your option) any later version.
 
6
 *
 
7
 *    This program is distributed in the hope that it will be useful,
 
8
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
9
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
10
 *    GNU General Public License for more details.
 
11
 *
 
12
 *    You should have received a copy of the GNU General Public License
 
13
 *    along with this program; if not, write to the Free Software
 
14
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
15
 */
 
16
 
 
17
/*
 
18
 *    DatabaseResultListener.java
 
19
 *    Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
 
20
 *
 
21
 */
 
22
 
 
23
 
 
24
package weka.experiment;
 
25
 
 
26
import weka.core.FastVector;
 
27
 
 
28
import java.sql.DatabaseMetaData;
 
29
import java.sql.ResultSet;
 
30
 
 
31
/**
 
32
 <!-- globalinfo-start -->
 
33
 * Takes results from a result producer and sends them to a database.
 
34
 * <p/>
 
35
 <!-- globalinfo-end -->
 
36
 * 
 
37
 * @author Len Trigg (trigg@cs.waikato.ac.nz)
 
38
 * @version $Revision: 1.13 $
 
39
 */
 
40
public class DatabaseResultListener 
 
41
  extends DatabaseUtils
 
42
  implements ResultListener  {
 
43
 
 
44
  /** for serialization */
 
45
  static final long serialVersionUID = 7388014746954652818L;  
 
46
  
 
47
  /** The ResultProducer to listen to */
 
48
  protected ResultProducer m_ResultProducer;
 
49
  
 
50
  /** The name of the current results table */
 
51
  protected String m_ResultsTableName;
 
52
 
 
53
  /** True if debugging output should be printed */
 
54
  protected boolean m_Debug = true;
 
55
 
 
56
  /** Holds the name of the key field to cache upon, or null if no caching */
 
57
  protected String m_CacheKeyName = "";
 
58
 
 
59
  /** Stores the index of the key column holding the cache key data */
 
60
  protected int m_CacheKeyIndex;
 
61
 
 
62
  /** Stores the key for which the cache is valid */
 
63
  protected Object [] m_CacheKey;
 
64
 
 
65
  /** Stores the cached values */
 
66
  protected FastVector m_Cache = new FastVector();
 
67
 
 
68
 
 
69
  /**
 
70
   * Returns a string describing this result listener
 
71
   * @return a description of the result listener suitable for
 
72
   * displaying in the explorer/experimenter gui
 
73
   */
 
74
  public String globalInfo() {
 
75
    return "Takes results from a result producer and sends them to a "
 
76
      +"database.";
 
77
  }
 
78
 
 
79
  /**
 
80
   * Sets up the database drivers
 
81
   *
 
82
   * @throws Exception if an error occurs
 
83
   */
 
84
  public DatabaseResultListener() throws Exception {
 
85
 
 
86
    super();
 
87
  }
 
88
 
 
89
  /**
 
90
   * Prepare for the results to be received.
 
91
   *
 
92
   * @param rp the ResultProducer that will generate the results
 
93
   * @throws Exception if an error occurs during preprocessing.
 
94
   */
 
95
  public void preProcess(ResultProducer rp) throws Exception {
 
96
 
 
97
    m_ResultProducer = rp;
 
98
    // Connect to the database and find out what table corresponds to this
 
99
    //   ResultProducer
 
100
    updateResultsTableName(m_ResultProducer);
 
101
  }
 
102
  
 
103
  /**
 
104
   * Perform any postprocessing. When this method is called, it indicates
 
105
   * that no more results will be sent that need to be grouped together
 
106
   * in any way.
 
107
   *
 
108
   * @param rp the ResultProducer that generated the results
 
109
   * @throws Exception if an error occurs
 
110
   */
 
111
  public void postProcess(ResultProducer rp) throws Exception {
 
112
 
 
113
    if (m_ResultProducer != rp) {
 
114
      throw new Error("Unrecognized ResultProducer calling postProcess!!");
 
115
    }
 
116
    disconnectFromDatabase();
 
117
  }
 
118
  
 
119
  /**
 
120
   * Determines if there are any constraints (imposed by the
 
121
   * destination) on any additional measures produced by
 
122
   * resultProducers. Null should be returned if there are NO
 
123
   * constraints, otherwise a list of column names should be
 
124
   * returned as an array of Strings. In the case of
 
125
   * DatabaseResultListener, the structure of an existing database
 
126
   * will impose constraints.
 
127
   * @param rp the ResultProducer to which the constraints will apply
 
128
   * @return an array of column names to which resutltProducer's
 
129
   * results will be restricted.
 
130
   * @throws Exception if an error occurs.
 
131
   */
 
132
  public String [] determineColumnConstraints(ResultProducer rp) 
 
133
    throws Exception {
 
134
    FastVector cNames = new FastVector();
 
135
    updateResultsTableName(rp);
 
136
    DatabaseMetaData dbmd = m_Connection.getMetaData();
 
137
    ResultSet rs;
 
138
    // gets a result set where each row is info on a column
 
139
    if (m_checkForUpperCaseNames) {
 
140
      rs = dbmd.getColumns(null, null, m_ResultsTableName.toUpperCase(), null);
 
141
    } else {
 
142
      rs = dbmd.getColumns(null, null, m_ResultsTableName, null);
 
143
    }
 
144
    boolean tableExists=false;
 
145
    int numColumns = 0;
 
146
   
 
147
    while (rs.next()) {
 
148
      tableExists = true;
 
149
      // column four contains the column name
 
150
      if (rs.getString(4).toLowerCase().startsWith("measure")) {
 
151
        numColumns++;
 
152
        cNames.addElement(rs.getString(4));
 
153
      }
 
154
    }
 
155
 
 
156
    // no constraints on any additional measures if the table does not exist
 
157
    if (!tableExists) {
 
158
      return null;
 
159
    }
 
160
 
 
161
    // a zero element array indicates maximum constraint
 
162
    String [] columnNames = new String [numColumns];
 
163
    for (int i=0;i<numColumns;i++) {
 
164
      columnNames[i] = (String)(cNames.elementAt(i));
 
165
    }
 
166
 
 
167
    return columnNames;
 
168
  }
 
169
 
 
170
  /**
 
171
   * Submit the result to the appropriate table of the database
 
172
   *
 
173
   * @param rp the ResultProducer that generated the result
 
174
   * @param key The key for the results.
 
175
   * @param result The actual results.
 
176
   * @throws Exception if the result couldn't be sent to the database
 
177
   */
 
178
  public void acceptResult(ResultProducer rp, Object[] key, Object[] result) 
 
179
    throws Exception {
 
180
 
 
181
    if (m_ResultProducer != rp) {
 
182
      throw new Error("Unrecognized ResultProducer calling acceptResult!!");
 
183
    }
 
184
 
 
185
    // null result could occur from a chain of doRunKeys calls
 
186
    if (result != null) {
 
187
      putResultInTable(m_ResultsTableName, rp, key, result);      
 
188
    }
 
189
  }
 
190
 
 
191
  /**
 
192
   * Always says a result is required. If this is the first call,
 
193
   * prints out the header for the Database output.
 
194
   *
 
195
   * @param rp the ResultProducer wanting to generate the result
 
196
   * @param key The key for which a result may be needed.
 
197
   * @return true if the result should be calculated.
 
198
   * @throws Exception if the database couldn't be queried
 
199
   */
 
200
  public boolean isResultRequired(ResultProducer rp, Object[] key)
 
201
    throws Exception {
 
202
    
 
203
    if (m_ResultProducer != rp) {
 
204
      throw new Error("Unrecognized ResultProducer calling isResultRequired!");
 
205
    }
 
206
    if (m_Debug) {
 
207
      System.err.print("Is result required...");
 
208
      for (int i = 0; i < key.length; i++) {
 
209
        System.err.print(" " + key[i]);
 
210
      }
 
211
      System.err.flush();
 
212
    }
 
213
    boolean retval = false;
 
214
 
 
215
    // Check the key cache first
 
216
    if (!m_CacheKeyName.equals("")) {
 
217
      if (!isCacheValid(key)) {
 
218
        loadCache(rp, key);
 
219
      }
 
220
      retval = !isKeyInCache(rp, key);
 
221
    } else {
 
222
      // Ask whether the results are needed
 
223
      retval = !isKeyInTable(m_ResultsTableName,
 
224
                                             rp, key);
 
225
    }
 
226
    
 
227
    if (m_Debug) {
 
228
      System.err.println(" ..." + (retval ? "required" : "not required")
 
229
                         + (m_CacheKeyName.equals("") ? "" : " (cache)"));
 
230
      System.err.flush();
 
231
    }
 
232
    return retval;
 
233
  }
 
234
 
 
235
  
 
236
  /**
 
237
   * Determines the table name that results will be inserted into. If
 
238
   * required: a connection will be opened, an experiment index table created,
 
239
   * and the results table created.
 
240
   *
 
241
   * @param rp the ResultProducer
 
242
   * @throws Exception if an error occurs
 
243
   */
 
244
  protected void updateResultsTableName(ResultProducer rp) throws Exception {
 
245
 
 
246
    if (!isConnected()) {
 
247
      connectToDatabase();
 
248
    }
 
249
    if (!experimentIndexExists()) {
 
250
      createExperimentIndex();
 
251
    }
 
252
 
 
253
    String tableName = getResultsTableName(rp);
 
254
    if (tableName == null) {
 
255
      tableName = createExperimentIndexEntry(rp);
 
256
    }
 
257
    if (!tableExists(tableName)) {
 
258
      createResultsTable(rp, tableName);
 
259
    }
 
260
    m_ResultsTableName = tableName;
 
261
  }
 
262
 
 
263
  /**
 
264
   * Returns the tip text for this property
 
265
   * @return tip text for this property suitable for
 
266
   * displaying in the explorer/experimenter gui
 
267
   */
 
268
  public String cacheKeyNameTipText() {
 
269
    return "Set the name of the key field by which to cache.";
 
270
  }
 
271
  
 
272
  /**
 
273
   * Get the value of CacheKeyName.
 
274
   *
 
275
   * @return Value of CacheKeyName.
 
276
   */
 
277
  public String getCacheKeyName() {
 
278
    
 
279
    return m_CacheKeyName;
 
280
  }
 
281
 
 
282
  
 
283
  /**
 
284
   * Set the value of CacheKeyName.
 
285
   *
 
286
   * @param newCacheKeyName Value to assign to CacheKeyName.
 
287
   */
 
288
  public void setCacheKeyName(String newCacheKeyName) {
 
289
    
 
290
    m_CacheKeyName = newCacheKeyName;
 
291
  }
 
292
 
 
293
  
 
294
 
 
295
  /**
 
296
   * Checks whether the current cache contents are valid for the supplied
 
297
   * key.
 
298
   *
 
299
   * @param key the results key
 
300
   * @return true if the cache contents are valid for the key given
 
301
   */
 
302
  protected boolean isCacheValid(Object []key) {
 
303
 
 
304
    if (m_CacheKey == null) {
 
305
      return false;
 
306
    }
 
307
    if (m_CacheKey.length != key.length) {
 
308
      return false;
 
309
    }
 
310
    for (int i = 0; i < key.length; i++) {
 
311
      if ((i != m_CacheKeyIndex) && (!m_CacheKey[i].equals(key[i]))) {
 
312
        return false;
 
313
      }
 
314
    }
 
315
    return true;
 
316
  }
 
317
 
 
318
  /**
 
319
   * Returns true if the supplied key is in the key cache (and thus
 
320
   * we do not need to execute a database query).
 
321
   *
 
322
   * @param rp the ResultProducer the key belongs to.
 
323
   * @param key the result key
 
324
   * @return true if the key is in the key cache
 
325
   * @throws Exception if an error occurs
 
326
   */
 
327
  protected boolean isKeyInCache(ResultProducer rp, Object[] key)
 
328
    throws Exception {
 
329
 
 
330
    for (int i = 0; i < m_Cache.size(); i++) {
 
331
      if (m_Cache.elementAt(i).equals(key[m_CacheKeyIndex])) {
 
332
        return true;
 
333
      }
 
334
    }
 
335
    return false;
 
336
  }
 
337
  
 
338
  /**
 
339
   * Executes a database query to fill the key cache
 
340
   *
 
341
   * @param rp the ResultProducer the key belongs to
 
342
   * @param key the key
 
343
   * @throws Exception if an error occurs
 
344
   */
 
345
  protected void loadCache(ResultProducer rp, Object[] key)
 
346
    throws Exception {
 
347
 
 
348
    System.err.print(" (updating cache)"); System.err.flush();
 
349
    m_Cache.removeAllElements();
 
350
    m_CacheKey = null;
 
351
    String query = "SELECT Key_" + m_CacheKeyName
 
352
      + " FROM " + m_ResultsTableName;
 
353
    String [] keyNames = rp.getKeyNames();
 
354
    if (keyNames.length != key.length) {
 
355
      throw new Exception("Key names and key values of different lengths");
 
356
    }
 
357
    m_CacheKeyIndex = -1;
 
358
    for (int i = 0; i < keyNames.length; i++) {
 
359
      if (keyNames[i].equalsIgnoreCase(m_CacheKeyName)) {
 
360
        m_CacheKeyIndex = i;
 
361
        break;
 
362
      }
 
363
    }
 
364
    if (m_CacheKeyIndex == -1) {
 
365
      throw new Exception("No key field named " + m_CacheKeyName
 
366
                          + " (as specified for caching)");
 
367
    }
 
368
    boolean first = true;
 
369
    for (int i = 0; i < key.length; i++) {
 
370
      if ((key[i] != null) && (i != m_CacheKeyIndex)) {
 
371
        if (first) {
 
372
          query += " WHERE ";
 
373
          first = false;
 
374
        } else {
 
375
          query += " AND ";
 
376
        }
 
377
        query += "Key_" + keyNames[i] + '=';
 
378
        if (key[i] instanceof String) {
 
379
          query += "'" + DatabaseUtils.processKeyString(key[i].toString()) + "'";
 
380
        } else {
 
381
          query += key[i].toString();
 
382
        }
 
383
      }
 
384
    }
 
385
    ResultSet rs = select(query);
 
386
    while (rs.next()) {
 
387
      String keyVal = rs.getString(1);
 
388
      if (!rs.wasNull()) {
 
389
        m_Cache.addElement(keyVal);
 
390
      }
 
391
    }
 
392
    close(rs);
 
393
    m_CacheKey = (Object [])key.clone();
 
394
  }
 
395
  
 
396
}