05a03f0ff7aad6085224f64768acf3cb8415b1b9
[proteocache.git] / datadb / compbio / cassandra / CassandraWriter.java
1 package compbio.cassandra;
2
3 import java.util.List;
4
5 import org.apache.log4j.Logger;
6
7 import com.datastax.driver.core.Row;
8 import com.datastax.driver.core.Session;
9 import com.datastax.driver.core.ResultSet;
10 import com.datastax.driver.core.exceptions.QueryExecutionException;
11 import com.datastax.driver.core.exceptions.QueryValidationException;
12
13 import compbio.data.sequence.FastaSequence;
14 import compbio.engine.JpredJob;
15 import compbio.engine.ProteoCachePropertyHelperManager;
16 import compbio.util.PropertyHelper;
17
18 public class CassandraWriter {
19         private Session session;
20         private static final PropertyHelper ph = ProteoCachePropertyHelperManager.getPropertyHelper();
21         private static Logger log = Logger.getLogger(CassandraNativeConnector.class);
22
23         CassandraWriter() {
24                 Session inis = CassandraNativeConnector.getSession();
25                 setSession(inis);
26         }
27
28         public void setSession(Session s) {
29                 assert s != null;
30                 session = s;
31         }
32
33         private ResultSet execute(String command) {
34                 try {
35                         ResultSet results = session.execute(command);
36                         return results;
37                 } catch (QueryExecutionException e) {
38                         String mess = "CassandraWriter: query execution exception...";
39                         System.out.println(mess);
40                         log.error(mess);
41                         log.error(e.getLocalizedMessage(), e.getCause());
42                         return null;
43                 } catch (QueryValidationException e) {
44                         String mess = "CassandraWriter: query validation exception... Command: " + command;
45                         System.out.println(mess);
46                         log.error(mess);
47                         log.error(e.getLocalizedMessage(), e.getCause());
48                         return null;
49                 }
50         }
51
52         public boolean JobisNotInsterted(String jobid) {
53                 ResultSet results = execute("SELECT * FROM ProteinLog WHERE JobID = '" + jobid + "';");
54                 if (null != results && results.isExhausted()) {
55                         return true;
56                 }
57                 return false;
58         }
59
60         public boolean JobisNotArchived(String jobid) {
61                 ResultSet results = execute("SELECT * FROM JpredArchive WHERE JobID = '" + jobid + "';");
62                 if (null != results && results.isExhausted()) {
63                         return true;
64                 }
65                 return false;
66         }
67
68         /*
69          * inserting data into the tables for queries
70          */
71         public int FormQueryTables(JpredJob job) {
72                 if (JobisNotInsterted(job.getJobID())) {
73                         String id = job.getJobID();
74                         String protein = job.getProtein();
75                         String finalstatus = job.getFinalStatus();
76                         String execstatus = job.getExecutionStatus();
77                         String programmeName = job.getProgrammeName();
78                         String version = job.getVersion();
79
80                         String com1 = "INSERT INTO ProteinLog (JobID, IP, DataBegin, DataEnd, FinalStatus, ExecutionStatus, Protein, ProgrammeName, Version) VALUES ('" + id
81                                         + "','" + job.getIP() + "','" + job.getStartingTimeStr() + "','" + job.getEndTimeStr() + "','" + finalstatus + "','"
82                                         + execstatus + "','" + protein + "','" + programmeName + "','" + version + "');";
83                         ResultSet insert = execute(com1);
84                         if (null == insert) {
85                                 System.out.println("CassandraWriter.FormQueryTables: couldn't insert into ProteinLog");
86                                 // return 0;
87                         }
88                         if (finalstatus.equals("OK")) {
89                                 String com2 = "INSERT INTO ProteinData " + "(jobtime, JobID, ExecTime, Protein)" + " VALUES (" + job.getStartingDate()
90                                                 + ",'" + id + "'," + job.getExecutionTime() + ",'" + protein + "');";
91                                 if (null == execute(com2)) {
92                                         System.out.println("CassandraWriter.FormQueryTables: couldn't insert into ProteinData");
93                                         // return 0;
94                                 }
95
96                                 String allpredictions = "";
97                                 List<FastaSequence> pr = job.getPredictions();
98                                 for (FastaSequence pred : pr) {
99                                         String predictionname = pred.getId();
100                                         String prediction = pred.getSequence().replaceAll("\n", "");
101                                         allpredictions += "'" + predictionname + "':'" + prediction + "',";
102                                 }
103                                 String final_prediction = "";
104                                 if (!allpredictions.equals("")) {
105                                         final_prediction = allpredictions.substring(0, allpredictions.length() - 1);
106                                 }
107
108                                 ResultSet results2 = execute("SELECT * FROM ProteinRow WHERE JobID = '" + job.getJobID() + "';");
109                                 if (null != results2 && results2.isExhausted()) {
110                                         String com3 = "INSERT INTO ProteinRow (Protein, JobID, Predictions) VALUES ('" + protein + "','" + id + "',{"
111                                                         + final_prediction + "});";
112                                         if (null == execute(com3)) {
113                                                 System.out.println("CassandraWriter.FormQueryTables: couldn't insert into ProteinRow");
114                                                 return 0;
115                                         }
116                                 }
117                         } else {
118                                 String com5 = "INSERT INTO FailLog (jobtime, JobID, ExecTime, ip, FinalStatus) VALUES (" + job.getStartingDate() + ",'"
119                                                 + id + "'," + job.getExecutionTime() + ",'" + job.getIP() + "', '" + finalstatus + "');";
120                                 if (null == execute(com5)) {
121                                         System.out.println("CassandraWriter.FormQueryTables: couldn't insert into FailLog");
122                                         return 0;
123                                 }
124                         }
125
126                         // update Main parameters if the job is the earliest job so far
127                         ResultSet results3 = execute("SELECT * FROM MainParameters WHERE Name = 'EarliestJobDate';");
128                         if (null == results3) {
129                                 System.out.println("CassandraWriter.FormQueryTables: couldn't get results from MainParameters");
130                                 // return 0;
131                         }
132                         boolean updateparameter = true;
133                         if (!results3.isExhausted()) {
134                                 Row r = results3.one();
135                                 if (job.getStartingDate() >= Long.parseLong(r.getString("Value")))
136                                         updateparameter = false;
137                         }
138                         if (updateparameter) {
139                                 String com6 = "INSERT INTO MainParameters (Name, Value) VALUES ('EarliestJobDate','" + job.getStartingDate() + "');";
140                                 if (null == execute(com6)) {
141                                         System.out.println("CassandraWriter.FormQueryTables: couldn't insert into MainParameters");
142                                         return 0;
143                                 }
144                         }
145
146                         // update internal job counts (used by the Daily Statistics
147                         // requests)
148                         // TODO I don't like the bit of code. There should not be so many
149                         // counters...
150                         int njobsTotal = 1;
151                         int njobsOk = 0;
152                         int njobsStop = 0;
153                         int njobsError = 0;
154                         int njobsTimeOut = 0;
155                         if (finalstatus.equals("OK"))
156                                 njobsOk = 1;
157                         else if (finalstatus.equals("TIMEDOUT"))
158                                 njobsTimeOut = 1;
159                         else if (finalstatus.equals("JPREDERROR"))
160                                 njobsError = 1;
161                         else if (finalstatus.equals("STOPPED"))
162                                 njobsStop = 1;
163                         ResultSet results4 = execute("SELECT * FROM JobDateInfo WHERE jobday = " + job.getStartingDate() + ";");
164                         if (null == results4) {
165                                 System.out.println("CassandraWriter.FormQueryTables: couldn't get data from JobDateInfo");
166                                 // return 0;
167                         }
168                         if (!results4.isExhausted()) {
169                                 Row r = results4.one();
170                                 njobsTotal += r.getLong("Total");
171                                 njobsOk += r.getLong("TotalOK");
172                                 njobsError += r.getLong("TotalError");
173                                 njobsStop += r.getLong("TotalStopped");
174                                 njobsTimeOut += r.getLong("TotalTimeOut");
175                         }
176                         String com = "INSERT INTO JobDateInfo " + "(jobday, Total, TotalOK, TotalStopped, TotalError, TotalTimeOut)" + " VALUES ("
177                                         + job.getStartingDate() + "," + njobsTotal + "," + njobsOk + "," + njobsStop + "," + njobsError + "," + njobsTimeOut
178                                         + ");";
179                         if (null == execute(com)) {
180                                 System.out.println("CassandraWriter.FormQueryTables: couldn't insert into JobDateInfo");
181                                 // return 0;
182                         }
183                         return 1;
184                 }
185                 return 0;
186         }
187
188         /*
189          * insert data from a real Jpred job: timing+IP, Execution Status, Final
190          * status, protein sequence, predictions, alignment, LOG and tar.gz files
191          */
192         public int ArchiveData(JpredJob job, String archivepath) {
193                 if (JobisNotArchived(job.getJobID())) {
194                         String id = job.getJobID();
195                         String log = job.getLog().replaceAll("'", "");
196                         String com = "INSERT INTO JpredArchive (JobID, Protein, IP, StartTime, ExecTime, FinalStatus, ExecutionStatus, LOG, ArchiveLink, ProgrammeName, Version) VALUES ('"
197                                         + id
198                                         + "','"
199                                         + job.getProtein()
200                                         + "','"
201                                         + job.getIP()
202                                         + "',"
203                                         + job.getStartingTime()
204                                         + ","
205                                         + job.getExecutionTime()
206                                         + ",'" + job.getFinalStatus() + "','" + job.getExecutionStatus() + "','" + log + "','" + archivepath + "','" + job.getProgrammeName() + "','" + job.getVersion() + "');";
207                         if (null == execute(com)) {
208                                 System.out.println("CassandraWriter.ArchiveData: couldn't insert into JpredArchive");
209                         }
210                         List<FastaSequence> predictions = job.getPredictions();
211                         for (FastaSequence p : predictions) {
212                                 if (null == execute("UPDATE JpredArchive SET predictions = predictions + {'" + p.getId() + "':'"
213                                                 + p.getSequence().replaceAll("\n", "") + "'} WHERE JobID = '" + id + "';")) {
214                                         System.out.println("CassandraWriter.ArchiveData: couldn't update data in JpredArchive");
215                                 }
216                         }
217
218                         List<FastaSequence> seqs = job.getAlignment();
219
220                         for (FastaSequence s : seqs) {
221                                 String com2 = "UPDATE JpredArchive SET alignment = alignment + {'" + s.getId() + "':'"
222                                                 + s.getSequence().replaceAll("\n", "") + "'} WHERE JobID = '" + id + "';";
223                                 if (null == execute(com2)) {
224                                         System.out.println("CassandraWriter.ArchiveData: couldn't update data in JpredArchive");
225                                 }
226                         }
227                         return 1;
228                 }
229                 return 0;
230         }
231
232 }