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