1. Move query jsps into a separate directory
[proteocache.git] / server / compbio / statistic / CassandraRequester.java
1 package compbio.statistic;
2
3 import java.text.ParseException;
4 import java.text.SimpleDateFormat;
5 import java.util.ArrayList;
6 import java.util.Calendar;
7 import java.util.Date;
8 import java.util.List;
9 import java.util.Map;
10
11 import compbio.cassandra.DateBean;
12 import compbio.cassandra.ProteinBean;
13 import compbio.cassandra.CassandraNativeConnector;
14 import compbio.cassandra.CassandraReader;
15 import compbio.cassandra.DataBase;
16 import compbio.cassandra.Pair;
17 import compbio.cassandra.JobBean;
18 import compbio.cassandra.Total;
19 import compbio.cassandra.TotalByCounterBean;
20 import compbio.cassandra.TotalJobsStatisticBean;
21 import compbio.cassandra.UserBean;
22 import compbio.engine.JobStatus;
23
24 public class CassandraRequester {
25         private CassandraReader db = new CassandraReader();
26         private ArrayList<DataBase> query;
27         private static long currentDate = 0;
28         private static long earlestDate = 0;
29         private final static SimpleDateFormat formatYYMMDD = new SimpleDateFormat("yyyy/MM/dd");
30         private final static SimpleDateFormat formatDDMMYY = new SimpleDateFormat("dd/MM/yyyy");
31
32         /*
33          * query: execution time for the period from date1 till date2
34          */
35         public List<DataBase> extractExecutionTime(String date1, String date2) {
36                 if (null == date1) {
37                         date1 = "1970/1/1";
38                 }
39                 if (null == date2) {
40                         date1 = "2100/1/1";
41                 }
42                 if (!isThisDateValid(date1, formatYYMMDD) || !isThisDateValid(date2, formatYYMMDD)) {
43                         System.out.println("CassandraRequester.extractExecutionTime: wrong format for date1 " + date1 + "or date2 " + date2);
44                         return null;
45                 }
46                 SetDateRange();
47                 int nbins = 5;
48                 long dateStart = DateParsing(date1, formatYYMMDD);
49                 long dateEnd = DateParsing(date2, formatYYMMDD);
50                 if (dateEnd < earlestDate || dateStart > currentDate || dateStart > dateEnd)
51                         return null;
52                 if (dateStart < earlestDate)
53                         dateStart = earlestDate;
54                 if (dateEnd > currentDate)
55                         dateStart = currentDate;
56
57                 Calendar start = Calendar.getInstance();
58                 start.setTime(new Date(dateStart));
59                 Calendar end = Calendar.getInstance();
60                 end.setTime(new Date(dateEnd));
61                 query = new ArrayList<DataBase>();
62                 List<Integer> totalTime = new ArrayList<Integer>();
63                 for (int i = 0; i < nbins; i++)
64                         totalTime.add(i, 0);
65                 List<Pair<String, String>> res = db.ReadProteinDataTable();
66                 List<Pair<Date, Long>> numres = new ArrayList<Pair<Date, Long>>();
67
68                 for (Pair<String, String> entry : res) {
69                         SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy/MM/dd");
70                         try {
71                                 Date jobstartdate = dateformatter.parse(entry.getElement0());
72                                 long date = jobstartdate.getTime();
73                                 if (dateStart <= date && date <= dateEnd) {
74                                         SimpleDateFormat datetimeformatter = new SimpleDateFormat("yyyy/MM/dd:H:m:s");
75                                         Date jobstarttime = datetimeformatter.parse(entry.getElement0());
76                                         Date jobendtime = datetimeformatter.parse(entry.getElement1());
77                                         long diff = (jobendtime.getTime() - jobstarttime.getTime()) / 1000;
78                                         Pair<Date, Long> pair = new Pair<Date, Long>(jobstartdate, Long.valueOf(diff));
79                                         numres.add(pair);
80                                 }
81                         } catch (ParseException e) {
82                                 e.printStackTrace();
83                         }
84                 }
85
86                 for (Date date = start.getTime(); !start.after(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
87                         List<Integer> timeResult = new ArrayList<Integer>();
88                         for (int i = 0; i < nbins; i++)
89                                 timeResult.add(i, 0);
90                         for (Pair<Date, Long> p : numres) {
91                                 if (date.equals(p.getElement0())) {
92                                         long lenResult = p.getElement1().longValue();
93                                         if (lenResult <= 30)
94                                                 timeResult.set(0, timeResult.get(0) + 1);
95                                         else if (lenResult > 30 && lenResult <= 60)
96                                                 timeResult.set(1, timeResult.get(1) + 1);
97                                         else if (lenResult > 60 && lenResult <= 120)
98                                                 timeResult.set(2, timeResult.get(2) + 1);
99                                         else if (lenResult > 120 && lenResult <= 600)
100                                                 timeResult.set(3, timeResult.get(3) + 1);
101                                         else {
102                                                 timeResult.set(4, timeResult.get(4) + 1);
103                                         }
104                                 }
105                         }
106                         for (int i = 0; i < nbins; i++)
107                                 totalTime.set(i, totalTime.get(i) + timeResult.get(i));
108                         DataBase db = new DataBase();
109                         db.setTimeRez(timeResult);
110                         db.setDate(DateFormat(date.getTime()));
111                         query.add(db);
112                 }
113
114                 DataBase db = new DataBase();
115                 db.setTimeTotalExec(totalTime);
116                 query.add(db);
117                 return query;
118         }
119
120         /*
121          * query: total number of jobs for the period from date1 till date2
122          */
123         public TotalJobsStatisticBean countJobs(String date1, String date2) {
124                 if (null == date1) {
125                         date1 = "1970/1/1";
126                 }
127                 if (null == date2) {
128                         date1 = "2100/1/1";
129                 }
130                 if (!isThisDateValid(date1, formatYYMMDD) || !isThisDateValid(date2, formatYYMMDD)) {
131                         System.out.println("CassandraRequester.countJobs: wrong format for date1 " + date1 + "or date2 " + date2);
132                         return null;
133                 }
134                 SetDateRange();
135                 long dateStart = DateParsing(date1, formatYYMMDD);
136                 long dateEnd = DateParsing(date2, formatYYMMDD);
137                 if (dateEnd < earlestDate || dateStart > currentDate || dateStart > dateEnd)
138                         return null;
139                 if (dateStart < earlestDate)
140                         dateStart = earlestDate;
141                 if (dateEnd > currentDate)
142                         dateStart = currentDate;
143
144                 Calendar start = Calendar.getInstance();
145                 start.setTime(new Date(dateStart));
146                 Calendar end = Calendar.getInstance();
147                 end.setTime(new Date(dateEnd));
148                 TotalJobsStatisticBean query = new TotalJobsStatisticBean();
149                 Total wholeTotal = new Total(0, 0, 0, 0, 0);
150                 for (Date date = start.getTime(); !start.after(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
151                         Total res = db.ReadDateTable(date.getTime());
152                         if (res == null)
153                                 continue;
154                         query.setDateTotal(DateFormat(date.getTime()), res);
155                         wholeTotal.setTotal(res.getTotal() + wholeTotal.getTotal());
156                         wholeTotal.setTotalOK(res.getTotalOK() + wholeTotal.getTotalOK());
157                         wholeTotal.setTotalStopped(res.getTotalStopped() + wholeTotal.getTotalStopped());
158                         wholeTotal.setTotalError(res.getTotalError() + wholeTotal.getTotalError());
159                         wholeTotal.setTotalTimeOut(res.getTotalTimeOut() + wholeTotal.getTotalTimeOut());
160                 }
161                 query.setWholeTotal(wholeTotal);
162                 return query;
163         }
164
165         /*
166          * query: jobs and sequence at date
167          */
168         public DateBean readJobByDay(String date, JobStatus status) {
169                 if (!isThisDateValid(date, formatDDMMYY)) {
170                         System.out.println("CassandraRequester.readJobByDay: Wrong date format for " + date);
171                         return null;
172                 }
173                 SetDateRange();
174                 long day = DateParsing(date, formatDDMMYY);
175                 if (day < earlestDate || day > currentDate)
176                         return null;
177                 
178                 if (status == JobStatus.OK) {
179                         return db.ReadProteinData(day, date);
180                 }
181                 return db.ReadFailedJobs(day, date, status);
182         }
183
184         /*
185          * query: protein sequence
186          */
187         public List<ProteinBean> readProteins(String protIn, String searchtype) {
188                 List<ProteinBean> result;
189                 if (searchtype.equals("whole"))
190                         result = db.ReadWholeSequence(protIn);
191                 else
192                         result = db.ReadPartOfSequence(protIn);
193                 if (result == null)
194                         return null;
195
196                 if (searchtype.equals("partial")) {
197                         for (ProteinBean entry : result) {
198                                 entry.setSubProt(CreateSubprot(entry.getSequence(), protIn));
199                         }
200                 }
201                 return result;
202         }
203
204         /*
205          * query protein sequences with number of jobs
206          */
207         public List<TotalByCounterBean> readProteinByCounter(int minimalcounter) {
208                 List<TotalByCounterBean> query = new ArrayList<TotalByCounterBean>();
209                 Map<String, Integer> map = db.ReadProteinSequenceByCounter();
210                 if (map == null)
211                         return null;
212                 for (Map.Entry<String, Integer> entry : map.entrySet()) {
213                         if (entry.getValue() > minimalcounter) {
214                                 TotalByCounterBean bean = new TotalByCounterBean();
215                                 bean.setTotaljobs(entry.getValue());
216                                 bean.setName(entry.getKey());
217                                 query.add(bean);
218                         }
219                 }
220                 return query;
221         }
222
223         /*
224          * query ip with number of jobs
225          */
226         public List<TotalByCounterBean> readIpByCounter(Integer minimalcounter) {
227                 List<TotalByCounterBean> query = new ArrayList<TotalByCounterBean>();
228                 Map<String, Integer> map = db.ReadIpByCounter();
229                 if (minimalcounter == null)
230                         minimalcounter = 0;
231                 if (map == null)
232                         return null;
233                 for (Map.Entry<String, Integer> entry : map.entrySet()) {
234                         if (entry.getValue() > minimalcounter) {
235                                 TotalByCounterBean bean = new TotalByCounterBean();
236                                 bean.setTotaljobs(entry.getValue());
237                                 bean.setName(entry.getKey());
238                                 query.add(bean);
239                         }
240                 }
241                 return query;
242         }
243
244         /*
245          * query jobs log info
246          */
247         public JobBean readJobLog(String jobid) {
248                 if (jobid == null)
249                         return null;
250                 return db.ReadJobLog(jobid);
251         }
252
253         /*
254          * query jobs by ipStructureJobLog
255          */
256         public UserBean readIp(String ip) {
257                 if (ip == null)
258                         return null;
259                 Map<String, String[]> res = db.ReadIpWithJobs(ip);
260                 if (res == null)
261                         return null;
262                 UserBean query = new UserBean(ip);
263                 query.setMainInfo(res);
264                 return query;
265         }
266
267         /*
268          * create list of parts of protein sequence;
269          */
270         private static List<String> CreateSubprot(String protein, String subprot) {
271                 List<String> sub = new ArrayList<String>();
272                 String subStr = protein;
273                 while (subStr.length() > 0 && subStr.contains(subprot)) {
274                         String first = subStr.substring(0, subStr.indexOf(subprot));
275                         if (first.length() > 0)
276                                 sub.add(first);
277                         sub.add(subprot);
278                         subStr = subStr.substring(subStr.indexOf(subprot) + subprot.length(), subStr.length());
279                 }
280                 if (subStr.length() > 0)
281                         sub.add(subStr);
282                 return sub;
283         }
284
285         /*
286          * convert String date into long date (miliseconds since the epoch start)
287          */
288         private static long DateParsing(String datInput, SimpleDateFormat formatter) {
289                 if (datInput == null) {
290                         return 0;
291                 }
292                 long dateWorkSt = 0;
293
294                 try {
295                         dateWorkSt = formatter.parse(datInput).getTime();
296                 } catch (ParseException e) {
297                         e.printStackTrace();
298                 }
299                 return dateWorkSt;
300         }
301
302         // convert long to date in string format
303         private static String DateFormat(long inDate) {
304                 SimpleDateFormat datformat = new SimpleDateFormat("dd/MM/yyyy");
305                 return datformat.format(new Date(inDate));
306         }
307
308         /*
309          * set earlest date and current dates. earlestDate is static and should be
310          * set at the 1st call currentDate should be re-calculated every time
311          */
312         private static void SetDateRange() {
313                 Calendar cal = Calendar.getInstance();
314                 currentDate = DateParsing(cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DAY_OF_MONTH),
315                                 formatYYMMDD);
316                 if (0 == earlestDate) {
317                         CassandraRequester cr = new CassandraRequester();
318                         earlestDate = cr.earliestDate();
319                 }
320         }
321
322         public boolean isThisDateValid(String dateToValidate, SimpleDateFormat sdf) {
323                 if (dateToValidate == null || dateToValidate.equals("")) {
324                         return false;
325                 }
326                 try {
327                         // if not valid, this will throw ParseException
328                         sdf.setLenient(false);
329                         Date date = sdf.parse(dateToValidate);
330                 } catch (ParseException e) {
331                         e.printStackTrace();
332                         return false;
333                 }
334                 return true;
335         }
336
337         /*
338          * find the earliest date in the database
339          */
340         public long earliestDate() {
341                 earlestDate = CassandraNativeConnector.getEarliestDateInDB();
342                 return earlestDate;
343         }
344
345 }