Changeset 500


Ignore:
Timestamp:
01/30/11 23:04:07 (2 years ago)
Author:
philsmart
Message:

added SQL Filter capabilities

Location:
raptor-mua/trunk/src/main
Files:
1 added
4 edited

Legend:

Unmodified
Added
Removed
  • raptor-mua/trunk/src/main/java/uk/ac/cardiff/raptormua/engine/statistics/AuthenticationStatistic.java

    r495 r500  
    3939/** 
    4040 * @author philsmart 
    41  * 
    42  * TODO need to include where filter parameters for most these methods 
    43  * 
     41 *  
     42 *         TODO need to include where filter parameters for most these methods 
     43 *  
    4444 */ 
    4545public class AuthenticationStatistic extends Statistic { 
    46     static Logger log = LoggerFactory.getLogger(AuthenticationStatistic.class); 
    47  
    48     /** 
    49      * <p> 
    50      * returns false if semantic error with the entries, throws an exception on code failure 
    51      * </p> 
    52      * 
    53      * @param timeInterval 
    54      *            - assumes a String representing minutes 
    55      * @return 
    56      * @throws StatisticalUnitException 
    57      */ 
    58     public Boolean countEntryPerInterval(String timeInterval) throws StatisticalUnitException { 
    59  
    60         log.debug("Performing countEntryPerInterval Statistical Operation"); 
    61         int timeIntervalInt = Integer.parseInt(timeInterval); 
    62         // convert minutes to ms for the procedure 
    63         timeIntervalInt = timeIntervalInt * 60 * 1000; 
    64         log.debug("Params for method:  {}, {}",statisticParameters.getMethodName(), statisticParameters.getUnitName()); 
    65  
    66         /* divide the temporal extent into evenly sized buckets */ 
    67         DateTime start = startingTime(); 
    68         DateTime end = endingTime(); 
    69         log.debug("countEntryPerInterval between [start:{}] [end:{}]",start,end); 
    70         long difference = end.getMillis() - start.getMillis(); 
    71         log.debug("There is " + difference + "ms difference between start and end entries"); 
    72         int numberOfBuckets = (int) (difference / timeIntervalInt); 
    73         long reminder = difference % timeIntervalInt; 
    74         log.debug("There are " + numberOfBuckets + " buckets, with reminder " + reminder + "ms"); 
    75  
    76         /* now create that many buckets of length timeIntervalInt */ 
    77         Bucket[] buckets = null; 
    78         if (reminder > 0) 
    79             buckets = new Bucket[numberOfBuckets + 1]; // add 1 for the reminder 
    80         else 
    81             buckets = new Bucket[numberOfBuckets]; 
    82  
    83         buckets[0] = new Bucket(); 
    84         buckets[0].setStart(start); 
    85         buckets[0].setEnd(new DateTime(start.getMillis() + timeIntervalInt)); 
    86         DateTime endOfEvenBuckets = null; 
    87         for (int i = 1; i < numberOfBuckets; i++) { 
    88             Bucket buck = new Bucket(); 
    89             buck.setStart(buckets[i - 1].getEnd()); 
    90             buck.setEnd(new DateTime(buckets[i - 1].getEnd().getMillis() + timeIntervalInt)); 
    91             buckets[i] = buck; 
    92             endOfEvenBuckets = buck.getEnd(); 
    93         } 
    94  
    95         /* 
    96          * there may only be a reminder if the time frame specified is not big enough to fit the interval specified, in this case the endOfEvenBuckets has not 
    97          * been set, and it needs setting to the current starttime. 
     46        static Logger log = LoggerFactory.getLogger(AuthenticationStatistic.class); 
     47 
     48        /** 
     49         * <p> 
     50         * returns false if semantic error with the entries, throws an exception on 
     51         * code failure 
     52         * </p> 
     53         *  
     54         * @param timeInterval 
     55         *            - assumes a String representing minutes 
     56         * @param sqlWhere if a SQL filter has been attached to the statistical unit, it is inputed to the method 
     57         *                                      if there is not SQL filter, it comes through as an empty string (not null) 
     58         * @return 
     59         * @throws StatisticalUnitException 
    9860         */ 
    99         boolean hasOnlyReminder = false; 
    100         if (endOfEvenBuckets == null) { 
    101             hasOnlyReminder = true; 
    102             endOfEvenBuckets = start; 
    103         } 
    104  
    105         if (reminder > 0) { 
    106             /* now do something with the reminder, create a bucket from the last entry, to the maximum temporal extent of all entries */ 
    107             Bucket reminderBucket = new Bucket(); 
    108             reminderBucket.setStart(endOfEvenBuckets); 
    109             if (!hasOnlyReminder) 
    110                 reminderBucket.setEnd(end); 
    111             else 
    112                 reminderBucket.setEnd(new DateTime(start.getMillis() + end.getMillis())); 
    113             buckets[buckets.length - 1] = reminderBucket; 
    114         } 
    115  
    116         long testCount = 0; 
    117         for (Bucket bucket : buckets) { 
    118             // SQL between is >= start && <= end. We want, >= start && < end, so must exclude equals end 
    119             Integer count = (Integer) this.getEntryHandler().queryUnique("select count(*) from Entry where (eventTime between '" + bucket.getStart() + "' and '" + bucket.getEnd() + "') and (eventTime !='" + bucket.getEnd() + "')");// new 
    120                                                                                                                                                                                                                                        // Object[]{start,end}); 
    121             bucket.setValue(count); 
    122             testCount += bucket.getValue(); 
    123         } 
    124  
    125         /* 
    126          * test count should equal the number of entries unless there is a reminder, or the specified start time and endtime does not completely contain the 
    127          * entries. 
     61        public Boolean countEntryPerInterval(String timeInterval, String sqlWhere) throws StatisticalUnitException { 
     62                log.debug("Performing countEntryPerInterval Statistical Operation"); 
     63                int timeIntervalInt = Integer.parseInt(timeInterval); 
     64                // convert minutes to ms for the procedure 
     65                timeIntervalInt = timeIntervalInt * 60 * 1000; 
     66                log.debug("Params for method:  {}, {}. SQL Filter {}", new Object[]{statisticParameters.getMethodName(), statisticParameters.getUnitName(),sqlWhere}); 
     67 
     68                /* divide the temporal extent into evenly sized buckets */ 
     69                DateTime start = startingTime(); 
     70                DateTime end = endingTime(); 
     71                log.debug("countEntryPerInterval between [start:{}] [end:{}]", start, end); 
     72                long difference = end.getMillis() - start.getMillis(); 
     73                log.debug("There is " + difference + "ms difference between start and end entries"); 
     74                int numberOfBuckets = (int) (difference / timeIntervalInt); 
     75                long reminder = difference % timeIntervalInt; 
     76                log.debug("There are " + numberOfBuckets + " buckets, with reminder " + reminder + "ms"); 
     77 
     78                /* now create that many buckets of length timeIntervalInt */ 
     79                Bucket[] buckets = null; 
     80                if (reminder > 0) 
     81                        buckets = new Bucket[numberOfBuckets + 1]; // add 1 for the reminder 
     82                else 
     83                        buckets = new Bucket[numberOfBuckets]; 
     84 
     85                buckets[0] = new Bucket(); 
     86                buckets[0].setStart(start); 
     87                buckets[0].setEnd(new DateTime(start.getMillis() + timeIntervalInt)); 
     88                DateTime endOfEvenBuckets = null; 
     89                for (int i = 1; i < numberOfBuckets; i++) { 
     90                        Bucket buck = new Bucket(); 
     91                        buck.setStart(buckets[i - 1].getEnd()); 
     92                        buck.setEnd(new DateTime(buckets[i - 1].getEnd().getMillis() + timeIntervalInt)); 
     93                        buckets[i] = buck; 
     94                        endOfEvenBuckets = buck.getEnd(); 
     95                } 
     96 
     97                /* 
     98                 * there may only be a reminder if the time frame specified is not big 
     99                 * enough to fit the interval specified, in this case the 
     100                 * endOfEvenBuckets has not been set, and it needs setting to the 
     101                 * current starttime. 
     102                 */ 
     103                boolean hasOnlyReminder = false; 
     104                if (endOfEvenBuckets == null) { 
     105                        hasOnlyReminder = true; 
     106                        endOfEvenBuckets = start; 
     107                } 
     108 
     109                if (reminder > 0) { 
     110                        /* 
     111                         * now do something with the reminder, create a bucket from the last 
     112                         * entry, to the maximum temporal extent of all entries 
     113                         */ 
     114                        Bucket reminderBucket = new Bucket(); 
     115                        reminderBucket.setStart(endOfEvenBuckets); 
     116                        if (!hasOnlyReminder) 
     117                                reminderBucket.setEnd(end); 
     118                        else 
     119                                reminderBucket.setEnd(new DateTime(start.getMillis() + end.getMillis())); 
     120                        buckets[buckets.length - 1] = reminderBucket; 
     121                } 
     122 
     123                long testCount = 0; 
     124                for (Bucket bucket : buckets) { 
     125                        // SQL between is >= start && <= end. We want, >= start && < end, so 
     126                        // must exclude equals end 
     127                        String query=null; 
     128                        if (sqlWhere.equals("")) 
     129                                query = "select count(*) from Entry where (eventTime between '" + bucket.getStart() + "' and '" 
     130                                                        + bucket.getEnd() + "') and (eventTime !='" + bucket.getEnd() + "')"; 
     131                        else  
     132                                query = "select count(*) from Entry where (eventTime between '" + bucket.getStart() + "' and '" 
     133                                + bucket.getEnd() + "') and (eventTime !='" + bucket.getEnd() + "') and "+sqlWhere; 
     134                        Integer count = (Integer) this.getEntryHandler().queryUnique(query);// new 
     135                        // Object[]{start,end}); 
     136                        bucket.setValue(count); 
     137                        testCount += bucket.getValue(); 
     138                } 
     139 
     140                /* 
     141                 * test count should equal the number of entries unless there is a 
     142                 * reminder, or the specified start time and endtime does not completely 
     143                 * contain the entries. 
     144                 */ 
     145                log.debug("Entries: " + this.getEntryHandler().getNumberOfEntries() + ", total in buckets: " + testCount); 
     146 
     147                if (this.getEntryHandler().getNumberOfEntries() != testCount) 
     148                        log.error("Ah! Curse your sudden but inevitable betrayal!, Potential statistical error in countEntryPerInterval, total frequency does not match total entries"); 
     149 
     150                if (statisticParameters.getSeriesLabel() == null) 
     151                        statisticParameters.setSeriesLabelFormatted("Number of Events per " + timeInterval + " minutes"); 
     152                else { 
     153                        statisticParameters.setSeriesLabelFormatted(statisticParameters.getSeriesLabel() + " (every " 
     154                                        + timeInterval + " minutes, where "+sqlWhere+")"); 
     155                } 
     156 
     157                observations = buckets; 
     158 
     159                // finished successfully, no exception thrown 
     160                return true; 
     161 
     162        } 
     163 
     164        public Boolean countEntry(String numberOfIntervalsString, String sqlWhere) throws StatisticalUnitException { 
     165 
     166                int numberOfIntervals = Integer.parseInt(numberOfIntervalsString); 
     167                log.debug("Performing countEntry Statistical Operation"); 
     168                log.debug("Params for method:  " + statisticParameters.getMethodName() + ", " 
     169                                + statisticParameters.getUnitName()); 
     170 
     171                /* divide the temporal extent into evenly sized buckets */ 
     172                DateTime start = startingTime(); 
     173                DateTime end = endingTime(); 
     174                log.debug("countEntry between [start:{}] [end:{}]", start, end); 
     175                long difference = end.getMillis() - start.getMillis(); 
     176                log.debug("There is " + difference + "ms difference between start and end entries"); 
     177                long timeIntervalsInMs = (long) (difference / numberOfIntervals); 
     178                long reminder = difference % numberOfIntervals; 
     179                log.debug("There are " + numberOfIntervals + " buckets, with reminder " + reminder + "ms"); 
     180 
     181                /* now create that many buckets of length timeIntervalInt */ 
     182                Bucket[] buckets = null; 
     183                if (reminder > 0) 
     184                        buckets = new Bucket[numberOfIntervals + 1]; // add 1 for the 
     185                                                                                                                        // reminder 
     186                else 
     187                        buckets = new Bucket[numberOfIntervals]; 
     188 
     189                buckets[0] = new Bucket(); 
     190                buckets[0].setStart(start); 
     191                buckets[0].setEnd(new DateTime(start.getMillis() + timeIntervalsInMs)); 
     192                DateTime endOfEvenBuckets = null; 
     193                for (int i = 1; i < numberOfIntervals; i++) { 
     194                        Bucket buck = new Bucket(); 
     195                        buck.setStart(buckets[i - 1].getEnd()); 
     196                        buck.setEnd(new DateTime(buckets[i - 1].getEnd().getMillis() + timeIntervalsInMs)); 
     197                        buckets[i] = buck; 
     198                        endOfEvenBuckets = buck.getEnd(); 
     199                } 
     200 
     201                /* 
     202                 * there may only be a reminder if the time frame specified is not big 
     203                 * enough to fit the interval specified, in this case the 
     204                 * endOfEvenBuckets has not been set, and it needs setting to the 
     205                 * current starttime. 
     206                 */ 
     207                boolean hasOnlyReminder = false; 
     208                if (endOfEvenBuckets == null) { 
     209                        hasOnlyReminder = true; 
     210                        endOfEvenBuckets = start; 
     211                } 
     212 
     213                if (reminder > 0) { 
     214                        /* 
     215                         * now do something with the reminder, create a bucket from the last 
     216                         * entry, to the maximum temporal extent of all entries 
     217                         */ 
     218                        Bucket reminderBucket = new Bucket(); 
     219                        reminderBucket.setStart(endOfEvenBuckets); 
     220                        if (!hasOnlyReminder) 
     221                                reminderBucket.setEnd(end); 
     222                        else 
     223                                reminderBucket.setEnd(new DateTime(start.getMillis() + end.getMillis())); 
     224                        buckets[buckets.length - 1] = reminderBucket; 
     225                } 
     226 
     227                long testCount = 0; 
     228                for (Bucket bucket : buckets) { 
     229                        // SQL between is >= start && <= end. We want, >= start && < end, so 
     230                        // must exclude equals end 
     231                        Integer count = (Integer) this.getEntryHandler().queryUnique( 
     232                                        "select count(*) from Entry where (eventTime between '" + bucket.getStart() + "' and '" 
     233                                                        + bucket.getEnd() + "') and (eventTime !='" + bucket.getEnd() + "')");// new 
     234                        // Object[]{start,end}); 
     235                        bucket.setValue(count); 
     236                        testCount += bucket.getValue(); 
     237                } 
     238 
     239                /* 
     240                 * test count should equal the number of entries unless there is a 
     241                 * reminder, or the specified start time and endtime does not completely 
     242                 * contain the entries. 
     243                 */ 
     244                log.debug("Entries: " + this.getEntryHandler().getNumberOfEntries() + ", total in buckets: " + testCount); 
     245 
     246                double timeIntervalInHours = ((((timeIntervalsInMs / 1000) / 60) / 60)); 
     247                double timeIntervalInDays = ((((timeIntervalsInMs / 1000) / 60) / 60) / 24); 
     248 
     249                if (this.getEntryHandler().getNumberOfEntries() != testCount) 
     250                        log.error("Ah! Curse your sudden but inevitable betrayal!, Potential statistical error in countEntryPerInterval, total frequency does not match total entries"); 
     251 
     252                if (statisticParameters.getSeriesLabel() == null) 
     253                        statisticParameters.setSeriesLabelFormatted("Number of Events per " + timeIntervalInDays + " days"); 
     254                else { 
     255                        statisticParameters.setSeriesLabelFormatted(statisticParameters.getSeriesLabel() + " (every " 
     256                                        + timeIntervalInDays + " days)"); 
     257                } 
     258 
     259                observations = buckets; 
     260 
     261                return true; 
     262 
     263        } 
     264 
     265        /** 
     266         * Perform the groupByField statistic. This statistic counts the frequency 
     267         * that each distinct value of the given <code>groupByField</code> occurs in 
     268         * the entry set. It is the responsibility of this method to throw a 
     269         * <code>StatisticalUnitException</code> if the code logic fails, or return 
     270         * false if the statistic functioned correctly, but there are no valid 
     271         * observations, or true if the statistic succeeds and there are valid 
     272         * observations. 
     273         *  
     274         *  
     275         * @param groupByField 
     276         * @return 
     277         * @throws StatisticalUnitException 
    128278         */ 
    129         log.debug("Entries: " + this.getEntryHandler().getNumberOfEntries() + ", total in buckets: " + testCount); 
    130  
    131         if (this.getEntryHandler().getNumberOfEntries() != testCount) 
    132             log.error("Ah! Curse your sudden but inevitable betrayal!, Potential statistical error in countEntryPerInterval, total frequency does not match total entries"); 
    133  
    134         if (statisticParameters.getSeriesLabel() == null) 
    135             statisticParameters.setSeriesLabelFormatted("Number of Events per " + timeInterval+" minutes"); 
    136         else{ 
    137             statisticParameters.setSeriesLabelFormatted(statisticParameters.getSeriesLabel()+" (every "+timeInterval+" minutes)"); 
    138         } 
    139  
    140         observations = buckets; 
    141  
    142         // finished successfully, no exception thrown 
    143         return true; 
    144  
    145     } 
    146  
    147     public Boolean countEntry(String numberOfIntervalsString) throws StatisticalUnitException { 
    148  
    149         int numberOfIntervals = Integer.parseInt(numberOfIntervalsString); 
    150         log.debug("Performing countEntry Statistical Operation"); 
    151         log.debug("Params for method:  " + statisticParameters.getMethodName() + ", " + statisticParameters.getUnitName()); 
    152  
    153         /* divide the temporal extent into evenly sized buckets */ 
    154         DateTime start = startingTime(); 
    155         DateTime end = endingTime(); 
    156         log.debug("countEntry between [start:{}] [end:{}]",start,end); 
    157         long difference = end.getMillis() - start.getMillis(); 
    158         log.debug("There is " + difference + "ms difference between start and end entries"); 
    159         long timeIntervalsInMs = (long) (difference / numberOfIntervals); 
    160         long reminder = difference % numberOfIntervals; 
    161         log.debug("There are " + numberOfIntervals + " buckets, with reminder " + reminder + "ms"); 
    162  
    163         /* now create that many buckets of length timeIntervalInt */ 
    164         Bucket[] buckets = null; 
    165         if (reminder > 0) 
    166             buckets = new Bucket[numberOfIntervals + 1]; // add 1 for the reminder 
    167         else 
    168             buckets = new Bucket[numberOfIntervals]; 
    169  
    170         buckets[0] = new Bucket(); 
    171         buckets[0].setStart(start); 
    172         buckets[0].setEnd(new DateTime(start.getMillis() + timeIntervalsInMs)); 
    173         DateTime endOfEvenBuckets = null; 
    174         for (int i = 1; i < numberOfIntervals; i++) { 
    175             Bucket buck = new Bucket(); 
    176             buck.setStart(buckets[i - 1].getEnd()); 
    177             buck.setEnd(new DateTime(buckets[i - 1].getEnd().getMillis() + timeIntervalsInMs)); 
    178             buckets[i] = buck; 
    179             endOfEvenBuckets = buck.getEnd(); 
    180         } 
    181  
    182         /* 
    183          * there may only be a reminder if the time frame specified is not big enough to fit the interval specified, in this case the endOfEvenBuckets has not 
    184          * been set, and it needs setting to the current starttime. 
     279        public Boolean groupByFrequency(String groupByField, String sqlWhere) throws StatisticalUnitException { 
     280                log.debug("Performing groupByFrequency Statistical Operation"); 
     281                log.debug("Params for method:  {},{}", statisticParameters.getMethodName(), statisticParameters.getUnitName()); 
     282                log.debug("Grouping field: {}", groupByField); 
     283 
     284                DateTime start = startingTime(); 
     285                DateTime end = endingTime(); 
     286                log.debug("groupByFrequency between [start:{}] [end:{}]", start, end); 
     287                String tableName = ReflectionHelper.findEntrySubclassForMethod(groupByField); 
     288                log.debug("Select {}, tableName {}", groupByField, tableName); 
     289                List results = getEntryHandler().query( 
     290                                "select " + groupByField + ",count(*) from " + tableName + " where (eventTime between '" + start 
     291                                                + "' and '" + end + "') group by (" + groupByField + ")"); 
     292 
     293                ArrayList<Group> groups = new ArrayList(); 
     294                int testCount = 0; 
     295                for (Object result : results) { 
     296                        Object[] resultAsArray = (Object[]) result; 
     297                        Group group = new Group(); 
     298                        group.setValue((Integer) resultAsArray[1]); 
     299                        group.setGroupName((String) resultAsArray[0]); 
     300                        groups.add(group); 
     301                        testCount += group.getValue(); 
     302                } 
     303 
     304                /* 
     305                 * test count should equal the number of entries unless there is a 
     306                 * reminder as this has not been catered for yet. 
     307                 */ 
     308                log.debug("Entries: {}, total in buckets:{} ", this.getEntryHandler().getNumberOfEntries(), testCount); 
     309 
     310                // add the series label or if none specified, add a default 
     311                if (statisticParameters.getSeriesLabel() == null) 
     312                        statisticParameters.setSeriesLabelFormatted("Number of Events Grouped By " + groupByField); 
     313                else { 
     314                        statisticParameters.setSeriesLabelFormatted(statisticParameters.getSeriesLabel()); 
     315                } 
     316 
     317                observations = groups.toArray(new Group[0]); 
     318 
     319                if (observations.length == 0) 
     320                        return false; 
     321                // finished successfully, no exception thrown 
     322                return true; 
     323 
     324        } 
     325 
     326        /** 
     327         * Perform the groupByField statistic. This statistic returns a list of 
     328         * distinct values of the given <code>groupByField</code> field. In contrast 
     329         * to the <code>groupByFrequency</code> method, it does not count the 
     330         * occurrence that each distinct value occurs. It is the responsibility of 
     331         * this method to throw a <code>StatisticalUnitException</code> if the code 
     332         * logic fails, or return false if the statistic functioned correctly, but 
     333         * there are no valid observations, or true if the statistic succeeds and 
     334         * there are valid observations. 
     335         *  
     336         * @param groupByField 
     337         * @return 
     338         * @throws StatisticalUnitException 
    185339         */ 
    186         boolean hasOnlyReminder = false; 
    187         if (endOfEvenBuckets == null) { 
    188             hasOnlyReminder = true; 
    189             endOfEvenBuckets = start; 
    190         } 
    191  
    192         if (reminder > 0) { 
    193             /* now do something with the reminder, create a bucket from the last entry, to the maximum temporal extent of all entries */ 
    194             Bucket reminderBucket = new Bucket(); 
    195             reminderBucket.setStart(endOfEvenBuckets); 
    196             if (!hasOnlyReminder) 
    197                 reminderBucket.setEnd(end); 
    198             else 
    199                 reminderBucket.setEnd(new DateTime(start.getMillis() + end.getMillis())); 
    200             buckets[buckets.length - 1] = reminderBucket; 
    201         } 
    202  
    203         long testCount = 0; 
    204         for (Bucket bucket : buckets) { 
    205             // SQL between is >= start && <= end. We want, >= start && < end, so must exclude equals end 
    206             Integer count = (Integer) this.getEntryHandler().queryUnique("select count(*) from Entry where (eventTime between '" + bucket.getStart() + "' and '" + bucket.getEnd() + "') and (eventTime !='" + bucket.getEnd() + "')");// new 
    207                                                                                                                                                                                                                                        // Object[]{start,end}); 
    208             bucket.setValue(count); 
    209             testCount += bucket.getValue(); 
    210         } 
    211  
    212         /* 
    213          * test count should equal the number of entries unless there is a reminder, or the specified start time and endtime does not completely contain the 
    214          * entries. 
     340        public Boolean groupBy(String groupByField, String sqlWhere) throws StatisticalUnitException { 
     341                log.debug("Performing groupByFrequency Statistical Operation"); 
     342                log.debug("Params for method:  {},{}", statisticParameters.getMethodName(), statisticParameters.getUnitName()); 
     343                log.debug("Grouping field: {}", groupByField); 
     344 
     345                DateTime start = startingTime(); 
     346                DateTime end = endingTime(); 
     347                log.debug("groupBy between [start:{}] [end:{}]", start, end); 
     348                String tableName = ReflectionHelper.findEntrySubclassForMethod(groupByField); 
     349                log.debug("Select {}, tableName {}", groupByField, tableName); 
     350                List results = getEntryHandler().query( 
     351                                "select " + groupByField + " from " + tableName + " where (eventTime between '" + start + "' and '" 
     352                                                + end + "') group by (" + groupByField + ")"); 
     353 
     354                ArrayList<Group> groups = new ArrayList(); 
     355                for (Object result : results) { 
     356                        Object resultAsArray = (Object) result; 
     357                        Group group = new Group(); 
     358                        group.setValue(0); 
     359                        group.setGroupName((String) resultAsArray); 
     360                        groups.add(group); 
     361 
     362                } 
     363 
     364                // add the series label or if none specified, add a default 
     365                if (statisticParameters.getSeriesLabel() == null) 
     366                        statisticParameters.setSeriesLabel("Distinct Values " + groupByField); 
     367 
     368                observations = groups.toArray(new Group[0]); 
     369 
     370                if (observations.length == 0) 
     371                        return false; 
     372                // finished successfully, no exception thrown 
     373                return true; 
     374 
     375        } 
     376 
     377        private DateTime startingTime() { 
     378                if (statisticParameters.getStartTimeAsDate() != null) 
     379                        return statisticParameters.getStartTimeAsDate(); 
     380                DateTime start = (DateTime) this.getEntryHandler().queryUnique("select min(eventTime) from Entry"); 
     381                return start; 
     382        } 
     383 
     384        private DateTime endingTime() { 
     385                if (statisticParameters.getEndTimeAsDate() != null) 
     386                        return statisticParameters.getEndTimeAsDate(); 
     387                DateTime end = (DateTime) this.getEntryHandler().queryUnique("select max(eventTime) from Entry"); 
     388                return end; 
     389        } 
     390 
     391        /** 
     392         * <p> 
     393         * </p> 
     394         *  
     395         * @param date 
     396         * @param isEndTime 
     397         *            - if is endTime and only ddMMyyyy is given, then the endTime 
     398         *            should be 23.59 as opposed to 00.00 as this is the end of the 
     399         *            day 
     400         * @return 
    215401         */ 
    216         log.debug("Entries: " + this.getEntryHandler().getNumberOfEntries() + ", total in buckets: " + testCount); 
    217  
    218         double timeIntervalInHours = ((((timeIntervalsInMs/1000)/60)/60)); 
    219         double timeIntervalInDays = ((((timeIntervalsInMs/1000)/60)/60)/24); 
    220  
    221         if (this.getEntryHandler().getNumberOfEntries() != testCount) 
    222             log.error("Ah! Curse your sudden but inevitable betrayal!, Potential statistical error in countEntryPerInterval, total frequency does not match total entries"); 
    223  
    224         if (statisticParameters.getSeriesLabel() == null) 
    225             statisticParameters.setSeriesLabelFormatted("Number of Events per " + timeIntervalInDays+" days"); 
    226         else{ 
    227             statisticParameters.setSeriesLabelFormatted(statisticParameters.getSeriesLabel()+" (every "+timeIntervalInDays+" days)"); 
    228         } 
    229  
    230         observations = buckets; 
    231  
    232         return true; 
    233  
    234     } 
    235  
    236     /** 
    237      * Perform the groupByField statistic. This statistic counts the frequency that each distinct value of the given <code>groupByField</code> occurs in the 
    238      * entry set. It is the responsibility of this method to throw a <code>StatisticalUnitException</code> if the code logic fails, or return false if the 
    239      * statistic functioned correctly, but there are no valid observations, or true if the statistic succeeds and there are valid observations. 
    240      * 
    241      * 
    242      * @param groupByField 
    243      * @return 
    244      * @throws StatisticalUnitException 
    245      */ 
    246     public Boolean groupByFrequency(String groupByField) throws StatisticalUnitException { 
    247         log.debug("Performing groupByFrequency Statistical Operation"); 
    248         log.debug("Params for method:  {},{}", statisticParameters.getMethodName(), statisticParameters.getUnitName()); 
    249         log.debug("Grouping field: {}", groupByField); 
    250  
    251         DateTime start = startingTime(); 
    252         DateTime end = endingTime(); 
    253         log.debug("groupByFrequency between [start:{}] [end:{}]",start,end); 
    254         String tableName = ReflectionHelper.findEntrySubclassForMethod(groupByField); 
    255         log.debug("Select {}, tableName {}",groupByField,tableName); 
    256         List results = getEntryHandler().query("select "+groupByField+",count(*) from "+tableName+" where (eventTime between '" + start + "' and '" + end + "') group by ("+groupByField+")"); 
    257  
    258         ArrayList<Group> groups = new ArrayList(); 
    259         int testCount =0; 
    260         for (Object result : results) { 
    261             Object[] resultAsArray = (Object[])result; 
    262                 Group group = new Group(); 
    263                 group.setValue((Integer)resultAsArray[1]); 
    264                 group.setGroupName((String) resultAsArray[0]); 
    265                 groups.add(group); 
    266                 testCount+=group.getValue(); 
    267         } 
    268  
    269  
    270         /* test count should equal the number of entries unless there is a reminder as this has not been catered for yet. */ 
    271         log.debug("Entries: {}, total in buckets:{} ", this.getEntryHandler().getNumberOfEntries(), testCount); 
    272  
    273         // add the series label or if none specified, add a default 
    274         if (statisticParameters.getSeriesLabel() == null) 
    275             statisticParameters.setSeriesLabelFormatted("Number of Events Grouped By " + groupByField); 
    276         else{ 
    277             statisticParameters.setSeriesLabelFormatted(statisticParameters.getSeriesLabel()); 
    278         } 
    279  
    280         observations = groups.toArray(new Group[0]); 
    281  
    282         if (observations.length == 0) 
    283             return false; 
    284         // finished successfully, no exception thrown 
    285         return true; 
    286  
    287     } 
    288  
    289     /** 
    290      * Perform the groupByField statistic. This statistic returns a list of distinct values of the given <code>groupByField</code> field. In 
    291      * contrast to the <code>groupByFrequency</code> method, it does not count the occurrence that each distinct value occurs. 
    292      *  It is the responsibility of this method to throw a <code>StatisticalUnitException</code> if the code logic fails, or return false if the 
    293      * statistic functioned correctly, but there are no valid observations, or true if the statistic succeeds and there are valid observations. 
    294      * 
    295      * @param groupByField 
    296      * @return 
    297      * @throws StatisticalUnitException 
    298      */ 
    299     public Boolean groupBy(String groupByField) throws StatisticalUnitException { 
    300         log.debug("Performing groupByFrequency Statistical Operation"); 
    301         log.debug("Params for method:  {},{}", statisticParameters.getMethodName(), statisticParameters.getUnitName()); 
    302         log.debug("Grouping field: {}", groupByField); 
    303  
    304         DateTime start = startingTime(); 
    305         DateTime end = endingTime(); 
    306         log.debug("groupBy between [start:{}] [end:{}]",start,end); 
    307         String tableName = ReflectionHelper.findEntrySubclassForMethod(groupByField); 
    308         log.debug("Select {}, tableName {}",groupByField,tableName); 
    309         List results = getEntryHandler().query("select "+groupByField+" from "+tableName+" where (eventTime between '" + start + "' and '" + end + "') group by ("+groupByField+")"); 
    310  
    311         ArrayList<Group> groups = new ArrayList(); 
    312         for (Object result : results) { 
    313                 Object resultAsArray = (Object)result; 
    314                 Group group = new Group(); 
    315                 group.setValue(0); 
    316                 group.setGroupName((String) resultAsArray); 
    317                 groups.add(group); 
    318  
    319         } 
    320  
    321         // add the series label or if none specified, add a default 
    322         if (statisticParameters.getSeriesLabel() == null) 
    323             statisticParameters.setSeriesLabel("Distinct Values " + groupByField); 
    324  
    325         observations = groups.toArray(new Group[0]); 
    326  
    327         if (observations.length == 0) 
    328             return false; 
    329         // finished successfully, no exception thrown 
    330         return true; 
    331  
    332     } 
    333  
    334     private DateTime startingTime() { 
    335         if (statisticParameters.getStartTimeAsDate() != null) 
    336             return statisticParameters.getStartTimeAsDate(); 
    337         DateTime start = (DateTime) this.getEntryHandler().queryUnique("select min(eventTime) from Entry"); 
    338         return start; 
    339     } 
    340  
    341     private DateTime endingTime() { 
    342         if (statisticParameters.getEndTimeAsDate() != null) 
    343             return statisticParameters.getEndTimeAsDate(); 
    344         DateTime end = (DateTime) this.getEntryHandler().queryUnique("select max(eventTime) from Entry"); 
    345         return end; 
    346     } 
    347  
    348     /** 
    349      * <p> 
    350      * </p> 
    351      * 
    352      * @param date 
    353      * @param isEndTime 
    354      *            - if is endTime and only ddMMyyyy is given, then the endTime should be 23.59 as opposed to 00.00 as this is the end of the day 
    355      * @return 
    356      */ 
    357     private DateTime formatDate(String date, boolean isEndTime) { 
    358         /* this is not a nice hack, please tidy */ 
    359         log.debug("Date format being parsed " + date + " with " + date.length() + " characters"); 
    360         if (date.length() == 8) { 
    361             // assume ddMMyyy 
    362             String format = "ddMMyyyy"; 
    363             DateTimeFormatter dtf = DateTimeFormat.forPattern(format); 
    364             DateTime dt = dtf.parseDateTime(date.substring(0, date.length())); 
    365             if (isEndTime) { 
    366                 dt = new DateTime(dt.getMillis() + 86340000); // where 86340000 is 23.59 hours 
    367             } 
    368             log.debug("time set to " + dt.getDayOfMonth() + "th " + dt.getMonthOfYear() + " " + dt.getYear() + " " + dt.getHourOfDay() + ":" + dt.getMinuteOfHour() + ":" + dt.getSecondOfMinute() + " for " + statisticParameters.getUnitName()); 
    369             return dt; 
    370         } else if (date.length() == 15) { 
    371             // assume yyyyMMdd'T'HHmmss 
    372             String format = "yyyyMMdd'T'HHmmss"; 
    373             DateTimeFormatter dtf = DateTimeFormat.forPattern(format); 
    374             DateTime dt = dtf.parseDateTime(date.substring(0, date.length())); 
    375             log.debug("time set to " + dt.getDayOfMonth() + "th " + dt.getMonthOfYear() + " " + dt.getYear() + " " + dt.getHourOfDay() + ":" + dt.getMinuteOfHour() + ":" + dt.getSecondOfMinute() + " for " + statisticParameters.getUnitName()); 
    376             return dt; 
    377         } 
    378         return new DateTime(); 
    379     } 
     402        private DateTime formatDate(String date, boolean isEndTime) { 
     403                /* this is not a nice hack, please tidy */ 
     404                log.debug("Date format being parsed " + date + " with " + date.length() + " characters"); 
     405                if (date.length() == 8) { 
     406                        // assume ddMMyyy 
     407                        String format = "ddMMyyyy"; 
     408                        DateTimeFormatter dtf = DateTimeFormat.forPattern(format); 
     409                        DateTime dt = dtf.parseDateTime(date.substring(0, date.length())); 
     410                        if (isEndTime) { 
     411                                dt = new DateTime(dt.getMillis() + 86340000); // where 86340000 
     412                                                                                                                                // is 23.59 
     413                                                                                                                                // hours 
     414                        } 
     415                        log.debug("time set to " + dt.getDayOfMonth() + "th " + dt.getMonthOfYear() + " " + dt.getYear() + " " 
     416                                        + dt.getHourOfDay() + ":" + dt.getMinuteOfHour() + ":" + dt.getSecondOfMinute() + " for " 
     417                                        + statisticParameters.getUnitName()); 
     418                        return dt; 
     419                } else if (date.length() == 15) { 
     420                        // assume yyyyMMdd'T'HHmmss 
     421                        String format = "yyyyMMdd'T'HHmmss"; 
     422                        DateTimeFormatter dtf = DateTimeFormat.forPattern(format); 
     423                        DateTime dt = dtf.parseDateTime(date.substring(0, date.length())); 
     424                        log.debug("time set to " + dt.getDayOfMonth() + "th " + dt.getMonthOfYear() + " " + dt.getYear() + " " 
     425                                        + dt.getHourOfDay() + ":" + dt.getMinuteOfHour() + ":" + dt.getSecondOfMinute() + " for " 
     426                                        + statisticParameters.getUnitName()); 
     427                        return dt; 
     428                } 
     429                return new DateTime(); 
     430        } 
    380431 
    381432} 
  • raptor-mua/trunk/src/main/java/uk/ac/cardiff/raptormua/engine/statistics/StatisticsHandler.java

    r439 r500  
    2828import uk.ac.cardiff.model.Entry; 
    2929import uk.ac.cardiff.model.Graph.AggregatorGraphModel; 
     30import uk.ac.cardiff.model.sql.SQLFilter; 
    3031import uk.ac.cardiff.model.wsmodel.MethodParameter; 
    3132import uk.ac.cardiff.model.wsmodel.StatisticalUnitInformation; 
     
    3637 */ 
    3738public class StatisticsHandler { 
    38     static Logger log = LoggerFactory.getLogger(StatisticsHandler.class); 
     39        static Logger log = LoggerFactory.getLogger(StatisticsHandler.class); 
    3940 
    40     private List<Statistic> statisticalUnits; 
     41        private List<Statistic> statisticalUnits; 
    4142 
    42     private EntryHandler entryHandler; 
     43        private EntryHandler entryHandler; 
    4344 
    44     public void setStatisticalUnits(List<Statistic> statisticalUnits) { 
    45         this.statisticalUnits = statisticalUnits; 
    46     } 
    47  
    48     public List<Statistic> getStatisticalUnits() { 
    49         return statisticalUnits; 
    50     } 
    51  
    52     /** 
    53      * @param statisticName 
    54      */ 
    55     public AggregatorGraphModel peformStatistic(String statisticName) { 
    56         for (Statistic statistic : statisticalUnits) { 
    57             if (statistic.getStatisticParameters().getUnitName().equals(statisticName)) { 
    58                 return performStatiticalPipeline(statistic);  
    59             } 
    60         } 
    61         return null; 
    62     } 
    63  
    64     private AggregatorGraphModel performStatiticalPipeline(Statistic statistic) { 
    65         // on set entries, also perform preprocessing, could be done as an extra method call 
    66         statistic.setEntryHandler(entryHandler); 
    67         Boolean success = invoke(statistic); 
    68         log.info("Statistic succedded " + success); 
    69         if (success) { 
    70             // now send through post processor 
    71             statistic.postProcess(); 
    72             return statistic.constructGraphModel(); 
    73         } 
    74         return null; 
    75     } 
    76  
    77     /** 
    78      * @param statistic 
    79      */ 
    80     private Boolean invoke(Statistic statistic) { 
    81         if (this.getEntryHandler() != null) 
    82             log.debug("Working off " + this.getEntryHandler().getNumberOfEntries() + " entries"); 
    83  
    84         /* stop processing if there are no valid entries */ 
    85         if (this.getEntryHandler() == null || this.getEntryHandler().getNumberOfEntries() == 0) { 
    86             log.error("Not enough entries to perform statistic countEntryPerInterval"); 
    87             return false; 
     45        public void setStatisticalUnits(List<Statistic> statisticalUnits) { 
     46                this.statisticalUnits = statisticalUnits; 
    8847        } 
    8948 
    90         try { 
    91             List<MethodParameter> params = statistic.getStatisticParameters().getMethodParams(); 
    92             Object[] paramsO = new Object[params.size()]; 
    93             for (int i = 0; i < paramsO.length; i++) { 
    94                 paramsO[i] = params.get(i).getParameter(); 
    95             } 
    96             return invoke(statistic.getStatisticParameters().getMethodName(), paramsO, statistic); 
    97         } catch (Exception e) { 
    98             e.printStackTrace(); 
     49        public List<Statistic> getStatisticalUnits() { 
     50                return statisticalUnits; 
    9951        } 
    100         return null; 
    10152 
    102     } 
     53        /** 
     54         * @param statisticName 
     55         */ 
     56        public AggregatorGraphModel peformStatistic(String statisticName) { 
     57                for (Statistic statistic : statisticalUnits) { 
     58                        if (statistic.getStatisticParameters().getUnitName().equals(statisticName)) { 
     59                                return performStatiticalPipeline(statistic); 
     60                        } 
     61                } 
     62                return null; 
     63        } 
    10364 
    104     private Boolean invoke(String fieldname, Object[] params, Object object) { 
    105         try { 
    106             Class id = object.getClass(); 
    107             Class[] paramC = new Class[params.length]; 
    108             for (int i = 0; i < params.length; i++) { 
    109                 paramC[i] = params[i].getClass(); 
    110             } 
    111             log.debug("Calling method: " + fieldname + " on " + object); 
    112             Method statisticalMethod = id.getMethod(fieldname, paramC); 
    113             // log.debug("Trying to Set :"+setter); 
    114             Boolean success = (Boolean) statisticalMethod.invoke(object, params); 
    115             return success; 
    116         } catch (Throwable e) { 
    117             log.error("Field name '" + fieldname + "' does not match internal model attribute"); 
    118             e.printStackTrace(); 
    119             // System.exit(1); 
     65        private AggregatorGraphModel performStatiticalPipeline(Statistic statistic) { 
     66                // on set entries, also perform preprocessing, could be done as an extra 
     67                // method call 
     68                statistic.setEntryHandler(entryHandler); 
     69                Boolean success = invoke(statistic); 
     70                log.info("Statistic succedded " + success); 
     71                if (success) { 
     72                        // now send through post processor 
     73                        statistic.postProcess(); 
     74                        return statistic.constructGraphModel(); 
     75                } 
     76                return null; 
     77        } 
     78 
     79        /** 
     80         * @param statistic 
     81         */ 
     82        private Boolean invoke(Statistic statistic) { 
     83                if (this.getEntryHandler() != null) 
     84                        log.debug("Working off " + this.getEntryHandler().getNumberOfEntries() + " entries"); 
     85 
     86                /* stop processing if there are no valid entries */ 
     87                if (this.getEntryHandler() == null || this.getEntryHandler().getNumberOfEntries() == 0) { 
     88                        log.error("Not enough entries to perform statistic countEntryPerInterval"); 
     89                        return false; 
     90                } 
     91 
     92                try { 
     93                        List<MethodParameter> params = statistic.getStatisticParameters().getMethodParams(); 
     94                        SQLFilter sqlFilter = statistic.getStatisticParameters().getSqlFilter(); 
     95                        String whereClause=null; 
     96                        if (sqlFilter !=null){ 
     97                                SQLFilterConstructor sqlConstructor = new SQLFilterConstructor(sqlFilter); 
     98                                whereClause = sqlConstructor.convertFilterToString(); 
     99                        }                        
     100                        Object[] paramsO = new Object[params.size() + 1]; 
     101                        for (int i = 0; i < paramsO.length-1; i++) { 
     102                                paramsO[i] = params.get(i).getParameter(); 
     103                        } 
     104                        if (whereClause!=null) 
     105                                paramsO[paramsO.length - 1] = whereClause; 
     106                        else  
     107                                paramsO[paramsO.length - 1] = new String(); 
     108                        return invoke(statistic.getStatisticParameters().getMethodName(), paramsO, statistic); 
     109                } catch (Exception e) { 
     110                        log.error("Failed to invoke statistics {} -> {}",statistic.getStatisticParameters().getUnitName(),e.getMessage()); 
     111                        e.printStackTrace(); 
     112                } 
     113                return null; 
    120114 
    121115        } 
    122         return null; 
    123     } 
    124116 
    125     /** 
    126      * updates a statistical unit based on the values in the <code>statisticalUnitInformation</code> parameter Not a very good primary key (unit name) should be 
    127      * something else 
    128      * 
    129      * @param statisticalUnitInformation 
    130      */ 
    131     public void updateStatisticalUnit(StatisticalUnitInformation statisticalUnitInformation) { 
    132         log.info("Updating statistical unit {} ", statisticalUnitInformation.getStatisticParameters().getUnitName()); 
    133         Statistic toUpdate = null; 
    134         for (Statistic statistic : statisticalUnits) { 
    135             if (statistic.getStatisticParameters().getUnitName().equals(statisticalUnitInformation.getStatisticParameters().getUnitName())) 
    136                 toUpdate = statistic; 
     117        private Boolean invoke(String fieldname, Object[] params, Object object) { 
     118                try { 
     119                        Class id = object.getClass(); 
     120                        Class[] paramC = new Class[params.length]; 
     121                        for (int i = 0; i < params.length; i++) { 
     122                                paramC[i] = params[i].getClass(); 
     123                        } 
     124                        log.debug("Calling method: " + fieldname + " on " + object); 
     125                        Method statisticalMethod = id.getMethod(fieldname, paramC); 
     126                        // log.debug("Trying to Set :"+setter); 
     127                        Boolean success = (Boolean) statisticalMethod.invoke(object, params); 
     128                        return success; 
     129                } catch (Throwable e) { 
     130                        log.error("Field name '" + fieldname + "' does not match internal model attribute"); 
     131                        e.printStackTrace(); 
     132                        // System.exit(1); 
     133 
     134                } 
     135                return null; 
    137136        } 
    138         log.debug("Found Statistic {} to update", toUpdate); 
    139         update(toUpdate, statisticalUnitInformation); 
    140137 
    141     } 
     138        /** 
     139         * updates a statistical unit based on the values in the 
     140         * <code>statisticalUnitInformation</code> parameter Not a very good primary 
     141         * key (unit name) should be something else 
     142         *  
     143         * @param statisticalUnitInformation 
     144         */ 
     145        public void updateStatisticalUnit(StatisticalUnitInformation statisticalUnitInformation) { 
     146                log.info("Updating statistical unit {} ", statisticalUnitInformation.getStatisticParameters().getUnitName()); 
     147                Statistic toUpdate = null; 
     148                for (Statistic statistic : statisticalUnits) { 
     149                        if (statistic.getStatisticParameters().getUnitName() 
     150                                        .equals(statisticalUnitInformation.getStatisticParameters().getUnitName())) 
     151                                toUpdate = statistic; 
     152                } 
     153                log.debug("Found Statistic {} to update", toUpdate); 
     154                update(toUpdate, statisticalUnitInformation); 
    142155 
    143     /** 
    144      * Only currently updates certain values, these will need to be completed in the future 
    145      * 
    146      * @param statistic 
    147      * @param statisticalUnitInformation 
    148      */ 
    149     private void update(Statistic statistic, StatisticalUnitInformation statisticalUnitInformation) { 
    150         if (statisticalUnitInformation.getStatisticParameters().getEndTimeAsDate()!=null) 
    151             statistic.getStatisticParameters().setEndTime(statisticalUnitInformation.getStatisticParameters().getEndTimeAsDate()); 
    152         if (statisticalUnitInformation.getStatisticParameters().getStartTimeAsDate()!=null) 
    153             statistic.getStatisticParameters().setStartTime(statisticalUnitInformation.getStatisticParameters().getStartTimeAsDate()); 
    154         if (statisticalUnitInformation.getStatisticParameters().getMethodParams()!=null) 
    155             statistic.getStatisticParameters().setMethodParams(statisticalUnitInformation.getStatisticParameters().getMethodParams()); 
    156         if (statisticalUnitInformation.getStatisticParameters().getSeriesLabel()!=null) 
    157             statistic.getStatisticParameters().setSeriesLabel(statisticalUnitInformation.getStatisticParameters().getSeriesLabel()); 
    158     } 
     156        } 
    159157 
    160     /** 
    161      * 
    162      * @param entryHandler 
    163      */ 
    164     public void setEntryHandler(EntryHandler entryHandler) { 
    165         this.entryHandler = entryHandler; 
    166     } 
     158        /** 
     159         * Only currently updates certain values, these will need to be completed in 
     160         * the future 
     161         *  
     162         * @param statistic 
     163         * @param statisticalUnitInformation 
     164         */ 
     165        private void update(Statistic statistic, StatisticalUnitInformation statisticalUnitInformation) { 
     166                if (statisticalUnitInformation.getStatisticParameters().getEndTimeAsDate() != null) 
     167                        statistic.getStatisticParameters().setEndTime( 
     168                                        statisticalUnitInformation.getStatisticParameters().getEndTimeAsDate()); 
     169                if (statisticalUnitInformation.getStatisticParameters().getStartTimeAsDate() != null) 
     170                        statistic.getStatisticParameters().setStartTime( 
     171                                        statisticalUnitInformation.getStatisticParameters().getStartTimeAsDate()); 
     172                if (statisticalUnitInformation.getStatisticParameters().getMethodParams() != null) 
     173                        statistic.getStatisticParameters().setMethodParams( 
     174                                        statisticalUnitInformation.getStatisticParameters().getMethodParams()); 
     175                if (statisticalUnitInformation.getStatisticParameters().getSeriesLabel() != null) 
     176                        statistic.getStatisticParameters().setSeriesLabel( 
     177                                        statisticalUnitInformation.getStatisticParameters().getSeriesLabel()); 
     178        } 
    167179 
    168     /** 
    169      * 
    170      * @return 
    171      */ 
    172     public EntryHandler getEntryHandler() { 
    173         return entryHandler; 
    174     } 
     180        /** 
     181         *  
     182         * @param entryHandler 
     183         */ 
     184        public void setEntryHandler(EntryHandler entryHandler) { 
     185                this.entryHandler = entryHandler; 
     186        } 
     187 
     188        /** 
     189         *  
     190         * @return 
     191         */ 
     192        public EntryHandler getEntryHandler() { 
     193                return entryHandler; 
     194        } 
    175195 
    176196} 
  • raptor-mua/trunk/src/main/java/uk/ac/cardiff/raptormua/service/impl/MUAProcessImpl.java

    r495 r500  
    3838 
    3939/** 
    40  * All operations should go through this service class, so as to obey locks and synchronisation issues. Locks collisions are thrown 
    41  * use a <code>SoapFault</code>. Fault codes are: 
    42  * Client (if a malformed input e.g. statistic name is wrong) 
    43  * Server (we use for locks, as server side issue) 
    44  * VersionMismatch 
    45  * MustUnderstand 
    46  * 
     40 * All operations should go through this service class, so as to obey locks and 
     41 * synchronisation issues. Locks collisions are thrown use a 
     42 * <code>SoapFault</code>. Fault codes are: Client (if a malformed input e.g. 
     43 * statistic name is wrong) Server (we use for locks, as server side issue) 
     44 * VersionMismatch MustUnderstand 
     45 *  
    4746 * @author philsmart 
    48  * 
     47 *  
    4948 */ 
    5049public class MUAProcessImpl implements MUAProcess { 
    5150 
    52     /* class logger */ 
    53     static Logger log = LoggerFactory.getLogger(MUAProcessImpl.class); 
    54  
    55     /* main engine of the MultiUnitAggregator */ 
    56     private MUAEngine engine; 
    57  
    58     /* 
    59      * ReentrantLock to prevent more than at the same time 
    60      */ 
    61     final Lock lockR = new ReentrantLock(); 
    62  
    63     public void setEngine(MUAEngine engine) { 
    64         this.engine = engine; 
    65     } 
    66  
    67     public MUAEngine getEngine() { 
    68         return engine; 
    69     } 
    70  
    71     /* 
    72      * The MUA no longer polls for data from the UA, but this is still here in case it is needed 
    73      * 
    74      * (non-Javadoc) 
    75      * 
    76      * @see uk.ac.cardiff.raptormua.service.MUAProcess#poll() 
    77      */ 
    78     public void poll() { 
    79         if (lockR.tryLock()) { 
    80             try { 
    81                 // engine.poll(); 
    82             } catch (Exception e) { 
    83                 // TODO either throw as service output, or deal with here 
    84                 log.error(e.getMessage()); 
    85                 e.printStackTrace(); 
    86             } finally { 
    87                 lockR.unlock(); 
    88             } 
    89         } 
    90  
    91     } 
    92  
    93     /* 
    94      * (non-Javadoc) 
    95      * 
    96      * @see uk.ac.cardiff.raptormua.service.MUAProcess#performStatistics(java.lang .String) 
    97      */ 
    98     public AggregatorGraphModel performStatistic(String statisticName) throws SoapFault{ 
    99         if (lockR.tryLock()) { 
    100             try { 
    101                 log.info("WebSservice call for perform statistic {} ", statisticName); 
    102                 return engine.performStatistic(statisticName); 
    103             } catch (Exception e) { 
    104                 // TODO either throw as service output, or deal with here 
    105                 log.error(e.getMessage()); 
    106                 e.printStackTrace(); 
    107             } finally { 
    108                 lockR.unlock(); 
    109             } 
    110         } 
    111         log.warn("Lock was hit for method performStatistic"); 
    112         throw new SoapFault("lock was hit on method performStatistic", new QName("Server")); 
    113  
    114     } 
    115  
    116     /* 
    117      * Method does not need to be locked. (non-Javadoc) 
    118      * 
    119      * @see uk.ac.cardiff.raptormua.service.MUAProcess#getCapabilities() 
    120      */ 
    121     public Capabilities getCapabilities() { 
    122         log.info("WebSservice call for get capabilities"); 
    123         return engine.getCapabilities(); 
    124     } 
    125  
    126     /* 
    127      * (non-Javadoc) 
    128      * 
    129      * @see uk.ac.cardiff.raptormua.service.MUAProcess#setStatisticalUnit(uk.ac.cardiff .model.wsmodel.StatisticalUnitInformation) 
    130      */ 
    131     @Override 
    132     public void updateStatisticalUnit(StatisticalUnitInformation statisticalUnitInformation) throws SoapFault { 
    133         boolean success = false; 
    134         if (lockR.tryLock()) { 
    135             try { 
    136                 log.info("Updating statistical unit {}",statisticalUnitInformation.getStatisticParameters().getUnitName()); 
    137                 engine.updateStatisticalUnit(statisticalUnitInformation); 
    138                 success = true; 
    139             } catch (Exception e) { 
    140                 // TODO either throw as service output, or deal with here 
    141                 log.error(e.getMessage()); 
    142                 e.printStackTrace(); 
    143             } finally { 
    144                 lockR.unlock(); 
    145             } 
    146         } 
    147         if (!success){ 
    148             log.warn("Lock was hit for method updateStatisticalUnit"); 
    149             throw new SoapFault("lock was hit on method updateStatisticalUnit", new QName("Server")); 
    150         } 
    151     } 
    152  
    153     /* 
    154      * (non-Javadoc) 
    155      * 
    156      * @see uk.ac.cardiff.raptormua.service.MUAProcess#performAdministrativeFunction (uk.ac.cardiff.model.AdministrativeFunction.AdministrativeFunctionType) 
    157      */ 
    158     @Override 
    159     public boolean performAdministrativeFunction(AdministrativeFunction function) throws SoapFault { 
    160         if (lockR.tryLock()) { 
    161             try { 
    162                 log.info("Performing administrative function {}, request orginates from {}", function.getAdministrativeFunction(), function.getRequester()); 
    163                 return engine.performAdministrativeFunction(function); 
    164             } catch (Exception e) { 
    165                 // TODO either throw as service output, or deal with here 
    166                 log.error(e.getMessage()); 
    167                 e.printStackTrace(); 
    168                 return false; 
    169             } finally { 
    170                 lockR.unlock(); 
    171  
    172             } 
    173  
    174         } 
    175         log.warn("Lock was hit for method performAdministrativeFunction"); 
    176         throw new SoapFault("lock was hit on method performAdministrativeFunction", new QName("Server")); 
    177     } 
    178  
    179     /* 
    180      * (non-Javadoc) 
    181      * 
    182      * @see uk.ac.cardiff.raptormua.service.MUAProcess#addAuthentications(uk.ac.cardiff .model.wsmodel.UAEntryPush) 
    183      */ 
    184     @Override 
    185     public void addAuthentications(UAEntryPush pushed) { 
    186         boolean success = false; 
    187         if (lockR.tryLock()) { 
    188             try { 
    189                 log.info("MUA has received {} entries from {}", pushed.getEntries().size(), pushed.getUaMetaData().getUaName()); 
    190                 engine.addAuthentications(pushed); 
    191                 success = true; 
    192             } catch (Exception e) { 
    193                 // TODO either throw as service output, or deal with here 
    194                 log.error(e.getMessage()); 
    195                 e.printStackTrace(); 
    196             } finally { 
    197                 lockR.unlock(); 
    198  
    199             } 
    200         } 
    201         if (!success) 
    202             log.warn("Lock was hit for method addAuthentications"); 
    203  
    204     } 
    205  
    206     @Override 
    207     public AggregatorGraphModel updateAndInvokeStatisticalUnit(StatisticalUnitInformation statisticalUnitInformation) throws SoapFault { 
    208         if (lockR.tryLock()) { 
    209             try { 
    210                 log.info("Webservice call to update and perform statistic {}", statisticalUnitInformation.getStatisticParameters().getUnitName()); 
    211                 engine.updateStatisticalUnit(statisticalUnitInformation); 
    212                 return engine.performStatistic(statisticalUnitInformation.getStatisticParameters().getUnitName()); 
    213             } catch (Exception e) { 
    214                 // TODO either throw as service output, or deal with here 
    215                 log.error(e.getMessage()); 
    216                 e.printStackTrace(); 
    217             } finally { 
    218                 lockR.unlock(); 
    219             } 
    220         } 
    221         log.warn("Lock was hit for method updateAndInvokeStatisticalUnit"); 
    222         throw new SoapFault("lock was hit on method updateAndInvokeStatisticalUnit", new QName("Server")); 
    223  
    224     } 
     51        /* class logger */ 
     52        static Logger log = LoggerFactory.getLogger(MUAProcessImpl.class); 
     53 
     54        /* main engine of the MultiUnitAggregator */ 
     55        private MUAEngine engine; 
     56 
     57        /* 
     58         * ReentrantLock to prevent more than at the same time 
     59         */ 
     60        final Lock lockR = new ReentrantLock(); 
     61 
     62        public void setEngine(MUAEngine engine) { 
     63                this.engine = engine; 
     64        } 
     65 
     66        public MUAEngine getEngine() { 
     67                return engine; 
     68        } 
     69 
     70        /* 
     71         * The MUA no longer polls for data from the UA, but this is still here in 
     72         * case it is needed 
     73         *  
     74         * (non-Javadoc) 
     75         *  
     76         * @see uk.ac.cardiff.raptormua.service.MUAProcess#poll() 
     77         */ 
     78        public void poll() { 
     79                if (lockR.tryLock()) { 
     80                        try { 
     81                                // engine.poll(); 
     82                        } catch (Exception e) { 
     83                                // TODO either throw as service output, or deal with here 
     84                                log.error(e.getMessage()); 
     85                                e.printStackTrace(); 
     86                        } finally { 
     87                                lockR.unlock(); 
     88                        } 
     89                } 
     90 
     91        } 
     92 
     93        /* 
     94         * (non-Javadoc) 
     95         *  
     96         * @see 
     97         * uk.ac.cardiff.raptormua.service.MUAProcess#performStatistics(java.lang 
     98         * .String) 
     99         */ 
     100        public AggregatorGraphModel performStatistic(String statisticName) throws SoapFault { 
     101                if (lockR.tryLock()) { 
     102                        try { 
     103                                log.info("WebSservice call for perform statistic {} ", statisticName); 
     104                                return engine.performStatistic(statisticName); 
     105                        } catch (Exception e) { 
     106                                // TODO either throw as service output, or deal with here 
     107                                log.error(e.getMessage()); 
     108                                e.printStackTrace(); 
     109                        } finally { 
     110                                lockR.unlock(); 
     111                        } 
     112                } 
     113                log.warn("Lock was hit for method performStatistic"); 
     114                throw new SoapFault("lock was hit on method performStatistic", new QName("Server")); 
     115 
     116        } 
     117 
     118        /* 
     119         * Method does not need to be locked. (non-Javadoc) 
     120         *  
     121         * @see uk.ac.cardiff.raptormua.service.MUAProcess#getCapabilities() 
     122         */ 
     123        public Capabilities getCapabilities() { 
     124                log.info("WebSservice call for get capabilities"); 
     125                return engine.getCapabilities(); 
     126        } 
     127 
     128        /* 
     129         * (non-Javadoc) 
     130         *  
     131         * @see 
     132         * uk.ac.cardiff.raptormua.service.MUAProcess#setStatisticalUnit(uk.ac.cardiff 
     133         * .model.wsmodel.StatisticalUnitInformation) 
     134         */ 
     135        @Override 
     136        public void updateStatisticalUnit(StatisticalUnitInformation statisticalUnitInformation) throws SoapFault { 
     137                boolean success = false; 
     138                if (lockR.tryLock()) { 
     139                        try { 
     140                                log.info("Updating statistical unit {}", statisticalUnitInformation.getStatisticParameters() 
     141                                                .getUnitName()); 
     142                                engine.updateStatisticalUnit(statisticalUnitInformation); 
     143                                success = true; 
     144                        } catch (Exception e) { 
     145                                // TODO either throw as service output, or deal with here 
     146                                log.error(e.getMessage()); 
     147                                e.printStackTrace(); 
     148                        } finally { 
     149                                lockR.unlock(); 
     150                        } 
     151                } 
     152                if (!success) { 
     153                        log.warn("Lock was hit for method updateStatisticalUnit"); 
     154                        throw new SoapFault("lock was hit on method updateStatisticalUnit", new QName("Server")); 
     155                } 
     156        } 
     157 
     158        /* 
     159         * (non-Javadoc) 
     160         *  
     161         * @see 
     162         * uk.ac.cardiff.raptormua.service.MUAProcess#performAdministrativeFunction 
     163         * (uk.ac.cardiff.model.AdministrativeFunction.AdministrativeFunctionType) 
     164         */ 
     165        @Override 
     166        public boolean performAdministrativeFunction(AdministrativeFunction function) throws SoapFault { 
     167                if (lockR.tryLock()) { 
     168                        try { 
     169                                log.info("Performing administrative function {}, request orginates from {}", 
     170                                                function.getAdministrativeFunction(), function.getRequester()); 
     171                                return engine.performAdministrativeFunction(function); 
     172                        } catch (Exception e) { 
     173                                // TODO either throw as service output, or deal with here 
     174                                log.error(e.getMessage()); 
     175                                e.printStackTrace(); 
     176                                return false; 
     177                        } finally { 
     178                                lockR.unlock(); 
     179 
     180                        } 
     181 
     182                } 
     183                log.warn("Lock was hit for method performAdministrativeFunction"); 
     184                throw new SoapFault("lock was hit on method performAdministrativeFunction", new QName("Server")); 
     185        } 
     186 
     187        /* 
     188         * (non-Javadoc) 
     189         *  
     190         * @see 
     191         * uk.ac.cardiff.raptormua.service.MUAProcess#addAuthentications(uk.ac.cardiff 
     192         * .model.wsmodel.UAEntryPush) 
     193         */ 
     194        @Override 
     195        public void addAuthentications(UAEntryPush pushed) { 
     196                boolean success = false; 
     197                if (lockR.tryLock()) { 
     198                        try { 
     199                                log.info("MUA has received {} entries from {}", pushed.getEntries().size(), pushed.getUaMetaData() 
     200                                                .getUaName()); 
     201                                engine.addAuthentications(pushed); 
     202                                success = true; 
     203                        } catch (Exception e) { 
     204                                // TODO either throw as service output, or deal with here 
     205                                log.error(e.getMessage()); 
     206                                e.printStackTrace(); 
     207                        } finally { 
     208                                lockR.unlock(); 
     209 
     210                        } 
     211                } 
     212                if (!success) 
     213                        log.warn("Lock was hit for method addAuthentications"); 
     214 
     215        } 
     216 
     217        @Override 
     218        public AggregatorGraphModel updateAndInvokeStatisticalUnit(StatisticalUnitInformation statisticalUnitInformation) 
     219                        throws SoapFault { 
     220                if (lockR.tryLock()) { 
     221                        try { 
     222                                log.info("Webservice call to update and perform statistic {}", statisticalUnitInformation 
     223                                                .getStatisticParameters().getUnitName()); 
     224                                engine.updateStatisticalUnit(statisticalUnitInformation); 
     225                                return engine.performStatistic(statisticalUnitInformation.getStatisticParameters().getUnitName()); 
     226                        } catch (Exception e) { 
     227                                // TODO either throw as service output, or deal with here 
     228                                log.error(e.getMessage()); 
     229                                e.printStackTrace(); 
     230                        } finally { 
     231                                lockR.unlock(); 
     232                        } 
     233                } 
     234                log.warn("Lock was hit for method updateAndInvokeStatisticalUnit"); 
     235                throw new SoapFault("lock was hit on method updateAndInvokeStatisticalUnit", new QName("Server")); 
     236 
     237        } 
    225238 
    226239} 
  • raptor-mua/trunk/src/main/webapp/WEB-INF/statistical-units.xml

    r489 r500  
    3636                                <ref bean="bottom5Resources"/> 
    3737                                <ref bean="numberOfAuthenticationsPerIntervalNumber"/> 
     38                                <ref bean="authenticationsForOneSP"/> 
    3839                        </list> 
    3940                </property> 
     
    165166 
    166167 
     168        <bean id="authenticationsForOneSP" class="uk.ac.cardiff.raptormua.engine.statistics.AuthenticationStatistic"> 
     169                <property name="statisticParameters"> 
     170                        <bean class="uk.ac.cardiff.model.StatisticParameters"> 
     171                                        <property name="statisticType"><value>User</value></property> 
     172                                        <property name="unitName"><value>Authentications Over Time For A Single SP (by Organisational Name)</value></property> 
     173                                        <property name="methodName"><value>countEntryPerInterval</value></property> 
     174                                        <property name="startTime"><value>20101020T140000</value></property>   <!-- presently only ddMMyyy or yyyyMMdd'T'HHmmss --> 
     175                                        <property name="endTime"><value>20110115T170000</value></property>  <!-- presently only ddMMyyy or yyyyMMdd'T'HHmmss e.g. 20101020T225100Z --> 
     176                                        <property name="seriesLabel"><value>Number of authentications for service provider</value></property> 
     177                                        <property name="methodParams"> 
     178                                                <list> 
     179                                                        <bean class="uk.ac.cardiff.model.wsmodel.MethodParameter"> 
     180                                                                <property name="parameter"><value>1000</value></property> 
     181                                                        </bean> 
     182                                                </list> 
     183                                        </property> 
     184                                        <property name="sqlFilter"><ref bean="testWhere"></ref></property> 
     185                        </bean> 
     186                </property> 
     187                <property name="postprocessor"> 
     188                        <list> 
     189                                <ref bean="ShibbolethMetadataNameFormatter"></ref> 
     190                        </list> 
     191                </property> 
     192        </bean> 
    167193 
    168194        <!--  Support statistical workflows --> 
     
    190216 
    191217        <bean id="numberFormat" class = "uk.ac.cardiff.raptormua.engine.statistics.NumberFormatterPostProcessor"> 
     218        </bean> 
     219         
     220        <!-- test SQL where filters , follows subset of SQL-99 spec, but too verbose--> 
     221         
     222        <bean id="testWhere" class="uk.ac.cardiff.model.sql.SQLWhere"> 
     223                <property name="booleanExpression"> 
     224                        <bean class="uk.ac.cardiff.model.sql.BooleanExpression"> 
     225                                <property name="booleanTerm"> 
     226                                        <bean class="uk.ac.cardiff.model.sql.BooleanTerm"> 
     227                                                <property name="booleanFactor"> 
     228                                                        <bean class="uk.ac.cardiff.model.sql.BooleanFactor"> 
     229                                                                <property name="booleanTest"> 
     230                                                                        <bean class="uk.ac.cardiff.model.sql.BooleanTest"> 
     231                                                                                <property name="booleanPrimary"> 
     232                                                                                        <bean class="uk.ac.cardiff.model.sql.BooleanPrimary"> 
     233                                                                                                <property name="predicate"> 
     234                                                                                                        <bean class="uk.ac.cardiff.model.sql.Predicate"> 
     235                                                                                                                <property name="comparisonPredicate"> 
     236                                                                                                                        <bean class="uk.ac.cardiff.model.sql.ComparisonPredicate"> 
     237                                                                                                                                <property name="compOp" value="EQUAL"/> 
     238                                                                                                                                <property name="fieldName" value="requestHost"/> 
     239                                                                                                                                <property name="value" value="https://sdauth.sciencedirect.com/"/> 
     240                                                                                                                        </bean> 
     241                                                                                                                </property> 
     242                                                                                                        </bean> 
     243                                                                                                </property>                                                                                      
     244                                                                                        </bean> 
     245                                                                                </property> 
     246                                                                        </bean> 
     247                                                                </property> 
     248                                                        </bean> 
     249                                                </property> 
     250                                        </bean> 
     251                                </property> 
     252                        </bean> 
     253                </property>  
     254         
    192255        </bean> 
    193256 
Note: See TracChangeset for help on using the changeset viewer.