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