Invoke a Java Method From a Data Policy

From LongJump Support Wiki
Revision as of 22:00, 4 June 2013 by imported>Aeric (→‎Method Signature)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Invoke a Java Method From a Data Policy

Invoking a Java method, lets you use the Java APIs to interact with the platform, and do anything else that you can accomplish using Java code.

Method Signature

You can select any method defined in a Java class, as long as it has the required signature:

public void someMethod(com.platform.api.Parameters requestParams);
Considerations
  • The method can be either a static class method or an instance method. An instance of the object is created before making the call.
  • The method must be public, return void, and take a single Parameters argument.

Example: Validate Incoming Data

In addition to the rudimentary data validation that is part of every Custom Object, Data Policies give you the capacity for more sophisticated validation.

In this example, the data policy action ensures that the credit number is in the proper format to begin with. (Exactly 16 digits, with no characters or spaces.) The policy action is designed for the Orders object in the Sample Order Processing System, which has field named credit_card_number.

This is an important technique for more sophisticated validations. In this case, for example, a credit card number is too big to use a numeric field, while normal validation mechanisms are limited to simple field comparisons. The solution is to use a data policy to parse the data, and throw an exception in the event of an error.

This code throws an exception if the format isn't valid. The exception will abort the transaction before it is committed. If it were activated in after the triggering event ("post-trigger") then the transaction would have to be rolled back. So it is better practice to configure the data policy so it is activated before the triggering event is carried out.

    
    public void validate_order(Parameters requestParams)
    throws Exception
    {
      // Functions.debug("Validating order");
       String errMsg = "Invalid credit card number format. Needs 16 digits.";
       String ccn = (String) requestParams.get(ccn_field);
       if ((null != ccn) && (ccn.length() != 16)) {
           throw new Exception(errMsg);
       }
       for (int i=0; i<=15; i++) {
           char c = ccn.charAt(i);
           if (c < '0' || c > '9') {
               throw new Exception(errMsg);
           }
       }
       // Format validated
       return;
    }

Additional Examples

For many more examples of data policies that execute java code, see Java Code Data Policy Examples.