Refactoring and code style improving
[jabaws.git] / webservices / compbio / stat / collector / StatDB.java
1 /* Copyright (c) 2011 Peter Troshin\r
2  *  \r
3  *  JAva Bioinformatics Analysis Web Services (JABAWS) @version: 2.0     \r
4  * \r
5  *  This library is free software; you can redistribute it and/or modify it under the terms of the\r
6  *  Apache License version 2 as published by the Apache Software Foundation\r
7  * \r
8  *  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\r
9  *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Apache \r
10  *  License for more details.\r
11  * \r
12  *  A copy of the license is in apache_license.txt. It is also available here:\r
13  * @see: http://www.apache.org/licenses/LICENSE-2.0.txt\r
14  * \r
15  * Any republication or derived work distributed in source code form\r
16  * must include this copyright and license notice.\r
17  */\r
18 package compbio.stat.collector;\r
19 \r
20 import java.sql.Connection;\r
21 import java.sql.DriverManager;\r
22 import java.sql.PreparedStatement;\r
23 import java.sql.ResultSet;\r
24 import java.sql.SQLException;\r
25 import java.sql.Statement;\r
26 import java.sql.Timestamp;\r
27 import java.util.ArrayList;\r
28 import java.util.Date;\r
29 import java.util.List;\r
30 import java.util.Set;\r
31 \r
32 import org.apache.log4j.Logger;\r
33 \r
34 import compbio.engine.conf.PropertyHelperManager;\r
35 import compbio.util.Util;\r
36 import compbio.ws.client.Services;\r
37 \r
38 /**\r
39  * The database must be stored in the application root directory and called\r
40  * "ExecutionStatistic"\r
41  * \r
42  * @author pvtroshin\r
43  * \r
44  */\r
45 public class StatDB {\r
46 \r
47         private static final String driver = "org.apache.derby.jdbc.EmbeddedDriver";\r
48         private static final String protocol = "jdbc:derby:";\r
49         private static final String statDBName = "ExecutionStatistic";\r
50 \r
51         private static final Logger log = Logger.getLogger(StatDB.class);\r
52 \r
53         static Connection conn;\r
54 \r
55         private synchronized static Connection getDBConnection() throws SQLException {\r
56 \r
57                 if (conn != null && !conn.isClosed()) {\r
58                         return conn;\r
59                 } else {\r
60                         try {\r
61                                 String dbpath = PropertyHelperManager.getLocalPath();\r
62                                 log.info("Looking for JABAWS access statistics database at: " + dbpath);\r
63                                 System.setProperty("derby.system.home", dbpath);\r
64                                 // Apparently under Tomcat webapp you cannot rely on Java\r
65                                 // auto discovery and have to register the driver explicitly\r
66                                 Class.forName(driver);\r
67                                 conn = DriverManager.getConnection(protocol + statDBName + ";create=false");\r
68 \r
69                                 conn.setAutoCommit(true);\r
70                                 /*\r
71                                  * Runtime.getRuntime().addShutdownHook(new Thread() {\r
72                                  * \r
73                                  * @Override public void run() { shutdownDBServer(); } });\r
74                                  */\r
75                         } catch (ClassNotFoundException e) {\r
76                                 log.error(e.getMessage(), e);\r
77                         }\r
78                 }\r
79                 return conn;\r
80         }\r
81 \r
82         public StatDB() throws SQLException {\r
83                 this.conn = getDBConnection();\r
84         }\r
85 \r
86         /**\r
87          * Connect to test database\r
88          * \r
89          * @param ignored\r
90          * @throws SQLException\r
91          */\r
92         StatDB(boolean ignored) throws SQLException {\r
93                 this.conn = getTestDBConnection();\r
94         }\r
95 \r
96         private static Connection getTestDBConnection() throws SQLException {\r
97                 System.setProperty("derby.system.home", "testsrc/testdata");\r
98                 Connection conn = DriverManager.getConnection(protocol + statDBName\r
99                                 + ";create=false");\r
100                 conn.setAutoCommit(true);\r
101                 log.debug("Connecting to the TEST database!");\r
102                 return conn;\r
103         }\r
104 \r
105         // ServiceName,jobname,start,finish,inputSize,resultSize,isCancelled,isCollected\r
106         /**\r
107          * \r
108          * rs.getBoolean(i) will return true for any non-zero value and false for 0\r
109          * on SMALLINT data column.\r
110          * \r
111          * @throws SQLException\r
112          */\r
113         private void createStatTable() throws SQLException {\r
114 \r
115                 /*\r
116                  * Creating a statement object that we can use for running various SQL\r
117                  * statements commands against the database.\r
118                  */\r
119                 Statement s = conn.createStatement();\r
120                 String create = "create table exec_stat("\r
121                                 + "number INT GENERATED ALWAYS AS IDENTITY,"\r
122                                 + "service_name VARCHAR(15) NOT NULL, "\r
123                                 + "cluster_job_id VARCHAR(30), "\r
124                                 + "job_id VARCHAR(35) NOT NULL PRIMARY KEY, "\r
125                                 + "start TIMESTAMP," + "finish TIMESTAMP,"\r
126                                 + "inputsize BIGINT," + "resultsize BIGINT,"\r
127                                 + "isCancelled SMALLINT NOT NULL,"\r
128                                 + "isCollected SMALLINT NOT NULL, "\r
129                                 + "isClusterJob SMALLINT NOT NULL)";\r
130                 // We create a table...\r
131                 log.debug(create);\r
132                 s.execute(create);\r
133                 s.close();\r
134                 conn.close();\r
135         }\r
136 \r
137         static void clearStatTable() throws SQLException {\r
138                 Connection conn = getDBConnection();\r
139                 String query = "delete from exec_stat";\r
140                 Statement st = conn.createStatement();\r
141                 st.executeUpdate(query);\r
142                 st.close();\r
143                 conn.commit();\r
144                 conn.close();\r
145         }\r
146 \r
147         void insertData(Set<JobStat> jobstatus) throws SQLException {\r
148                 log.info("Inserting " + jobstatus.size()\r
149                                 + " new records into the statistics database");\r
150 \r
151                 conn.setAutoCommit(false);\r
152                 String insert = "insert into exec_stat (service_name, cluster_job_id, job_id, start, finish, "\r
153                                 + "inputsize, resultsize, isCancelled, isCollected, isClusterJob) "\r
154                                 + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";\r
155                 PreparedStatement pstm = conn.prepareStatement(insert);\r
156                 for (JobStat js : jobstatus) {\r
157                         // Has to present\r
158                         pstm.setString(1, js.webService.toString());\r
159 \r
160                         if (!Util.isEmpty(js.clusterJobId)) {\r
161                                 pstm.setString(2, js.clusterJobId);\r
162                         } else {\r
163                                 pstm.setString(2, null);\r
164                         }\r
165                         // Has to present\r
166                         pstm.setString(3, js.jobname);\r
167 \r
168                         if (js.start != ExecutionStatCollector.UNDEFINED) {\r
169                                 pstm.setTimestamp(4, new Timestamp(js.start));\r
170                         } else {\r
171                                 pstm.setTimestamp(4, null);\r
172                         }\r
173                         if (js.finish != ExecutionStatCollector.UNDEFINED) {\r
174                                 pstm.setTimestamp(5, new Timestamp(js.finish));\r
175                         } else {\r
176                                 pstm.setTimestamp(5, null);\r
177                         }\r
178                         // -1 if UNDEFINED\r
179                         pstm.setLong(6, js.inputSize);\r
180                         // -1 if UNDEFINED\r
181                         pstm.setLong(7, js.resultSize);\r
182 \r
183                         pstm.setBoolean(8, js.isCancelled);\r
184                         pstm.setBoolean(9, js.isCollected);\r
185                         pstm.setBoolean(10, js.isClusterJob());\r
186                         pstm.executeUpdate();\r
187                 }\r
188                 conn.commit();\r
189                 conn.setAutoCommit(true);\r
190                 pstm.close();\r
191         }\r
192 \r
193         public Date getEarliestRecord() throws SQLException {\r
194                 String query = "select min(start) from exec_stat";\r
195                 Statement st = conn.createStatement();\r
196                 ResultSet res = st.executeQuery(query);\r
197                 boolean exist = res.next();\r
198                 Date date = new Date();\r
199                 if (exist) {\r
200                         date = res.getDate(1);\r
201                 }\r
202 \r
203                 res.close();\r
204                 st.close();\r
205                 return date;\r
206         }\r
207 \r
208         public int getTotalJobsCount(Timestamp from, Timestamp to)\r
209                         throws SQLException {\r
210                 String allQuery = "select count(*) from exec_stat where start BETWEEN ? and ? ";\r
211                 return getIntResult(from, to, allQuery);\r
212         }\r
213 \r
214         public int getCancelledCount(Timestamp from, Timestamp to)\r
215                         throws SQLException {\r
216                 // js.isCancelled\r
217                 String cancelledQuery = "select count(*) from exec_stat where start BETWEEN ? and ?  and  isCancelled=1 ";\r
218                 return getIntResult(from, to, cancelledQuery);\r
219         }\r
220 \r
221         public int getAbandonedCount(Timestamp from, Timestamp to)\r
222                         throws SQLException {\r
223                 // !js.isCollected && !js.isCancelled && js.hasResult()\r
224                 String abandonedQuery = "select count(*) from exec_stat where start BETWEEN ? and ? and isCollected=0 and isCancelled=0 and resultsize>0 ";\r
225                 return getIntResult(from, to, abandonedQuery);\r
226         }\r
227 \r
228         public int getIncompleteCount(Timestamp from, Timestamp to)\r
229                         throws SQLException {\r
230                 // !js.hasResult()\r
231                 String incompleteQuery = "select count(*) from exec_stat where start BETWEEN ? and ? and resultsize<=0 and isCancelled=0";\r
232                 return getIntResult(from, to, incompleteQuery);\r
233         }\r
234 \r
235         private int getIntResult(Timestamp from, Timestamp to, String query)\r
236                         throws SQLException {\r
237 \r
238                 log.debug("getIntRes: QUERY: " + query);\r
239                 log.debug("getIntRes: FROM: " + from);\r
240                 log.debug("getIntRes: TO: " + to);\r
241 \r
242                 PreparedStatement pstm = conn.prepareStatement(query);\r
243                 pstm.setTimestamp(1, from);\r
244                 pstm.setTimestamp(2, to);\r
245                 pstm.execute();\r
246                 ResultSet res = pstm.getResultSet();\r
247                 boolean exist = res.next();\r
248                 int count = 0;\r
249                 if (exist) {\r
250                         count = res.getInt(1);\r
251                 }\r
252                 log.debug("getIntRes: RES: " + count);\r
253                 res.close();\r
254                 pstm.close();\r
255                 return count;\r
256         }\r
257 \r
258         public List<JobStat> readData(Timestamp from, Timestamp to,\r
259                         Services wservice, Boolean clusterOnly) throws SQLException {\r
260 \r
261                 String query = "select service_name, cluster_job_id, job_id, start, finish, inputsize, "\r
262                                 + "resultsize, isCancelled, isCollected from exec_stat where start BETWEEN ? and ? ";\r
263 \r
264                 if (wservice != null) {\r
265                         query += " and service_name=? ";\r
266                 }\r
267 \r
268                 if (clusterOnly != null) {\r
269                         if (clusterOnly) {\r
270                                 query += " and isClusterJob!=0 ";\r
271                         } else {\r
272                                 query += " and isClusterJob=0 ";\r
273                         }\r
274                 }\r
275 \r
276                 log.debug("QUERY: " + query);\r
277                 log.debug("FROM: " + from);\r
278                 log.debug("TO: " + to);\r
279                 log.debug("WS: " + wservice);\r
280 \r
281                 PreparedStatement pstm = conn.prepareStatement(query);\r
282                 pstm.setTimestamp(1, from);\r
283                 pstm.setTimestamp(2, to);\r
284                 if (wservice != null) {\r
285                         pstm.setString(3, wservice.toString());\r
286                 }\r
287                 pstm.execute();\r
288                 List<JobStat> stats = new ArrayList<JobStat>();\r
289                 ResultSet rs = pstm.getResultSet();\r
290                 int rcount = 0;\r
291 \r
292                 while (rs.next()) {\r
293                         rcount++;\r
294                         stats.add(JobStat.newInstance(Services.getService(rs.getString(1)),\r
295                                         rs.getString(2), rs.getString(3), rs.getTimestamp(4),\r
296                                         rs.getTimestamp(5), rs.getLong(6), rs.getLong(7),\r
297                                         rs.getBoolean(8), rs.getBoolean(9)));\r
298                 }\r
299 \r
300                 log.debug("QUERY result len: " + rcount);\r
301                 rs.close();\r
302                 pstm.close();\r
303 \r
304                 return stats;\r
305         }\r
306 \r
307         /**\r
308          * Removes the job if\r
309          * \r
310          * 1) It has already been recorded\r
311          * \r
312          * 2) It has not completed and did not timeout - this is to prevent\r
313          * recording the information on the incomplete jobs.\r
314          * \r
315          * @param fsJobs\r
316          * @throws SQLException\r
317          */\r
318         public void removeRecordedJobs(Set<JobStat> fsJobs) throws SQLException {\r
319 \r
320                 String query = "select job_id from exec_stat";\r
321 \r
322                 Statement st = conn.createStatement();\r
323                 ResultSet result = st.executeQuery(query);\r
324 \r
325                 while (result.next()) {\r
326                         String recordedJob = result.getString(1);\r
327                         JobStat recStat = JobStat.newIncompleteStat(recordedJob);\r
328                         if (fsJobs.contains(recStat)) {\r
329                                 fsJobs.remove(recStat);\r
330                         }\r
331                 }\r
332                 result.close();\r
333                 st.close();\r
334         }\r
335 \r
336         public static synchronized final void shutdownDBServer() {\r
337                 // ## DATABASE SHUTDOWN SECTION ##\r
338                 /***\r
339                  * In embedded mode, an application should shut down Derby. Shutdown\r
340                  * throws the XJ015 exception to confirm success.\r
341                  ***/\r
342                 try {\r
343                         if (conn != null) {\r
344                                 conn.close();\r
345                         }\r
346                 } catch (SQLException e) {\r
347                         log.warn("Database commit failed with " + e.getLocalizedMessage());\r
348                 }\r
349                 boolean gotSQLExc = false;\r
350                 try {\r
351                         DriverManager.getConnection("jdbc:derby:;shutdown=true");\r
352                 } catch (SQLException se) {\r
353                         if (se.getSQLState().equals("XJ015")) {\r
354                                 gotSQLExc = true;\r
355                         }\r
356                 }\r
357                 if (!gotSQLExc) {\r
358                         log.warn("Database did not shut down normally");\r
359                 } else {\r
360                         log.info("Database shut down normally");\r
361                 }\r
362         }\r
363         public static void main(String[] args) {\r
364                 // This is called from Ant cleanStatTable task\r
365                 try {\r
366                         clearStatTable();\r
367                         shutdownDBServer();\r
368                 } catch (SQLException e) {\r
369                         System.err.println("Fails to clean up JABAWS stat database!");\r
370                         e.printStackTrace();\r
371                 }\r
372                 // new StatDB().createStatTable();\r
373                 // insertData(null);\r
374                 /*\r
375                  * StatDB statdb = new StatDB(); Date from = new Date();\r
376                  * from.setMonth(1); System.out.println(new\r
377                  * StatProcessor(statdb.readData( new Timestamp(from.getTime()), new\r
378                  * Timestamp(new Date().getTime()), null, null)).reportStat());\r
379                  */\r
380         }\r
381 }\r