View Javadoc

1   /*** DataSet.java - part of the MirkE (say murky) application for colormetric analysis emphesizing 
2    kinetics.
3    
4    Created by: Scott Menor on 21 July, 2004.
5    Last modified by: Scott Menor on 11 January, 2005
6    
7    Copyright (c) 2004 Arizona State University - Cancer Research Institute. All rights reserved.
8    
9    MirkE is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   MirkE is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18   
19   You should have received a copy of the GNU General Public License
20   along with MirkE; if not, write to the Free Software
21   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  US
22   */
23  
24  package edu.asu.cri.MirkE.dataStructures;
25  
26  import java.sql.DriverManager;
27  import java.util.List;
28  import java.util.Vector;
29  
30  import net.sf.hibernate.Session;
31  import net.sf.hibernate.SessionFactory;
32  import net.sf.hibernate.Transaction;
33  import net.sf.hibernate.cfg.Configuration;
34  import edu.asu.cri.MirkE.exceptions.MirkEApplicationException;
35  import edu.asu.cri.MirkE.exceptions.MirkESystemException;
36  import edu.asu.cri.MirkE.util.ObservableFactory;
37  
38  /*** DataSet - a JDBC database / Hibernate backed data store provides a HQL searchable collection of <code>DataPoint</code>s
39   * 
40   * TODO - for now, this is really a MultiWellPlateDataSet; need to refactor the DataSet from MultiWellPlateDataSet so this can be used for other applications
41   * @author Scott Menor
42   * @version 0.3.0, 17 january, 2005
43   */
44  public class DataSet {
45      private java.sql.Connection connection;
46      
47      private ObservableFactory observableFactory;
48      private DataPointCategoryFactory dataPointCategoryFactory;
49      /***
50       @return observableFactory
51       */
52      public ObservableFactory getObservableFactory() {
53          return this.observableFactory;
54      }
55      
56      /***
57       
58       @return dataPointCategoryFactory
59       */
60      public DataPointCategoryFactory getDataPointCategoryFactory() {
61          return this.dataPointCategoryFactory;
62      }
63      
64      /*** return the SQL database connection
65       
66       @return connection
67       */
68      public java.sql.Connection getConnection() {
69          return connection;
70      }
71      
72      /*** set the SQL database connection
73       
74       @param connection
75       */
76      public void setConnection(java.sql.Connection connection) {
77          this.connection = connection;
78      }
79      
80      private Configuration configuration;
81      
82      /*** get the Hibernate configuration
83       
84       @return configuration
85       */
86      public Configuration getConfiguration() {
87          return configuration;
88      }
89      
90      /*** set the Hibernate configuration
91       
92       @param configuration
93       */
94      public void setConfiguration(Configuration configuration) {
95          this.configuration = configuration;
96      }
97      
98      private SessionFactory sessionFactory;
99      
100     /*** get the Hibernate sessionFactory
101      * 
102      * @return sessionFactory
103      */
104     public SessionFactory getSessionFactory() {
105         return sessionFactory;
106     }
107     
108     /*** set the Hibernate sessionFactory
109      
110      @param sessionFactory
111      */
112     public void setSessionFactory(SessionFactory sessionFactory) {
113         this.sessionFactory = sessionFactory; 
114     }
115     
116     private String databaseName;
117     
118     /*** default constructor - create a hsqldb database in memory and initialize the tables for Hibernate based object persistance 
119      * @throws MirkEApplicationException
120      */
121     public DataSet() throws MirkESystemException {
122         try {
123             DriverManager.registerDriver(new org.hsqldb.jdbcDriver());
124             
125             // create a connection to an instance of hsqldb in memory
126             databaseName = "MirkE_" + System.currentTimeMillis();
127             
128             connection = DriverManager.getConnection("jdbc:hsqldb:mem:" + databaseName, "sa", "");
129             
130         } catch(Exception exception) {
131             // TODO - recover gracefully
132 //<<<<<<< DataSet.java
133             throw new MirkESystemException("Exception  save ",(Throwable)exception);
134 /*=======
135             exception.printStackTrace();
136             
137             System.exit(-1);
138 >>>>>>> 1.13*/
139         }
140         
141         try {
142             // setup Hibernate
143             configuration = new Configuration();
144             // TODO - move this to MirkE.hbm.xml so we don't have to edit this file every time we add a new class
145             configuration.addResource("DataPointCategory.hbm.xml"); 
146             configuration.addResource("DataPoint.hbm.xml"); 
147             configuration.addResource("MirkE.hbm.xml"); 
148             configuration.addResource("Magnitude.hbm.xml"); 
149             configuration.addResource("MeasuredValue.hbm.xml"); 
150             configuration.addResource("Observable.hbm.xml");
151             configuration.addResource("PlateDescription.hbm.xml"); 
152             configuration.addResource("PlateWellCategory.hbm.xml");
153             configuration.addResource("PlateWellDataPoint.hbm.xml");
154             configuration.addResource("PlateWellDescriptor.hbm.xml");
155             configuration.addResource("Unit.hbm.xml");
156             configuration.addResource("UnitValue.hbm.xml");
157             
158         } catch (net.sf.hibernate.MappingException mappingException) {
159             // TODO - recover gracefully
160             //mappingException.printStackTrace();
161             
162             //System.exit(-1);
163             
164           throw new MirkESystemException("Exception  mapping",(Throwable)mappingException);
165         }
166         
167         try {
168             sessionFactory = configuration.buildSessionFactory();
169             
170         } catch (net.sf.hibernate.HibernateException hibernateException) {
171             // TODO - recover gracefully
172             
173            // hibernateException.printStackTrace();
174             
175            // System.exit(-1);
176             throw new MirkESystemException("Exception  mapping",(Throwable)hibernateException);
177         }
178         
179         // create Hibernate tables for the DataSet 
180         
181         try {
182             
183             {
184                 String statementString = "create table DataPoints(UID integer not null primary key, timestamp timestamp)";
185                 
186                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
187                 preparedStatement.executeUpdate();
188             }
189             
190             {
191                 String statementString = "create table PlateWellDataPoints(UID integer not null primary key, timestamp timestamp, plateIdentifier char, observableName char, observedUnits char, observedValue double, plateRow char, plateColumn char)";
192                 
193                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
194                 preparedStatement.executeUpdate();
195             }
196             
197             {
198                 String statementString = "create table PlateWellDescriptors(UID integer not null primary key, plateIdentifier char, plateWellType char, plateRow char, plateColumn char)";
199                 
200                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
201                 preparedStatement.executeUpdate();
202             }
203             
204             {
205                 String statementString = "create table PlateWellCategories(UID integer not null primary key, plateIdentifier char, categoryName char, plateRow char, plateColumn char)";
206                 
207                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
208                 preparedStatement.executeUpdate();
209             }
210             
211             {
212                 String statementString = "create table PlateDescriptions(UID integer not null primary key, timestamp timestamp, plateIdentifier char, numberOfRows int, numberOfColumns int)";
213                 
214                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
215                 preparedStatement.executeUpdate();
216             }
217             
218             {
219                 String statementString = "create table dataPointDescriptorMaps(map_key integer, propertyName char, propertyValue char)";
220                 
221                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
222                 preparedStatement.executeUpdate();
223             }
224             
225             {
226                 String statementString = "create table observableToMeasuredValueMaps(map_key integer, observableIndex integer, measuredValueIndex integer)";
227                 
228                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
229                 preparedStatement.executeUpdate();
230             }
231             
232             {
233                 String statementString = "create table unitValues(UID integer not null primary key, unit_id integer, value double)";
234                 
235                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
236                 preparedStatement.executeUpdate();
237             }
238             
239             {
240                 String statementString = "create table observables(UID integer not null primary key, name CHAR)";
241                 
242                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
243                 preparedStatement.executeUpdate();
244             }
245             
246             
247             {
248                 String statementString = "create table dataPointCategories(UID integer not null primary key, categoryName CHAR, categoryType CHAR)";
249                 
250                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
251                 preparedStatement.executeUpdate();
252             }
253             
254             {
255                 String statementString = "create table dataPointCategorySets(set_key integer, dataPointIndex integer)";
256                 
257                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
258                 preparedStatement.executeUpdate();
259             }
260             
261             {
262                 String statementString = "create table measuredValues(UID integer not null primary key, unit_id integer, value double, standardDeviation double)";
263                 
264                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
265                 preparedStatement.executeUpdate();
266             }
267             
268             {
269                 String statementString = "create table UNITS(UID integer not null primary key, unitField char, unitName char, unitAbbreviation char, unitConversionMultiplier double, unitConversionOffset double)";
270                 
271                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
272                 preparedStatement.executeUpdate();
273             }
274             
275             {
276                 String statementString = "create table MAGNITUDES(UID integer not null primary key, MAGNITUDE_NAME char)";
277                 
278                 java.sql.PreparedStatement preparedStatement = connection.prepareStatement(statementString);
279                 preparedStatement.executeUpdate();
280             }
281             
282             this.observableFactory = new ObservableFactory(this);
283             this.dataPointCategoryFactory = new DataPointCategoryFactory(this);
284             
285         } catch (Exception exception) {
286 
287 			throw new MirkESystemException("Exception  save ", exception);
288 
289         }
290         
291     }
292     
293     /***
294      * 
295      * @return a new Hibernate <code>Session</code>
296      * @throws MirkEApplicationException
297      */
298     public Session getSession() throws MirkEApplicationException{
299         Session session = null;
300 
301         if (sessionFactory != null) {
302             try {
303                 session = sessionFactory.openSession(connection);
304                 
305             } catch (Exception exception) {
306                  throw new MirkEApplicationException("Exception  getSession ", exception);
307 
308             }
309         }
310         
311         return session;
312     }
313     /*** save an <code>Object</code> to the <code>DataSet</code>
314      * 
315      * @param object
316      * @throws MirkEApplicationException
317      */
318     public void save(Object object) throws MirkEApplicationException{
319         if (sessionFactory != null) {
320             try {
321                 Session session = sessionFactory.openSession(connection);
322                 Transaction transaction = session.beginTransaction();
323                 
324                 session.save(object);
325                 
326                 transaction.commit();
327                 session.close();
328             } catch (Exception exception) {
329                 throw new MirkEApplicationException("Exception  save ", exception);
330             }
331         }
332     }
333     
334     /*** remove an <code>Object</code> from the <code>DataSet</code>
335      * 
336      * @param object
337      */
338     public void delete(Object object) {
339         if (sessionFactory != null) {
340             try {
341                 Session session = sessionFactory.openSession(connection);
342                 Transaction transaction = session.beginTransaction();
343                 
344                 session.delete(object);
345                 
346                 transaction.commit();
347                 session.close();
348                 
349             } catch (Exception exception) {
350                 exception.printStackTrace();
351             }
352         }
353     }	
354     
355     /***
356      * 
357      * @return A set of all <code>Observable</code>s known to the <code>DataSet</code> 
358      * @throws MirkEApplicationException
359      */
360     public java.util.Set getObservables() throws MirkEApplicationException{
361         // TODO - use something like uniq in the query to get unique results rather than the HashSet constructor (perhaps distinct?)
362         java.util.Set observables = new java.util.HashSet(find("select p.observableName from PlateWellDataPoint as p")); 
363         
364         return observables;
365     }
366     
367     /***
368      * 
369      * @return plateIdentifiers
370      * @throws MirkEApplicationException
371      */
372     public java.util.Set getPlateIdentifiers() throws MirkEApplicationException {
373         // TODO - use something like distinct in the query to get unique results rather than the HashSet constructor
374         java.util.List plateIdentifierList = find("select p.plateIdentifier from PlateWellDataPoint as p order by p.timestamp desc");  // TODO - figure out why this doesn't actually seem to order things properly
375         java.util.Set plateIdentifiers = new java.util.LinkedHashSet(); // need a unique, ordered result set (there must be a better way; perhaps we should just use raw SQL?)
376         plateIdentifiers.addAll(plateIdentifierList);
377         
378         return plateIdentifiers;
379     }
380     
381     /***
382      * 
383      * @return categoryNames <code>Set</code> of all category names known to this <code>DataSet</code>. Cagetories represent a collection of one or more <code>DataPoint</code>(s) with a common property ('growth control'; 'media control'; 'strain 1'; etc).
384      * @throws MirkEApplicationException
385      */
386     public java.util.Set getCategoryNames() throws MirkEApplicationException {
387         java.util.List categoryNameList = find("select c.categoryName from PlateWellCategory as c");
388         java.util.Set categoryNames = new java.util.LinkedHashSet(categoryNameList); 
389         
390         return categoryNames;
391     }
392     
393     /***
394      * 
395      * @param rowNumber of a row in a multiwell plate
396      * @return label corresponding to a row in a multiwell plate ('A', 'B', 'C', 'D', etc)
397      */
398     public String rowNumberToLabel(int rowNumber) {
399         String rowLabel = "";
400         
401         rowLabel += (char)('A' + rowNumber);
402         
403         return rowLabel;
404     }
405     
406     /***
407      * 
408      * @param columnNumber of a column in a multiwell plate
409      * @return label corresponding to a column in a multiwell plate ('1', '2', '3', '4', etc)
410      */
411     public String columnNumberToColumnLabel(int columnNumber) {
412         String columnLabel = "" + (columnNumber + 1);
413         
414         return columnLabel;
415     }
416     
417     private int numberOfRows = 0;
418     
419     /***
420      * @return numberOfRows in a multiwell plate persisted in this <code>DataSet</code>
421      */
422     public int getNumberOfRows() {
423         return numberOfRows;
424     } 
425     
426     /***
427      * @return numberOfColumns in a multiwell plate persisted in this <code>DataSet</code>
428      */
429     public int getNumberOfColumns() {
430         return numberOfColumns;
431     } 
432     
433     private int numberOfColumns = 0;
434     
435     /*** Determine and set the numberOfRows and numberOfColumns of the plate
436      // TODO - refactor this out into another class (probably a subclass of DataSet -> MultiwellPlateDataSet)
437       * @throws MirkEApplicationException
438       */
439     public void computePlateDimensions() throws MirkEApplicationException {		
440         
441         java.util.List plateDescriptionList = find("from PlateDescription as d");
442         
443         java.util.Iterator iterator = plateDescriptionList.iterator();
444         
445         while (iterator.hasNext()) {
446             PlateDescription plateDescription = (PlateDescription)iterator.next();
447             
448             numberOfRows = Math.max(plateDescription.getNumberOfRows(),
449                     numberOfRows);
450             numberOfColumns = Math.max(plateDescription.getNumberOfColumns(),
451                     numberOfColumns);
452         }
453     }
454     
455     /***
456      *
457      * @return measuredPlateRowColumnVector
458      * @throws MirkEApplicationException
459      */
460     public Vector getMeasuredPlateRowColumnVector()throws MirkEApplicationException {
461         Vector measuredPlateRowColumnVector = new Vector();
462         
463         computePlateDimensions();
464         
465         for (int rowNumber=0;rowNumber<numberOfRows;rowNumber++) {
466             String rowLabel = rowNumberToLabel(rowNumber);
467             
468             for (int columnNumber=0;columnNumber<numberOfColumns;columnNumber++) {
469                 String columnLabel = columnNumberToColumnLabel(columnNumber);
470                 
471                 java.util.List plateWellDescriptorList = find("from PlateWellDescriptor as d " +
472                         "where d.plateWellType='M' and " + 
473                         "d.plateRow='"+rowLabel+"' and " + 
474                         "d.plateColumn='"+columnLabel+"'");
475                 
476                 if (plateWellDescriptorList.size() > 0) {
477                     String selectRowColumn = " o.plateRow='"+rowLabel+"' and o.plateColumn='"+columnLabel+"' ";
478                     
479                     measuredPlateRowColumnVector.add(selectRowColumn);
480                 }
481             }
482         }
483         
484         return measuredPlateRowColumnVector;
485     }
486     
487     /*** execute a database query on the DataSet
488      * @param query HQL query 
489      * @return list 
490      * @throws MirkEApplicationException
491      */
492     public java.util.List find(String query)throws MirkEApplicationException {
493         if (sessionFactory != null) {
494             try {
495                 Session session = sessionFactory.openSession(connection);
496                 Transaction transaction = session.beginTransaction();
497                 
498                 List list = session.find(query);
499                 
500                 transaction.commit();
501                 session.close();	
502                 
503                 return list;
504                 
505             } catch (Exception e) {
506                 e.printStackTrace();
507                 
508             }
509         }
510         
511         return null;
512     }
513 }