Fi bug for wrong job selection
[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.beans.DateBean;
13 import compbio.beans.JobBean;
14 import compbio.beans.ProteinBean;
15 import compbio.beans.Total;
16 import compbio.beans.TotalByCounterBean;
17 import compbio.beans.TotalJobsStatisticBean;
18 import compbio.beans.UserBean;
19 import compbio.cassandra.CassandraNativeConnector;
20 import compbio.cassandra.CassandraReaderOld;
21 import compbio.cassandra.DataBase;
22 import compbio.engine.JobStatus;
23 import compbio.engine.Pair;
24
25 public class CassandraRequester {
26         private CassandraReaderOld db = new CassandraReaderOld();
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                 /*
116                  * ???? Very strange code... DataBase db = new DataBase();
117                  * db.setTimeTotalExec(totalTime); query.add(db);
118                  */
119                 return query;
120         }
121
122         /*
123          * query: total number of jobs for the period from date1 till date2
124          */
125         public TotalJobsStatisticBean countJobs(String date1, String date2) {
126                 /*
127                  * if (null == date1) { date1 = "1970/1/1"; } if (null == date2) { date1
128                  * = "2100/1/1"; } if (!isThisDateValid(date1, formatYYMMDD) ||
129                  * !isThisDateValid(date2, formatYYMMDD)) { System.out.println(
130                  * "CassandraRequester.countJobs: wrong format for date1 " + date1 +
131                  * "or date2 " + date2); return null; }
132                  */
133                 SetDateRange();
134                 long dateStart = DateParsing(date1, formatYYMMDD);
135                 long dateEnd = DateParsing(date2, formatYYMMDD);
136                 /*
137                  * if (dateEnd < earlestDate || dateStart > currentDate || dateStart >
138                  * dateEnd) return null; if (dateStart < earlestDate) dateStart =
139                  * earlestDate; if (dateEnd > currentDate) dateStart = currentDate;
140                  */
141                 Calendar start = Calendar.getInstance();
142                 start.setTime(new Date(dateStart));
143                 Calendar end = Calendar.getInstance();
144                 end.setTime(new Date(dateEnd));
145                 TotalJobsStatisticBean query = new TotalJobsStatisticBean();
146                 Total wholeTotal = new Total(0, 0, 0, 0, 0);
147                 for (Date date = start.getTime(); !start.after(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
148                         Total res = db.ReadDateTable(date.getTime());
149                         if (res == null)
150                                 continue;
151                         query.setDateTotal(DateFormat(date.getTime()), res);
152                         wholeTotal.setTotal(res.getTotal() + wholeTotal.getTotal());
153                         wholeTotal.setTotalOK(res.getTotalOK() + wholeTotal.getTotalOK());
154                         wholeTotal.setTotalStopped(res.getTotalStopped() + wholeTotal.getTotalStopped());
155                         wholeTotal.setTotalError(res.getTotalError() + wholeTotal.getTotalError());
156                         wholeTotal.setTotalTimeOut(res.getTotalTimeOut() + wholeTotal.getTotalTimeOut());
157                 }
158                 query.setWholeTotal(wholeTotal);
159                 return query;
160         }
161
162         /*
163          * query: jobs and sequence at date
164          */
165         public DateBean readJobByDay(String date, JobStatus status) {
166                 if (!isThisDateValid(date, formatDDMMYY)) {
167                         System.out.println("CassandraRequester.readJobByDay: Wrong date format for " + date);
168                         return null;
169                 }
170                 SetDateRange();
171                 long day = DateParsing(date, formatDDMMYY);
172                 if (day < earlestDate || day > currentDate)
173                         return null;
174
175                 if (status == JobStatus.OK) {
176                         return db.ReadProteinData(day, date);
177                 }
178                 return db.ReadFailedJobs(day, date, status);
179         }
180
181         /*
182          * query: protein sequence
183          */
184         public List<ProteinBean> readProteins(String protIn, String searchtype) {
185                 List<ProteinBean> result;
186                 if (searchtype.equals("whole"))
187                         result = db.ReadWholeSequence(protIn);
188                 else
189                         result = db.ReadPartOfSequence(protIn);
190                 if (result == null)
191                         return null;
192
193                 if (searchtype.equals("partial")) {
194                         for (ProteinBean entry : result) {
195                                 entry.setSubProt(CreateSubprot(entry.getSequence(), protIn));
196                         }
197                 }
198                 return result;
199         }
200
201         /*
202          * query: protein feature
203          */
204
205         public Map<String, String> readProteinsPrediction(String feature, int percent) {
206                 Map<String, String> results = db.ReadProtein();
207                 if (results == null)
208                         return null;
209                 Map<String, String> query = new HashMap<String, String>();
210                 for (Map.Entry<String, String> entry : results.entrySet()) {
211                         String prediction = entry.getValue();
212                         String protein = entry.getKey();
213                         if (prediction.replaceAll("[^" + feature + "]", "").length() > prediction.length() * percent / 100 && !protein.equals("")) {
214                                 query.put(protein, prediction);
215                         }
216                 }
217                 return query;
218         }
219
220         /*
221          * query protein sequences with number of jobs
222          */
223         public List<TotalByCounterBean> readProteinByCounter(int minimalcounter) {
224                 List<TotalByCounterBean> query = new ArrayList<TotalByCounterBean>();
225                 Map<String, Integer> map = db.ReadProteinSequenceByCounter();
226                 if (map == null)
227                         return null;
228                 for (Map.Entry<String, Integer> entry : map.entrySet()) {
229                         if (entry.getValue() > minimalcounter) {
230                                 TotalByCounterBean bean = new TotalByCounterBean();
231                                 bean.setTotaljobs(entry.getValue());
232                                 bean.setName(entry.getKey());
233                                 query.add(bean);
234                         }
235                 }
236                 return query;
237         }
238
239         /*
240          * query ip with number of jobs
241          */
242         public List<TotalByCounterBean> readIpByCounter(Integer minimalcounter) {
243                 List<TotalByCounterBean> query = new ArrayList<TotalByCounterBean>();
244                 Map<String, Integer> map = db.ReadIpByCounter();
245                 if (minimalcounter == null)
246                         minimalcounter = 0;
247                 if (map == null)
248                         return null;
249                 for (Map.Entry<String, Integer> entry : map.entrySet()) {
250                         if (entry.getValue() > minimalcounter) {
251                                 TotalByCounterBean bean = new TotalByCounterBean();
252                                 bean.setTotaljobs(entry.getValue());
253                                 bean.setName(entry.getKey());
254                                 query.add(bean);
255                         }
256                 }
257                 return query;
258         }
259
260         /*
261          * query jobs log info
262          */
263         public JobBean readJobLog(String jobid) {
264                 if (jobid == null)
265                         return null;
266                 return db.ReadJobLog(jobid);
267         }
268
269         /*
270          * query jobs by ipStructureJobLog
271          */
272         public UserBean readIp(String ip) {
273                 if (ip == null)
274                         return null;
275                 Map<String, String[]> res = db.ReadIpWithJobs(ip);
276                 if (res == null)
277                         return null;
278                 UserBean query = new UserBean(ip);
279                 query.setMainInfo(res);
280                 return query;
281         }
282
283         /*
284          * create list of parts of protein sequence;
285          */
286         private static List<String> CreateSubprot(String protein, String subprot) {
287                 List<String> sub = new ArrayList<String>();
288                 String subStr = protein;
289                 while (subStr.length() > 0 && subStr.contains(subprot)) {
290                         String first = subStr.substring(0, subStr.indexOf(subprot));
291                         if (first.length() > 0)
292                                 sub.add(first);
293                         sub.add(subprot);
294                         subStr = subStr.substring(subStr.indexOf(subprot) + subprot.length(), subStr.length());
295                 }
296                 if (subStr.length() > 0)
297                         sub.add(subStr);
298                 return sub;
299         }
300
301         /*
302          * convert String date into long date (miliseconds since the epoch start)
303          */
304         private static long DateParsing(String datInput, SimpleDateFormat formatter) {
305                 if (datInput == null) {
306                         return 0;
307                 }
308                 long dateWorkSt = 0;
309
310                 try {
311                         dateWorkSt = formatter.parse(datInput).getTime();
312                 } catch (ParseException e) {
313                         e.printStackTrace();
314                 }
315                 return dateWorkSt;
316         }
317
318         // convert long to date in string format
319         private static String DateFormat(long inDate) {
320                 SimpleDateFormat datformat = new SimpleDateFormat("dd/MM/yyyy");
321                 return datformat.format(new Date(inDate));
322         }
323
324         /*
325          * set earlest date and current dates. earlestDate is static and should be
326          * set at the 1st call currentDate should be re-calculated every time
327          */
328         private static void SetDateRange() {
329                 Calendar cal = Calendar.getInstance();
330                 currentDate = DateParsing(cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DAY_OF_MONTH),
331                                 formatYYMMDD);
332                 if (0 == earlestDate) {
333                         CassandraRequester cr = new CassandraRequester();
334                         earlestDate = cr.earliestDate();
335                 }
336         }
337
338         public boolean isThisDateValid(String dateToValidate, SimpleDateFormat sdf) {
339                 if (dateToValidate == null || dateToValidate.equals("")) {
340                         return false;
341                 }
342                 try {
343                         // if not valid, this will throw ParseException
344                         sdf.setLenient(false);
345                         Date date = sdf.parse(dateToValidate);
346                 } catch (ParseException e) {
347                         e.printStackTrace();
348                         return false;
349                 }
350                 return true;
351         }
352
353         /*
354          * find the earliest date in the database
355          */
356         public long earliestDate() {
357                 earlestDate = CassandraNativeConnector.getEarliestDateInDB();
358                 return earlestDate;
359         }
360
361         /**
362          * prepares an example of either job id or IP for the DB
363          * 
364          * @param exampletype
365          *            defines which example you need (an existing job from the DB -
366          *            jobid, an IP - "ip")
367          * @return a string representation of the requested example, if the example
368          *         type is not known empty string is returned
369          */
370         public String getExample(String exampletype) {
371                 if (exampletype.equals("jobid")) {
372                         return "jp_NzBOJKo";
373                 } else if (exampletype.equals("ip")) {
374                         return "127.0.0.1";
375                 }
376                 return "";
377         }
378
379 }