Invoke a method in a Java Class

From AgileApps Support Wiki
Revision as of 23:01, 5 August 2013 by imported>Aeric (→‎Example: Validate Incoming Data)

Invoke a Java Method

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 data validation that is part of every Custom Object, you can use Java methods to do even more sophisticated validation.

In this example, the method ensures that the credit number is in the proper format -- exactly 16 digits, with no characters or spaces. The validation method is designed for the Orders object in the Sample Order Processing System, which has field named credit_card_number. Such a method could be invoked in a Rule Action that is triggered when a new record is created.

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. The solution is to use a text field, 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.

String ccn_field = "credit_card_number";

public void validate_order(Parameters requestParams)
throws Exception
{
   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;
}