@Override
public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception {
String service = Util.getParam(params, SERVICE_PARAM);
Element response = new Element("response");
final SearchRequestRepository requestRepository = context.getBean(SearchRequestRepository.class);
ISODate begin = requestRepository.getOldestRequestDate();
ISODate end = requestRepository.getMostRecentRequestDate();
if (begin == null || end == null) {
return response; // No stats available.
}
DateTime beginDate = ISODate.parseBasicOrFullDateTime(begin.getDateAndTime());
DateTime endDate = ISODate.parseBasicOrFullDateTime(end.getDateAndTime());
int days = Days.daysBetween(beginDate, endDate).getDays();
int nonZeroDays = days == 0 ? 1 : days;
int months = Months.monthsBetween(beginDate, endDate).getMonths();
int nonZeroMonths = months == 0 ? 1 : months;
response.addContent(new Element("activity_days").setText(days + ""));
response.addContent(new Element("activity_months").setText(months + ""));
// Total number of searches
long total = requestRepository.count(hasService(service));
addSingleDBValueToElement(response, total, "total_searches", "total");
// Average searches by day
long avgPerDay = total / nonZeroDays;
addSingleDBValueToElement(response, avgPerDay, "avg_searches_by_day", "avg");
// Average searches by month
long avgPerMonth = total / nonZeroMonths;
addSingleDBValueToElement(response, avgPerMonth, "avg_searches_by_month", "avg");
// Average views by day
final int views = context.getBean(MetadataRepository.class).getMetadataStatistics().getTotalStat(popularitySum(),
Optional.<Specification<Metadata>>absent());
int viewsByDay = views / nonZeroDays;
addSingleDBValueToElement(response, viewsByDay, "avg_views_by_day", "avg");
// Average views by month
int viewsByMonth = views / nonZeroMonths;
addSingleDBValueToElement(response, viewsByMonth, "avg_views_by_month", "avg");
// Number of search with no hits
long noHits = requestRepository.count(where(hasService(service)).and(hasHits(0)));
addSingleDBValueToElement(response, noHits, "total_searches_with_no_hits", "total");
return response;
}