Apply formatting
[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
78                         String com1 = "INSERT INTO ProteinLog (JobID, IP, DataBegin, DataEnd, FinalStatus, ExecutionStatus, Protein) VALUES ('" + id
79                                         + "','" + job.getIP() + "','" + job.getStartingTimeStr() + "','" + job.getEndTimeStr() + "','" + finalstatus + "','"
80                                         + execstatus + "','" + protein + "');";
81                         ResultSet insert = execute(com1);
82                         if (null == insert) {
83                                 System.out.println("CassandraWriter.FormQueryTables: couldn't insert into ProteinLog");
84                                 // return 0;
85                         }
86                         if (finalstatus.equals("OK")) {
87                                 String com2 = "INSERT INTO ProteinData " + "(jobtime, JobID, ExecTime, Protein)" + " VALUES (" + job.getStartingDate()
88                                                 + ",'" + id + "'," + job.getExecutionTime() + ",'" + protein + "');";
89                                 if (null == execute(com2)) {
90                                         System.out.println("CassandraWriter.FormQueryTables: couldn't insert into ProteinData");
91                                         // return 0;
92                                 }
93
94                                 String allpredictions = "";
95                                 List<FastaSequence> pr = job.getPredictions();
96                                 for (FastaSequence pred : pr) {
97                                         String predictionname = pred.getId();
98                                         String prediction = pred.getSequence().replaceAll("\n", "");
99                                         allpredictions += "'" + predictionname + "':'" + prediction + "',";
100                                 }
101                                 String final_prediction = "";
102                                 if (!allpredictions.equals("")) {
103                                         final_prediction = allpredictions.substring(0, allpredictions.length() - 1);
104                                 }
105
106                                 ResultSet results2 = execute("SELECT * FROM ProteinRow WHERE JobID = '" + job.getJobID() + "';");
107                                 if (null != results2 && results2.isExhausted()) {
108                                         String com3 = "INSERT INTO ProteinRow (Protein, JobID, Predictions) VALUES ('" + protein + "','" + id + "',{"
109                                                         + final_prediction + "});";
110                                         if (null == execute(com3)) {
111                                                 System.out.println("CassandraWriter.FormQueryTables: couldn't insert into ProteinRow");
112                                                 return 0;
113                                         }
114                                 }
115                         } else {
116                                 String com5 = "INSERT INTO FailLog (jobtime, JobID, ExecTime, ip, FinalStatus) VALUES (" + job.getStartingDate() + ",'"
117                                                 + id + "'," + job.getExecutionTime() + ",'" + job.getIP() + "', '" + finalstatus + "');";
118                                 if (null == execute(com5)) {
119                                         System.out.println("CassandraWriter.FormQueryTables: couldn't insert into FailLog");
120                                         return 0;
121                                 }
122                         }
123
124                         // update Main parameters if the job is the earliest job so far
125                         ResultSet results3 = execute("SELECT * FROM MainParameters WHERE Name = 'EarliestJobDate';");
126                         if (null == results3) {
127                                 System.out.println("CassandraWriter.FormQueryTables: couldn't get results from MainParameters");
128                                 // return 0;
129                         }
130                         boolean updateparameter = true;
131                         if (!results3.isExhausted()) {
132                                 Row r = results3.one();
133                                 if (job.getStartingDate() >= Long.parseLong(r.getString("Value")))
134                                         updateparameter = false;
135                         }
136                         if (updateparameter) {
137                                 String com6 = "INSERT INTO MainParameters (Name, Value) VALUES ('EarliestJobDate','" + job.getStartingDate() + "');";
138                                 if (null == execute(com6)) {
139                                         System.out.println("CassandraWriter.FormQueryTables: couldn't insert into MainParameters");
140                                         return 0;
141                                 }
142                         }
143
144                         // update internal job counts (used by the Daily Statistics
145                         // requests)
146                         // TODO I don't like the bit of code. There should not be so many
147                         // counters...
148                         int njobsTotal = 1;
149                         int njobsOk = 0;
150                         int njobsStop = 0;
151                         int njobsError = 0;
152                         int njobsTimeOut = 0;
153                         if (finalstatus.equals("OK"))
154                                 njobsOk = 1;
155                         else if (finalstatus.equals("TIMEDOUT"))
156                                 njobsTimeOut = 1;
157                         else if (finalstatus.equals("JPREDERROR"))
158                                 njobsError = 1;
159                         else if (finalstatus.equals("STOPPED"))
160                                 njobsStop = 1;
161                         ResultSet results4 = execute("SELECT * FROM JobDateInfo WHERE jobday = " + job.getStartingDate() + ";");
162                         if (null == results4) {
163                                 System.out.println("CassandraWriter.FormQueryTables: couldn't get data from JobDateInfo");
164                                 // return 0;
165                         }
166                         if (!results4.isExhausted()) {
167                                 Row r = results4.one();
168                                 njobsTotal += r.getLong("Total");
169                                 njobsOk += r.getLong("TotalOK");
170                                 njobsError += r.getLong("TotalError");
171                                 njobsStop += r.getLong("TotalStopped");
172                                 njobsTimeOut += r.getLong("TotalTimeOut");
173                         }
174                         String com = "INSERT INTO JobDateInfo " + "(jobday, Total, TotalOK, TotalStopped, TotalError, TotalTimeOut)" + " VALUES ("
175                                         + job.getStartingDate() + "," + njobsTotal + "," + njobsOk + "," + njobsStop + "," + njobsError + "," + njobsTimeOut
176                                         + ");";
177                         if (null == execute(com)) {
178                                 System.out.println("CassandraWriter.FormQueryTables: couldn't insert into JobDateInfo");
179                                 // return 0;
180                         }
181                         return 1;
182                 }
183                 return 0;
184         }
185
186         /*
187          * insert data from a real Jpred job: timing+IP, Execution Status, Final
188          * status, protein sequence, predictions, alignment, LOG and tar.gz files
189          */
190         public int ArchiveData(JpredJob job, String archivepath) {
191                 if (JobisNotArchived(job.getJobID())) {
192                         String id = job.getJobID();
193                         String log = job.getLog().replaceAll("'", "");
194                         String com = "INSERT INTO JpredArchive (JobID, Protein, IP, StartTime, ExecTime, FinalStatus, ExecutionStatus, LOG, ArchiveLink) VALUES ('"
195                                         + id
196                                         + "','"
197                                         + job.getProtein()
198                                         + "','"
199                                         + job.getIP()
200                                         + "',"
201                                         + job.getStartingTime()
202                                         + ","
203                                         + job.getExecutionTime()
204                                         + ",'" + job.getFinalStatus() + "','" + job.getExecutionStatus() + "','" + log + "','" + archivepath + "');";
205                         if (null == execute(com)) {
206                                 System.out.println("CassandraWriter.ArchiveData: couldn't insert into JpredArchive");
207                         }
208                         List<FastaSequence> predictions = job.getPredictions();
209                         for (FastaSequence p : predictions) {
210                                 if (null == execute("UPDATE JpredArchive SET predictions = predictions + {'" + p.getId() + "':'"
211                                                 + p.getSequence().replaceAll("\n", "") + "'} WHERE JobID = '" + id + "';")) {
212                                         System.out.println("CassandraWriter.ArchiveData: couldn't update data in JpredArchive");
213                                 }
214                         }
215
216                         List<FastaSequence> seqs = job.getAlignment();
217
218                         for (FastaSequence s : seqs) {
219                                 String com2 = "UPDATE JpredArchive SET alignment = alignment + {'" + s.getId() + "':'"
220                                                 + s.getSequence().replaceAll("\n", "") + "'} WHERE JobID = '" + id + "';";
221                                 if (null == execute(com2)) {
222                                         System.out.println("CassandraWriter.ArchiveData: couldn't update data in JpredArchive");
223                                 }
224                         }
225                         return 1;
226                 }
227                 return 0;
228         }
229
230 }