Example usage for org.joda.time LocalDateTime isBefore

List of usage examples for org.joda.time LocalDateTime isBefore

Introduction

In this page you can find the example usage for org.joda.time LocalDateTime isBefore.

Prototype

public boolean isBefore(ReadablePartial partial) 

Source Link

Document

Is this partial earlier than the specified partial.

Usage

From source file:org.apache.fineract.infrastructure.scheduledemail.service.EmailCampaignWritePlatformCommandHandlerImpl.java

License:Apache License

@Override
@CronTarget(jobName = JobName.UPDATE_EMAIL_OUTBOUND_WITH_CAMPAIGN_MESSAGE)
public void storeTemplateMessageIntoEmailOutBoundTable() throws JobExecutionException {
    final Collection<EmailCampaignData> emailCampaignDataCollection = this.emailCampaignReadPlatformService
            .retrieveAllScheduleActiveCampaign();
    if (emailCampaignDataCollection != null) {
        for (EmailCampaignData emailCampaignData : emailCampaignDataCollection) {
            LocalDateTime tenantDateNow = tenantDateTime();
            LocalDateTime nextTriggerDate = emailCampaignData.getNextTriggerDate().toLocalDateTime();

            logger.info(/* w  w  w  . j  a va 2  s  .c o  m*/
                    "tenant time " + tenantDateNow.toString() + " trigger time " + nextTriggerDate.toString());
            if (nextTriggerDate.isBefore(tenantDateNow)) {
                insertDirectCampaignIntoEmailOutboundTable(emailCampaignData.getParamValue(),
                        emailCampaignData.getEmailSubject(), emailCampaignData.getMessage(),
                        emailCampaignData.getCampaignName(), emailCampaignData.getId());
                this.updateTriggerDates(emailCampaignData.getId());
            }
        }
    }
}

From source file:org.apache.fineract.infrastructure.sms.service.SmsCampaignWritePlatformCommandHandlerImpl.java

License:Apache License

@Override
@CronTarget(jobName = JobName.UPDATE_SMS_OUTBOUND_WITH_CAMPAIGN_MESSAGE)
public void storeTemplateMessageIntoSmsOutBoundTable() throws JobExecutionException {
    final Collection<SmsCampaignData> smsCampaignDataCollection = this.smsCampaignReadPlatformService
            .retrieveAllScheduleActiveCampaign();
    if (smsCampaignDataCollection != null) {
        for (SmsCampaignData smsCampaignData : smsCampaignDataCollection) {
            LocalDateTime tenantDateNow = tenantDateTime();
            LocalDateTime nextTriggerDate = smsCampaignData.getNextTriggerDate().toLocalDateTime();

            logger.info(/*from   ww w .j av  a 2s.  c o m*/
                    "tenant time " + tenantDateNow.toString() + " trigger time " + nextTriggerDate.toString());
            if (nextTriggerDate.isBefore(tenantDateNow)) {
                insertDirectCampaignIntoSmsOutboundTable(smsCampaignData.getParamValue(),
                        smsCampaignData.getMessage(), smsCampaignData.getCampaignName());
                this.updateTriggerDates(smsCampaignData.getId());
            }
        }
    }
}

From source file:org.cowboyprogrammer.org.OrgTimestamp.java

License:Open Source License

/**
 * Returns null if no repeater is set. Otherwise the next repetition of this
 * time which is in the future. If it is already in the future, it will
 * return that./* w  ww. j a  va 2  s. co  m*/
 */
public LocalDateTime getNextFutureRepetition() {
    if (repeater == null) {
        return null;
    }
    final LocalDateTime now = LocalDateTime.now();
    if (now.isBefore(date)) {
        // Already in future
        return date;
    }
    // In this case, + and ++ have the same behaviour
    if (repeater.startsWith("+")) {
        LocalDateTime next = date.plus(repeatPeriod);
        // Just get it into the future
        while (now.isAfter(next)) {
            next = next.plus(repeatPeriod);
        }
        return next;
    } else {
        // Count from NOW
        return now.plus(repeatPeriod);
    }
}

From source file:org.openmastery.publisher.core.timeline.TimeBandModel.java

License:Open Source License

public boolean contains(LocalDateTime position) {
    return (position.isAfter(getStart()) && position.isBefore(getEnd())) || position.isEqual(getStart())
            || position.isEqual(getEnd());
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the app usage data for invoking APIs
 *
 * @param tableName name of the required table in the database
 * @param idList    Id list of applications
 * @return a collection containing the data related to App usage
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 *///  w ww. j  a v a2s . c om
private List<AppUsageDTO> getTopAppUsageData(String tableName, List<String> idList, String fromDate,
        String toDate, int limit) throws APIMgtUsageQueryServiceClientException {
    List<AppUsageDTO> topAppUsageDataList = new ArrayList<AppUsageDTO>();
    try {
        if (!idList.isEmpty()) {
            String startDate = fromDate + ":00";
            String endDate = toDate + ":00";
            String granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;//default granularity

            Map<String, Integer> durationBreakdown = this.getDurationBreakdown(startDate, endDate);
            LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
            DateTimeFormatter formatter = DateTimeFormat
                    .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
            LocalDateTime fromLocalDateTime = LocalDateTime.parse(startDate, formatter);//GMT time

            if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
                granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
            } else if ((durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0)
                    || (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0)) {
                granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
            }
            StringBuilder idListQuery = new StringBuilder();
            for (int i = 0; i < idList.size(); i++) {
                if (i > 0) {
                    idListQuery.append(" or ");
                }
                idListQuery.append(APIUsageStatisticsClientConstants.APPLICATION_ID + "==");
                idListQuery.append("'" + idList.get(i) + "'");
            }
            StringBuilder query = new StringBuilder("from " + tableName + " on " + idListQuery.toString()
                    + " within " + getTimestamp(startDate) + "L, " + getTimestamp(endDate) + "L per '"
                    + granularity + "' select " + APIUsageStatisticsClientConstants.APPLICATION_ID + ", "
                    + APIUsageStatisticsClientConstants.USERNAME + ", sum("
                    + APIUsageStatisticsClientConstants.TOTAL_REQUEST_COUNT
                    + ") as net_total_requests group by " + APIUsageStatisticsClientConstants.APPLICATION_ID
                    + ", " + APIUsageStatisticsClientConstants.USERNAME + " order by net_total_requests DESC");
            // limit enforced
            if (limit >= 0) {
                query.append(" limit" + limit);
            }
            query.append(";");
            JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                    APIUsageStatisticsClientConstants.APIM_ACCESS_SUMMARY_SIDDHI_APP, query.toString());
            String applicationId;
            String username;
            long requestCount;
            AppUsageDTO appUsageDTO;
            if (jsonObj != null) {
                JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
                for (Object record : jArray) {
                    JSONArray recordArray = (JSONArray) record;
                    if (recordArray.size() == 3) {
                        applicationId = (String) recordArray.get(0);
                        username = (String) recordArray.get(1);
                        requestCount = (Long) recordArray.get(2);
                        String appName = subscriberAppsMap.get(applicationId);
                        boolean found = false;
                        for (AppUsageDTO dto : topAppUsageDataList) {
                            if (dto.getAppName().equals(appName)) {
                                dto.addToUserCountArray(username, requestCount);
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            appUsageDTO = new AppUsageDTO();
                            appUsageDTO.setAppName(appName);
                            appUsageDTO.addToUserCountArray(username, requestCount);
                            topAppUsageDataList.add(appUsageDTO);
                        }
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying top app usage data from Stream Processor ", e);
    }
    return topAppUsageDataList;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the top user usage data for invoking APIs
 *
 * @param tableName name of the required table in the database
 * @param apiName   API name/*from  ww  w .  j av a  2 s.co m*/
 * @param version   version of the required API
 * @param fromDate  Start date of the time span
 * @param toDate    End date of time span
 * @return a collection containing the data related to Api usage
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 */
private List<ApiTopUsersDTO> getTopApiUsers(String tableName, String apiName, String tenantDomain,
        String version, String fromDate, String toDate) throws APIMgtUsageQueryServiceClientException {
    List<ApiTopUsersDTO> apiTopUsersDataList = new ArrayList<ApiTopUsersDTO>();
    try {
        StringBuilder topApiUserQuery;
        long totalRequestCount = getTotalRequestCountOfAPIVersion(tableName, apiName, tenantDomain, version,
                fromDate, toDate);

        String granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;//default granularity

        Map<String, Integer> durationBreakdown = this.getDurationBreakdown(fromDate, toDate);

        LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
        DateTimeFormatter formatter = DateTimeFormat
                .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
        LocalDateTime fromLocalDateTime = LocalDateTime.parse(fromDate, formatter);//GMT time

        if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
            granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
        } else if ((durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0)
                || (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0)) {
            granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
        }

        topApiUserQuery = new StringBuilder("from " + APIUsageStatisticsClientConstants.API_USER_PER_APP_AGG
                + " on(" + APIUsageStatisticsClientConstants.API_CREATOR_TENANT_DOMAIN + "=='" + tenantDomain
                + "' AND " + APIUsageStatisticsClientConstants.API_NAME + "=='" + apiName);

        if (!APIUsageStatisticsClientConstants.FOR_ALL_API_VERSIONS.equals(version)) {
            topApiUserQuery.append("' AND " + APIUsageStatisticsClientConstants.API_VERSION + "=='" + version);
        }
        topApiUserQuery.append("') within " + getTimestamp(fromDate) + "L, " + getTimestamp(toDate) + "L per '"
                + granularity + "' select " + APIUsageStatisticsClientConstants.USERNAME + ", "
                + APIUsageStatisticsClientConstants.API_CREATOR + ", sum("
                + APIUsageStatisticsClientConstants.TOTAL_REQUEST_COUNT + ") as net_total_requests group by "
                + APIUsageStatisticsClientConstants.USERNAME + ", "
                + APIUsageStatisticsClientConstants.API_CREATOR + " order by net_total_requests DESC;");

        JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                APIUsageStatisticsClientConstants.APIM_ACCESS_SUMMARY_SIDDHI_APP, topApiUserQuery.toString());

        String username;
        Long requestCount;
        if (jsonObj != null) {
            JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
            for (Object record : jArray) {
                JSONArray recordArray = (JSONArray) record;
                if (recordArray.size() == 3) {
                    String creator = (String) recordArray.get(1);
                    if (creator != null && MultitenantUtils.getTenantDomain(creator).equals(tenantDomain)) {
                        username = (String) recordArray.get(0);
                        requestCount = (Long) recordArray.get(2);
                        ApiTopUsersDTO apiTopUsersDTO = new ApiTopUsersDTO();
                        apiTopUsersDTO.setApiName(apiName);
                        apiTopUsersDTO.setFromDate(fromDate);
                        apiTopUsersDTO.setToDate(toDate);
                        apiTopUsersDTO.setVersion(version);
                        apiTopUsersDTO.setProvider(creator);

                        //remove @carbon.super from super tenant users
                        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
                                .equals(MultitenantUtils.getTenantDomain(username))) {
                            username = MultitenantUtils.getTenantAwareUsername(username);
                        }
                        apiTopUsersDTO.setUser(username);
                        apiTopUsersDTO.setRequestCount(requestCount);
                        apiTopUsersDTO.setTotalRequestCount(totalRequestCount);
                        apiTopUsersDataList.add(apiTopUsersDTO);
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying top api users data from Stream Processor ", e);
    }
    return apiTopUsersDataList;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the API faulty invocation data
 *
 * @param tableName name of the required table in the database
 * @param idList    Ids List of applications
 * @return a collection containing the data related to API faulty invocations
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 *//*from w  ww .  j a  va  2  s . c  om*/
private List<FaultCountDTO> getFaultAppUsageData(String tableName, List<String> idList, String fromDate,
        String toDate, int limit) throws APIMgtUsageQueryServiceClientException {
    List<FaultCountDTO> falseAppUsageDataList = new ArrayList<FaultCountDTO>();
    try {
        if (!idList.isEmpty()) {
            String startDate = fromDate + ":00";
            String endDate = toDate + ":00";
            String granularity = APIUsageStatisticsClientConstants.MINUTES_GRANULARITY;//default granularity
            Map<String, Integer> durationBreakdown = this.getDurationBreakdown(startDate, endDate);
            LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
            DateTimeFormatter formatter = DateTimeFormat
                    .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
            LocalDateTime fromLocalDateTime = LocalDateTime.parse(startDate, formatter);//GMT time

            if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
                granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
            } else if (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0
                    || durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_WEEKS) > 0) {
                granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
            } else if (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0) {
                granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;
            }

            StringBuilder idListQuery = new StringBuilder();
            for (int i = 0; i < idList.size(); i++) {
                if (i > 0) {
                    idListQuery.append(" or ");
                }
                idListQuery.append(APIUsageStatisticsClientConstants.APPLICATION_ID + "==");
                idListQuery.append("'" + idList.get(i) + "'");
            }
            String query = "from " + tableName + " on " + idListQuery.toString() + " within "
                    + getTimestamp(startDate) + "L, " + getTimestamp(endDate) + "L per '" + granularity
                    + "' select " + APIUsageStatisticsClientConstants.APPLICATION_ID + ", "
                    + APIUsageStatisticsClientConstants.API_NAME + ", "
                    + APIUsageStatisticsClientConstants.API_CREATOR + ", sum("
                    + APIUsageStatisticsClientConstants.TOTAL_FAULT_COUNT + ") as total_faults group by "
                    + APIUsageStatisticsClientConstants.APPLICATION_ID + ", "
                    + APIUsageStatisticsClientConstants.API_CREATOR + ", "
                    + APIUsageStatisticsClientConstants.API_NAME + ";";
            JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                    APIUsageStatisticsClientConstants.APIM_FAULT_SUMMARY_SIDDHI_APP, query);
            String applicationId;
            String apiName;
            String apiCreator;
            long faultCount;
            FaultCountDTO faultCountDTO;
            if (jsonObj != null) {
                JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
                for (Object record : jArray) {
                    JSONArray recordArray = (JSONArray) record;
                    if (recordArray.size() == 4) {
                        applicationId = (String) recordArray.get(0);
                        apiName = (String) recordArray.get(1);
                        apiCreator = (String) recordArray.get(2);
                        apiName = apiName + " (" + apiCreator + ")";
                        faultCount = (Long) recordArray.get(3);
                        String appName = subscriberAppsMap.get(applicationId);
                        boolean found = false;
                        for (FaultCountDTO dto : falseAppUsageDataList) {
                            if (dto.getAppName().equals(appName)) {
                                dto.addToApiFaultCountArray(apiName, faultCount);
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            faultCountDTO = new FaultCountDTO();
                            faultCountDTO.setAppName(appName);
                            faultCountDTO.addToApiFaultCountArray(apiName, faultCount);
                            falseAppUsageDataList.add(faultCountDTO);
                        }
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying API faulty invocation data from Stream Processor ", e);
    }
    return falseAppUsageDataList;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the API usage data per API call type
 *
 * @param tableName name of the required table in the database
 * @param idList    Ids List of applications
 * @return a collection containing the data related to API call types
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 *//*from   w w  w  . jav  a2  s .co m*/
private List<AppCallTypeDTO> getAPICallTypeUsageData(String tableName, List<String> idList, String fromDate,
        String toDate, int limit) throws APIMgtUsageQueryServiceClientException {
    List<AppCallTypeDTO> appApiCallTypeList = new ArrayList<AppCallTypeDTO>();
    try {
        if (!idList.isEmpty()) {
            String startDate = fromDate + ":00";
            String endDate = toDate + ":00";
            String granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;//default granularity

            Map<String, Integer> durationBreakdown = this.getDurationBreakdown(startDate, endDate);
            LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
            DateTimeFormatter formatter = DateTimeFormat
                    .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
            LocalDateTime fromLocalDateTime = LocalDateTime.parse(startDate, formatter);//GMT time

            if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
                granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
            } else if (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0) {
                granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
            } else if (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0) {
                granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
            }
            StringBuilder idListQuery = new StringBuilder();
            for (int i = 0; i < idList.size(); i++) {
                if (i > 0) {
                    idListQuery.append(" or ");
                }
                idListQuery.append(APIUsageStatisticsClientConstants.APPLICATION_ID + "==");
                idListQuery.append("'" + idList.get(i) + "'");
            }
            String query = "from " + tableName + " on " + idListQuery.toString() + " within "
                    + getTimestamp(startDate) + "L, " + getTimestamp(endDate) + "L per '" + granularity
                    + "' select " + APIUsageStatisticsClientConstants.API_NAME + ", "
                    + APIUsageStatisticsClientConstants.API_VERSION + ", "
                    + APIUsageStatisticsClientConstants.API_CREATOR + ", "
                    + APIUsageStatisticsClientConstants.API_METHOD + ", "
                    + APIUsageStatisticsClientConstants.APPLICATION_ID + ", "
                    + APIUsageStatisticsClientConstants.API_RESOURCE_TEMPLATE + ", " + "sum("
                    + APIUsageStatisticsClientConstants.TOTAL_REQUEST_COUNT
                    + ") as total_request_count group by " + APIUsageStatisticsClientConstants.APPLICATION_ID
                    + ", " + APIUsageStatisticsClientConstants.API_NAME + ", "
                    + APIUsageStatisticsClientConstants.API_VERSION + ", "
                    + APIUsageStatisticsClientConstants.API_CREATOR + ", "
                    + APIUsageStatisticsClientConstants.API_METHOD + ", "
                    + APIUsageStatisticsClientConstants.API_RESOURCE_TEMPLATE + ";";
            JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                    APIUsageStatisticsClientConstants.APIM_ACCESS_SUMMARY_SIDDHI_APP, query);
            String apiName;
            String apiVersion;
            String apiCreator;
            String callType;
            String applicationId;
            String apiResourceTemplate;
            AppCallTypeDTO appCallTypeDTO;
            if (jsonObj != null) {
                JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
                for (Object record : jArray) {
                    JSONArray recordArray = (JSONArray) record;
                    if (recordArray.size() == 7) {
                        apiName = (String) recordArray.get(0);
                        apiVersion = (String) recordArray.get(1);
                        apiCreator = (String) recordArray.get(2);
                        apiName = apiName + " (" + apiCreator + ")";
                        callType = (String) recordArray.get(3);
                        applicationId = (String) recordArray.get(4);
                        apiResourceTemplate = (String) recordArray.get(5);
                        List<String> callTypeList = new ArrayList<String>();
                        callTypeList.add(apiResourceTemplate + " (" + callType + ")");
                        List<Integer> hitCountList = new ArrayList<Integer>();
                        long hitCount = (Long) recordArray.get(6);
                        hitCountList.add((int) hitCount);
                        String appName = subscriberAppsMap.get(applicationId);
                        boolean found = false;
                        for (AppCallTypeDTO dto : appApiCallTypeList) {
                            if (dto.getAppName().equals(appName)) {
                                dto.addToApiCallTypeArray(apiName, apiVersion, callTypeList, hitCountList);
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            appCallTypeDTO = new AppCallTypeDTO();
                            appCallTypeDTO.setAppName(appName);
                            appCallTypeDTO.addToApiCallTypeArray(apiName, apiVersion, callTypeList,
                                    hitCountList);
                            appApiCallTypeList.add(appCallTypeDTO);
                        }
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying API call type data from Stream Processor ", e);
    }
    return appApiCallTypeList;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the API usage data per application
 *
 * @param tableName name of the required table in the database
 * @param idList    Ids list of applications
 * @return a collection containing the data related to per App API usage
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 *//* w w w .  j av a 2 s .co m*/
private List<PerAppApiCountDTO> getPerAppAPIUsageData(String tableName, List<String> idList, String fromDate,
        String toDate, int limit) throws APIMgtUsageQueryServiceClientException {
    List<PerAppApiCountDTO> perAppUsageDataList = new ArrayList<PerAppApiCountDTO>();
    try {
        if (!idList.isEmpty()) {
            String startDate = fromDate + ":00";
            String endDate = toDate + ":00";
            String granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;//default granularity
            Map<String, Integer> durationBreakdown = this.getDurationBreakdown(startDate, endDate);
            LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
            DateTimeFormatter formatter = DateTimeFormat
                    .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
            LocalDateTime fromLocalDateTime = LocalDateTime.parse(startDate, formatter);//GMT time

            if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
                granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
            } else if (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0) {
                granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
            } else if (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0) {
                granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
            }
            StringBuilder idListQuery = new StringBuilder();
            for (int i = 0; i < idList.size(); i++) {
                if (i > 0) {
                    idListQuery.append(" or ");
                }
                idListQuery.append(APIUsageStatisticsClientConstants.APPLICATION_ID + "==");
                idListQuery.append("'" + idList.get(i) + "'");
            }
            String query = "from " + tableName + " on " + idListQuery.toString() + " within "
                    + getTimestamp(startDate) + "L, " + getTimestamp(endDate) + "L per '" + granularity
                    + "' select " + APIUsageStatisticsClientConstants.API_NAME + ", "
                    + APIUsageStatisticsClientConstants.API_CREATOR + ", "
                    + APIUsageStatisticsClientConstants.APPLICATION_ID + ", sum("
                    + APIUsageStatisticsClientConstants.TOTAL_REQUEST_COUNT + ") as total_calls group by "
                    + APIUsageStatisticsClientConstants.API_NAME + ", "
                    + APIUsageStatisticsClientConstants.API_CREATOR + ", "
                    + APIUsageStatisticsClientConstants.APPLICATION_ID + ";";
            JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                    APIUsageStatisticsClientConstants.APIM_ACCESS_SUMMARY_SIDDHI_APP, query);
            String apiName;
            String apiCreator;
            String applicationId;
            long requestCount;
            PerAppApiCountDTO apiUsageDTO;
            if (jsonObj != null) {
                JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
                for (Object record : jArray) {
                    JSONArray recordArray = (JSONArray) record;
                    if (recordArray.size() == 4) {
                        apiName = (String) recordArray.get(0);
                        apiCreator = (String) recordArray.get(1);
                        apiName = apiName + " (" + apiCreator + ")";
                        applicationId = (String) recordArray.get(2);
                        requestCount = (Long) recordArray.get(3);
                        String appName = subscriberAppsMap.get(applicationId);
                        boolean found = false;
                        for (PerAppApiCountDTO dto : perAppUsageDataList) {
                            if (dto.getAppName().equals(appName)) {
                                dto.addToApiCountArray(apiName, requestCount);
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            apiUsageDTO = new PerAppApiCountDTO();
                            apiUsageDTO.setAppName(appName);
                            apiUsageDTO.addToApiCountArray(apiName, requestCount);
                            perAppUsageDataList.add(apiUsageDTO);
                        }
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying per App usage data from Stream Processor", e);
    }
    return perAppUsageDataList;
}

From source file:org.wso2.carbon.apimgt.usage.client.impl.APIUsageStatisticsRestClientImpl.java

License:Open Source License

/**
 * This method gets the usage data for a given API across all versions
 *
 * @param tableName name of the table in the database
 * @param tenantDomain Tenant Domain//ww  w.ja v  a 2s.  co m
 * @param fromDate From date
 * @param toDate To date
 * @return a collection containing the API usage data
 * @throws APIMgtUsageQueryServiceClientException if an error occurs while querying the database
 */
private Collection<APIUsage> getAPIUsageData(String tableName, String tenantDomain, String fromDate,
        String toDate) throws APIMgtUsageQueryServiceClientException {

    Collection<APIUsage> usageDataList = new ArrayList<APIUsage>();
    try {
        String granularity = APIUsageStatisticsClientConstants.HOURS_GRANULARITY;//default granularity

        Map<String, Integer> durationBreakdown = this.getDurationBreakdown(fromDate, toDate);
        LocalDateTime currentDate = LocalDateTime.now(DateTimeZone.UTC);
        DateTimeFormatter formatter = DateTimeFormat
                .forPattern(APIUsageStatisticsClientConstants.TIMESTAMP_PATTERN);
        LocalDateTime fromLocalDateTime = LocalDateTime.parse(fromDate, formatter);//GMT time

        if (fromLocalDateTime.isBefore(currentDate.minusYears(1))) {
            granularity = APIUsageStatisticsClientConstants.MONTHS_GRANULARITY;
        } else if ((durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_MONTHS) > 0)
                || (durationBreakdown.get(APIUsageStatisticsClientConstants.DURATION_DAYS) > 0)) {
            granularity = APIUsageStatisticsClientConstants.DAYS_GRANULARITY;
        }
        String query = "from " + tableName + " on("
                + APIUsageStatisticsClientConstants.API_CREATOR_TENANT_DOMAIN + "=='" + tenantDomain
                + "') within " + getTimestamp(fromDate) + "L, " + getTimestamp(toDate) + "L per '" + granularity
                + "' select " + APIUsageStatisticsClientConstants.API_NAME + ", "
                + APIUsageStatisticsClientConstants.API_CONTEXT + ", "
                + APIUsageStatisticsClientConstants.API_VERSION + ", sum("
                + APIUsageStatisticsClientConstants.TOTAL_REQUEST_COUNT + ") as aggregateSum group by "
                + APIUsageStatisticsClientConstants.API_NAME + ", "
                + APIUsageStatisticsClientConstants.API_CONTEXT + ", "
                + APIUsageStatisticsClientConstants.API_VERSION + ";";
        JSONObject jsonObj = APIUtil.executeQueryOnStreamProcessor(
                APIUsageStatisticsClientConstants.APIM_ACCESS_SUMMARY_SIDDHI_APP, query);

        String apiName;
        String apiContext;
        String apiVersion;
        Long requestCount;
        if (jsonObj != null) {
            JSONArray jArray = (JSONArray) jsonObj.get(APIUsageStatisticsClientConstants.RECORDS_DELIMITER);
            for (Object record : jArray) {
                JSONArray recordArray = (JSONArray) record;
                if (recordArray.size() == 4) {
                    apiName = (String) recordArray.get(0);
                    apiContext = (String) recordArray.get(1);
                    apiVersion = (String) recordArray.get(2);
                    requestCount = (Long) recordArray.get(3);
                    usageDataList.add(new APIUsage(apiName, apiContext, apiVersion, requestCount));
                }
            }
        }
    } catch (APIManagementException e) {
        handleException("Error occurred while querying API usage data from Stream Processor ", e);
    }
    return usageDataList;
}