Develop > Service Health > Service Health Rules API > Examples - API Sample Rule > Example - Average Performance Rule Using a Rule Parameter Filter

Example - Average Performance Rule Using a Rule Parameter Filter

The following rule calculates average performance in seconds, based on the dResponseTime and u_iStatus sample fields.

Only samples with a u_iStatus value of 0 (available samples) are used in the calculation.

The rule uses an optional rule parameter: Response time limit. If this rule parameter value has been set in the Service Health Admin, samples with a dResponseTime value greater then the rule parameter value are not used in the calculation.

Note A rule parameter with the same name must be set for the rule in the Rule Repository. For details, see Business Rules.

The rule logic is: sum(dResponseTime) / available samples.

/ This rule use the u_iStatus and dResponseTime sample fields.
def sampleFields = ["u_iStatus", "dResponseTime"];
public void calculateKPI(CI ci, KPI kpi, List<Sample> samples) {
    // Create a variable to count available samples.
    def availableSamples = 0;
    // Create a variable to sum response times of available samples.
    def totalResponseTime = 0;
    /**
     * Get the value of the rule parameter named "Response time limit"
     * from the KPI, as defined for the KPI in Service Health Admin.
     * This rule parameter is optional, so responseTimeLimit can be null.
     */
    Long responseTimeLimit = kpi.getRuleParameter("Response time limit")
    /**
     * Go over the given samples. If a sample's u_iStatus is equal to 0,
     * the sample is considered available.
     */
    samples.each {Sample currentSample ->
        if (currentSample.u_iStatus == 0) {
            /**
            * Check the value of the rule parameter.
            * If it is not null (meaning the user has set a value),
            * and the sample's dResponseTime is greater than the
            * rule parameter value, the value is not valid.
            */
            boolean isSampleValid = true;
            if (responseTimeLimit != null) {
                // Check if ResponseTime exceeds the rule parameter value.
                if (currentSample.dResponseTime > responseTimeLimit) {
                    // The sample is not valid.
                    isSampleValid = false;
                }
            }
            if (isSampleValid) {
                // Increase the count of available samples.
                availableSamples++;
                // Add the sample's dResponseTime value to totalResponseTime.
                totalResponseTime += currentSample.dResponseTime
            }
        }
    }
    if (availableSamples > 0) {
        // Set KPI value, converted to percentage.
        kpi.setValue((totalResponseTime / availableSamples))
    }
}


Parent topic: Examples - API Sample Rule