Samples > Starter stores > Starter store enhancements > IBM Gift Center for the Madisons starter store > Work with the sample store pages > Create a custom business validation rule


IBM Gift Center for Madisons: Creating a new validator class for the business validation rule

Create a Java class containing the logic to interpret the business validation rule and report an error when customers break the rule on the storefront. This class can either implement the GiftListRulesValidator interface or extend from the AbstractGiftListRulesValidator class.


Before you begin

Review the following existing Gift Center classes:


Procedure

  1. Open WebSphere Commerce Developer and switch to the Enterprise Explorer view.

  2. Create a package for the new validator class:

    1. Navigate to WebSphereCommerceServerExtensionsLogic > src.

    2. Right-click the src folder; then click New > Package.

    3. In the Name field, type:

      com.your_company_name.commerce.giftcenter.rules.validation

    4. Click Finish.

  3. In the new package, create a validator class that either implements the GiftListRulesValidator interface or extends from the AbstractGiftListRulesValidator class. Give the class a name that uses this syntax: Extrule_descriptionRuleValidator; for example, ExtExceedMaxRegistriesPerEventRuleValidator.

    To add logic to validate the rule, the new class must override one of the following methods:

    Method to override Applies to
    validateOnCreate(Object, Object, Integer) method Rules that validate on a Create action, that is, when a customer is creating a gift registry.
    validateOnUpdate(Object, Object, Integer) method Rules that validate on an Update action, that is, when a customer is updating a gift registry.
    validateOnDelete(Object, Object, Integer) method Rules that validate on a Delete action, that is, when a customer is deleting a gift registry.

    If your rule validates on an Update or Delete action, invoke the rule validator implementation explicitly in the change mediators where to perform the check for the rule validation. You can use the ValidateGiftListRulesHelper class to explicitly invoke validate methods for create, update and delete actions.

    For example, the sample code to invoke the rule validations for an Update action looks like:

    int rule = 7001; 
    ValidateGiftListRulesHelper helper = new ValidateGiftListRulesHelper(); 
    boolean valid = helper.validateARule(noun, nounPart, rule, GiftListServerConstants.UPDATE_EVENT); 
    // Process the error rule to report an error 
    if(!valid){ 
    String errorKey = GiftCenterComponentHelper.buildErrorKeyForRuleValidationError(GiftCenterApplicationMessageKeys._ERR_RULE_EVALUATION_FAILED, noun, rule); 
    ApplicationError error = new ApplicationError(ApplicationError.TYPE_GENERIC_ERROR, errorKey, new Object[]{rule, noun}, Logger.getResourceBundleName()); 
    } 
    // Throw this error when the rule fails. 
    

    For more information about change mediators and invoking the rule validators, see the validateChange method for the AbstractChangeGiftListPartMediator class.

  4. Optional: Your Java class might need to retrieve data from the database and compare the data to the value configured for the rule. If so, you can create a direct SQL statement and store the statement in a custom query template file. You can then use the executeSelectStatement method provided by the GiftCenterComponentHelper class to execute the statement in the Java class. The example at the end of this procedure provides a sample direct SQL statement and shows how the statement is used in the Java class. For general instructions on creating a custom query template file containing a direct SQL statement, see Create direct SQL statements.


Example

The following is an example custom validator class for the following business validation rule: "The number of registries allowed per registrant for each event type should not exceed a preconfigured maximum number." This class extends the AbstractGiftListRulesValidator class. The validation logic in this class checks the database using a direct SQL statement to determine whether the current customer has already created a gift registry with the same event type.

package com.mycompany.commerce.giftcenter.rules.validation; 
import
<dependency classes> 
/**
 * The
<code>ExtExceedMaxRegistriesPerEventRuleValidator</code> class validates whether the
 * number of registries allowed per registrant for each event type has exceeded a preconfigured 
 * maximum number.
 * 
 */
public class ExtExceedMaxRegistriesPerEventRuleValidator extends AbstractGiftListRulesValidator {

    /**
     * Constant to pass the configured value to the SQL from the gift list rule registry.
     */
    public static final String MAX_REGISTERIES_PER_EVENTS = "maxCount";     
    /**
     * Constant to pass the configured value to the SQL from the gift list rule registry.
     */
    public static final String EVENT_TYPE = "eventType";     
    /**
     * The constant that refers to the query template that selects the active gift
     * lists for the registrant users.
     */
    public static final String GC_SELECT_ACTIVE_PER_EVENT_GIFTLIST_FOR_REGISTRANTS = "IBM_Select_Active_Per_Event_GiftList_For_Registrants";     
    /**
     * Validates the rule when the gift list object is being created.
     * 
     * @param noun
     *            The
<code>GiftList</code> noun that needs to be validated.
     * @param nounPart
     *            The
<code>GiftList</code> noun part to use to validate the
     *            part data against a rule, rather than using the whole GiftList
     *            noun.
     * @param rule
     *            The rule name.
     * @return A boolean value to indicate whether the noun or the noun part
     *         satisfies the business rule.
     * @throws GiftListRuleValidationException
     */
    public boolean validateOnCreate(Object noun, Object nounPart, Integer rule)    throws GiftListRuleValidationException {
        
        boolean valid = true;         GiftListType giftList = null;         if (noun != null && noun instanceof GiftListType) {
            giftList = (GiftListType) noun;             try {
                BaseContext baseContext = getBaseContext();                 Long userId = getUserId(baseContext);                 GiftListRulesRegistry registry = GiftListRulesRegistry.singleton();                 if (registry != null) {
                    String eventType = getEventType(giftList);                     String ruleValue = registry.getRuleValue(baseContext.getStoreId(), eventType, rule);                     if (ruleValue == null) {
                        ruleValue = registry.getRuleValue(baseContext.getStoreId(), GiftListRuleConstants.DEFAULT_EVENT_TYPE_NAME, rule);                     }
                    if (ruleValue != null) {
                        int maxRegisteriesPerEvents = Integer.parseInt(ruleValue);                         Map params = new HashMap();                         
                        List paramValulesEvent = new ArrayList();                         paramValulesEvent.add(eventType);                         params.put(EVENT_TYPE, paramValulesEvent);                         
                        List paramValulesUser = new ArrayList();                         paramValulesUser.add(userId.toString());                         params.put(GiftListServerConstants.USERID_PARAM, paramValulesUser);                         
                        List paramValulesMax = new ArrayList();                         paramValulesMax.add(maxRegisteriesPerEvents);                         params.put(MAX_REGISTERIES_PER_EVENTS, paramValulesMax);                         
                        List resultSet = GiftCenterComponentHelper.executeSelectStatement(GC_SELECT_ACTIVE_PER_EVENT_GIFTLIST_FOR_REGISTRANTS, params);                         if (resultSet != null && resultSet.size() > 0) {
                                valid = false;                         }
                    } 
                } 
        } 
        return valid;     }

Near the end of the previous Java class example, the GC_SELECT_ACTIVE_PER_EVENT_GIFTLIST_FOR_REGISTRANTS SQL statement is defined in a custom query template file. The SQL statement checks the database for the existing number of gift registries for a particular customer for a specific event type. The SQL statement then compares this number with the number configured in the rule. If the SQL statement returns an empty row in the result set, this means the number in the database is lower than the number configured in the rule. As a result, the customer can create the gift registry. The sample SQL statement defined in the custom query template file looks like this:

BEGIN_SQL_STATEMENT
  base_table=GRGFTREG
  name=IBM_Select_Active_Per_Event_GiftList_For_Registrants
  sql=
          SELECT 
              GRGFTREG.EVENTTYPE_ID  
          FROM 
              GRGFTREG, GRRGSTRNT, GREVNTTYPE 
          WHERE 
              GRGFTREG.GIFTREGISTRY_ID = GRRGSTRNT.GIFTREGISTRY_ID AND 
              GRRGSTRNT.RGSTRNTTYPE = 0 AND 
              GRGFTREG.STATUS = 1 AND 
              GRGFTREG.EVENTTYPE_ID = GREVNTTYPE.EVENTTYPE_ID AND 
              GREVNTTYPE.EVENTTYPENAME = ?eventType? AND  
              GRRGSTRNT.USERID = ?userId?
          GROUP BY 
              EVENTTYPE_ID
          HAVING 
              COUNT(*) >= ?maxCount?
END_SQL_STATEMENT


Previous topic: IBM Gift Center for Madisons: Adding the new business validation rule to the GRREGRULE table


Next topic: IBM Gift Center for Madisons: Registering the new business validation rule


+

Search Tips   |   Advanced Search