Validating and Using the Model Data

Exclusive offer: get 50% off this eBook here
Oracle ADF 11gR2 Development Beginner's Guide

Oracle ADF 11gR2 Development Beginner's Guide — Save 50%

Experience the easiest way to learn, understand, and implement rich Internet applications using Oracle ADF 11gR2 with this book and ebook

$29.99    $15.00
by Vinod Krishnan | May 2013 | Beginner's Guides Enterprise Articles Oracle

In this article by Vinod Krishnan, author of Oracle ADF 11gR2 Development Beginner's Guide, we will take a look at validating and using the model data. Validating data is important as business depends on the data that gets stored in the database. So how do we validate the data? Validation is something that makes sure that valid data is getting stored in the database. Validation could be anything from comparing two fields in a table to multiple validations on a single field involving different columns from a different table.

In any other framework, we would end up writing a lot of code even for a small validation. But in ADF, we do little or no coding at all, and most of the validations are achieved declaratively.

In this article, we will learn the following topics:

  • Declarative validation
  • Groovy expressions

(For more resources related to this topic, see here.)

Declarative validation

It's easy to set up declarative validation for an entity object to validate the data that is passed through the metadata file. Declarative validation is the validation added for an attribute or an entity object to fulfill a particular business validation. It is called declarative validation because we don't write any code to achieve the validation as all the business validations are achieved declaratively. The entity object holds the business rules that are defined to fulfill specific business needs such as a range check for an attribute value or to check if the attribute value provided by the user is a valid value from the list defined. The rules are incorporated to maintain a standard way to validate the data.

Knowing the lifecycle of an entity object

It is important to know the lifecycle of an entity object before knowing the validation that is applied to an entity object. The following diagram depicts the lifecycle of an entity:

When a new row is created using an entity object, the status of the entity is set to NEW. When an entity is initialized with some values, the status is changed from NEW to INITIALIZED. At this time, the entity is marked invalid or dirty; this means that the state of the entity is changed from the value that was previously checked with the database value.

The status of an entity is changed to UNMODIFIED, and the entity is marked valid after applying validation rules and committing to the database. When the value of an unmodified entity is changed, the status is changed to MODIFIED and the entity is marked dirty again. The modified entity again goes to an UNMODIFIED state when it is saved to the database. When an entity is removed from the database, the status is changed to DELETED. When the value is committed, the status changes to DEAD.

Types of validation

Validation rules are applied to an entity to make sure that only valid values are committed to the database and to prevent any invalid data from getting saved to the database. In ADF, we use validation rules for the entity object to make sure the row is valid all the time.

There are three types of validation rules that can be set for the entity objects; they are as follows:

  • Entity-level validation
  • Attribute-level validation
  • Transaction-level validation

Entity-level validation

As we know, an entity represents a row in the database table. Entity-level validation is the business rule that is added to the database row. For example, the validation rule that has to be applied to a row is termed as entity-level validation.

There are two unique declarative validators that will be available only for entity-level validation—Collection and UniqueKey. The following diagram explains that entity-level validations are applied on a single row in the EMP table. The validated row is highlighted in bold.

Attribute-level validation

Attribute-level validations are applied to attributes. Business logic mostly involves specific validations to compare different attribute values or to restrict the attributes to a specific range. These kinds of validations are done in attribute-level validation. Some of the declarative validators available in ADF are Compare, Length, and Range.

The Precision and Mandatory attribute validations are added, by default, to the attributes from the column definition in the underlying database table. We can only set the display message for the validation.

The following diagram explains that the validation is happening on the attributes in the second row:

There can be any number of validations defined on a single attribute or on multiple attributes in an entity. In the diagram, Empno has a validation that is different from the validation defined for Ename. Validation for the Job attribute is different from that for the Sal attribute. Similarly, we can define validations for attributes in the entity object.

Transaction-level validation

Transaction-level validations are done after all entity-level validations are completed. If you want to add any kind of validation at the end of the process, you can defer the validation to the transaction level to ensure that the validation is performed only once.

Built-in declarative validators

ADF Business Components includes some built-in validators to support and apply validations for entity objects. The following screenshot explains how a declarative validation will show up in the Overview tab:

The Business Rules section for the EmpEO.xml file will list all the validations for the EmpEO entity. In the previous screenshot, we will see that the there are no entity-level validators defined and some of the attribute-level validations are listed in the Attributes folder.

Collection validator

A Collection validator is available only for entity-level validation. To perform operations such as average, min, max, count, and sum for the collection of rows, we use the collection validator.

Collection validators are compared to the GROUP BY operation in an SQL query with a validation. The aggregate functions, such as count, sum, min, and max are added to validate the entity row. The validator is operated against the literal value, expression, query result, and so on. You must have the association accessor to add a collection validation.

Time for action – adding a collection validator for the DeptEO file

Now, we will add a Collection validator to DeptEO.xml for adding a count validation rule. Imagine a business rule that says that the number of employees added to department number 10 should be more than five. In this case, you will have a count operation for the employees added to department number 10 and show a message if the count is less than 5 for a particular department.

We will break this action into the following three parts:

  • Adding a declarative validation: In this case, the number of employees added to the department should be greater than five
  • Specifying the execution rule: In our case, the execution of this validation should be fired only for department number 10
  • Displaying the error message: We have to show an error message to the user stating that the number of employees added to the department is less than five

Adding the validation

Following are the steps to add the validation:

  1. Go to the Business Rules section of DeptEO.xml. You will find the Business Rules section in the Overview tab.

  2. Select Entity Validators and click on the + button. You may right-click on the Entity Validators folder and then select New Validator to add a validator.

  3. Select Collection as Rule Type and move on to the Rule Definition tab.

  4. In this section, select Count for the Operation field; Accessor is the association accessor that gets added through a composition association relationship. Only the composition association accessor will be listed in the Accessor drop-down menu. Select the accessor for EmpEO listed in the dropdown, with Empno as the value for Attribute.

    In order to create a composition association accessor, you will have to create an association between DeptEO.xml and EmpEO.xml based on the Deptno attribute with cardinality of 1 to *. The Composition Association option has to be selected to enable a composition relationship between the two entities.

  5. The value of the Operator option should be selected as Greater Than. Compare with will be a literal value, which is 5 that can be entered in the Enter Literal Value section below.

Specifying the execution rule

Following are the steps to specify the execution:

  1. Now to set the execution rule, we will move to the Validation Execution tab.

  2. In the Conditional Execution section, add Deptno = '10' as the value for Conditional Execution Expression.

  3. In the Triggering Attribute section, select the Execute only if one of the Selected Attributes has been changed checkbox.

  4. Move the Empno attribute to the Selected Attributes list. This will make sure that the validation is fired only if the Empno attribute is changed:

Displaying the error message

Following are the steps to display the error message:

  1. Go to the Failure Handling section and select the Error option for Validation Failure Severity.

  2. In the Failure Message section, enter the following text:

    Please enter more than 5 Employees

  3. You can add the message stored in a resource bundle to Failure Message by clicking on the magnifying glass icon.

What just happened?

We have added a collection validation for our EmpEO.xml object. Every time a new employee is added to the department, the validation rule fires as we have selected Empno as our triggering attribute. The rule is also validated against the condition that we have provided to check if the department number is 10. If the department number is 10, the count for that department is calculated. When the user is ready to commit the data to the database, the rule is validated to check if the count is greater than 5. If the number of employees added is less than 5, the error message is displayed to the user.

When we add a collection validator, the EmpEO.xml file gets updated with appropriate entries. The following entries get added for the aforementioned validation in the EmpEO.xml file:

<validation:CollectionValidationBean Name="EmpEO_Rule_0" ResId= "com.empdirectory.model.entity.EmpEO_Rule_0" OnAttribute="Empno" OperandType="LITERAL" Inverse="false" CompareType="GREATERTHAN" CompareValue="5" Operation="count"> <validation:OnCondition> <![CDATA[Deptno = '10']]> </validation:OnCondition> </validation:CollectionValidationBean> <ResourceBundle> <PropertiesBundle PropertiesFile= "com.empdirectory.model.ModelBundle"/> </ResourceBundle>

The error message that is added in the Failure Handling section is automatically added to the resource bundle.

The Compare validator

The Compare validator is used to compare the current attribute value with other values. The attribute value can be compared against the literal value, query result, expression, view object attribute, and so on. The operators supported are equal, not-equal, less-than, greater-than, less-than or equal to, and greater-than or equal to.

The Key Exists validator

This validator is used to check if the key value exists for an entity object. The key value can be a primary key, foreign key, or an alternate key. The Key Exists validator is used to find the key from the entity cache, and if the key is not found, the value is determined from the database. Because of this reason, the Key Exists validator is considered to give better performance. For example, when an employee is assigned to a department deptNo 50 and you want to make sure that deptNo 50 already exists in the DEPT table.

The Length validator

This validator is used to check the string length of an attribute value. The comparison is based on the character or byte length.

The List validator

This validator is used to create a validation for the attribute in a list. The operators included in this validation are In and NotIn. These two operators help the validation rule check if an attribute value is in a list.

The Method validator

Sometimes, we would like to add our own validation with some extra logic coded in our Java class file. For this purpose, ADF provides a declarative validator to map the validation rule against a method in the entity-implementation class. The implementation class is generated in the Java section of the entity object. We need to create and select a method to handle method validation. The method is named as validateXXX(), and the returned value will be of the Boolean type.

The Range validator

This validator is used to add a rule to validate a range for the attribute value. The operators included are Between and NotBetween. The range will have a minimum and maximum value that can be entered for the attribute.

The Regular Expression validator

For example, let us consider that we have a validation rule to check if the e-mail ID provided by the user is in the correct format. For the e-mail validation, we have some common rules such as the following:

  • The e-mail ID should start with a string and end with the @ character
  • The e-mail ID's last character cannot be the dot (.) character
  • Two @ characters are not allowed within an e-mail ID

For this purpose, ADF provides a declarative Regular Expression validator. We can use the regex pattern to check the value of the attribute. The e-mail address and the US phone number pattern is provided by default:

  • Email: [A-Z0-9._%+-]+@[A-Z0-,9.-]+\.[A-Z]{2,4}
  • Phone Number (US): [0-9]{3}-?[0-9]{3}-?[0-9]{4}

You should select the required pattern and then click on the Use Pattern button to use it. Matches and NotMatches are the two operators that are included with this validator.

The Script validator

If we want to include an expression and validate the business rule, the Script validator is the best choice. ADF supports Groovy expressions to provide Script validation for an attribute.

The UniqueKey validator

This validator is available for use only for entity-level validation. To check for uniqueness in the record, we would be using this validator. If we have a primary key defined for the entity object, the Uniqueness Check Definition section will list the primary keys defined to check for uniqueness, as shown in the following screenshot:

If we have to perform a uniqueness check against any attribute other than the primary key attributes, we will have to create an alternate key for the entity object.

Time for action – creating an alternate key for DeptEO

Currently, the DeptEO.xml file has Deptno as the primary key. We would add business validation that states that there should not be a way to create a duplicate of the department name that is already available. The following steps show how to create an alternate key:

  1. Go to the General section of the DeptEO.xml file and expand the Alternate Keys section. Alternate keys are keys that are not part of the primary key.
  2. Click on the little + icon to add a new alternate key.
  3. Move the Dname attribute from the Available list to the Selected list and click on the OK button.

What just happened?

We have created an alternate key against the Dname attribute to prepare for a unique check validation for the department name. When the alternate key is added to an entity object, we will see the AltKey attribute listed in the Alternate Key section of the General tab.

In the DeptEO.xml file, you will find the following code that gets added for the alternate key definition:

<Key Name="AltKey" AltKey="true"> <DesignTime> <Attr Name="_isUnique" Value="true"/> <Attr Name="_DBObjectName" Value="HR.DEPT"/> </DesignTime> <AttrArray Name="Attributes"> <Item Value= "com.empdirectory.model.entity.DeptEO.Dname"/> </AttrArray> </Key>

Have a go hero – compare the attributes

For the first time, we have learned about the validations in ADF. So it's time for you to create your own validation for the EmpEO and DeptEO entity objects. Add validations for the following business scenarios:

  1. Continue with the creation of the uniqueness check for the department name in the DeptEO.xml file.

  2. The salary of the employees should not be greater than 1000. Display the following message if otherwise:

    Please enter Salary less than 1000.

  3. Display the message invalid date if the employee's hire date is after 10-10-2001.

  4. The length of the characters entered for Dname of DeptEO.xml should not be greater than 10.

  5. The location of a department can only be NEWYORK, CALIFORNIA, or CHICAGO.

  6. The department name should always be entered in uppercase. If the user enters a value in lowercase, display a message.

  7. The salary of an employee with the MANAGER job role should be between 800 and 1000. Display an error message if the value is not in this range.

  8. The employee name should always start with an uppercase letter and should end with any character other than special characters such as :, ;, and _.

  9. After creating all the validations, check the code and tags generated in the entity's XML file for each of the aforementioned validations.

Oracle ADF 11gR2 Development Beginner's Guide Experience the easiest way to learn, understand, and implement rich Internet applications using Oracle ADF 11gR2 with this book and ebook
Published: April 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

Groovy expression

ADF Business Components utilize Groovy expressions to support scripting. Groovy is an open source, Java-like scripting language that can be stored in an XML definition file. For instance, the attribute name for the employee name Ename can directly be used in a Groovy expression to represent the value of the Ename attribute.

Groovy follows the same JavaBeans way of accessing the methods of an entity object that is defined in the Java class. Following are some of the ways to call the method of entity objects in a Groovy expression:

Java method

Groovy expression

isEmployee()

employee

getEmployee()

employee

getEmpNo(int n)

source.emp(5)

checkEmployeeName()

source.checkEmployeeName()

checkEmployeeNo(int n)

source.checkEmployeeNo(5)

Setting a default value

We can set a default value for an attribute in the entity or view object by using the Groovy expression. The Default Value section for the attribute is provided with three options—Literal, Expression, and SQL. For the Literal value, we can provide a literal value. The Expression option is used to provide a value that is evaluated at runtime and to dynamically assign a default value to the attribute.

Time for action – setting a default salary for employees

For example, consider a case wherein we want to set a default value for the salary attribute in the EmpEO.xml file based on the Deptno attribute. In this case, we have to provide an expression that will be evaluated at runtime to provide the default value. The following steps show us how to do this:

  1. Click on the Sal attribute from the list of attributes displayed in the Attributes section of EmpEO.xml.

  2. In the Default Value section, select the Expression option. Now the pencil icon will be enabled for the textbox below the Expression option.

  3. Click on the pencil icon to open an Edit Expression Editor window, and add the following code in the Expression editor box:

    if(Job == 'MANAGER'){ Sal = 1000; } else{ Sal = 2000; }

  4. Select the Job attribute as the calculation is dependent on it.

  5. Now click on the OK button to add the expression for setting a default value for the Sal attribute.

What just happened?

We have created the default value for the attribute whose value is determined at runtime, using Groovy expression. This means that whenever we create a new record for the EMP table through EmpEO, If job is MANAGER, the Sal attribute is defaulted to 1000; otherwise the Sal attribute is defaulted to 2000. We will have a dependency set for the Sal attribute on job; this means whenever the value of job changes, the value of the Sal attribute is recalculated.

Have a go hero – set some default values for other attributes

We have now learned to set the default attribute using Groovy expressions. We will perform the following exercises to get familiar with the language:

  1. Set the default value for Job to CONTRACTOR when the value of Empno is greater than 100 in EmpEO.

  2. The Loc attribute for the DeptEO object will default to CHICAGO every time.

Validation execution

Validation execution is a section in attribute validation to set the execution rule. This is similar to the execution rule that we had set for entity-level validation. The validation for the attribute is executed only if the condition added to the expression editor is satisfied.

For example, we can have a compare validation set on the Sal attribute against 1000, say 9, and set the validation execution condition as Job == 'MANAGER'. This means the compare validation is executed only if the Job attribute is equal to MANAGER.

The validation execution section for entity-level validation will include a triggering attribute section that is not available in attribute validation.

Some commonly used expressions

Groovy expressions are used in ADF Business Components to evaluate and validate business logic. Groovy expression is preferred declarative expression language for the entity and view objects.

Sometimes, we will add an attribute for the entity or the view object with the values defaulted using Groovy expression as a calculated attribute known as transient attribute.

The following table gives the expressions and their functionalities:

Expression

Functionality

getAttribute("Sal")

This expression will fetch the Sal attribute.

(Date)getAttribute("HireDate")

This expression will cast the HireDate attribute value to Date.

new TimeStamp(System.currentTimeMillis())

This expressions will create a new Timestamp object from the current system time in long.

newValue

This expressions will get the new value for the attribute in the attribute-level validator.

 

oldValue

This expressions will get the old value for the attribute in the attribute-level validator.

source

This expressions will refer to the current entity object.

adf.context

This expressions will refer to the ADFContext object.

adf.object

This expressions will refer to the current object on which the expression is applied.

adf.error

This expressions will give reference for the current error handler object.

adf.error.raise

This expressions will raise an exception.

adf.error.warn

This expressions will raise a warning.

adf.currentDate

This expressions will refer to the current date with no time.

adf.currentDateTime

This expressions will refer to the current date with time.

rowSetAttr.sum(),rowSetAttr.count(), rowSetAttr.min(), rowSetAttr.max(), rowSetAttr.avg()

You can call the aggregate function on the ADF RowSet object. RowSet is a collection of rows returned through an association accessor.

Most of the Java methods such as subString(), compareTo(), and equals() can also be used in Groovy expressions along with some specific methods from EntityImpl.

Time for action – adding a script expression

Let us work on the Script expression validator for the Job attribute to understand the full advantages of Groovy expressions. Follow these steps:

  1. Select the Job attribute in the EmpEO entity object from the Attributes list.

  2. Click on the + icon to add a new validator.

  3. Select the Script Expression validator for the Rule Type option. This will open an Expression editor section to write the script.

  4. Enter the following code in this editor section:

    String value = newValue; String trim = value.trim(); if(trim.equals('MANAGER')){ adf.error.warn('NO_VACANCY'); return false; } return true;

  5. You can click on the Text Syntax button to check if the syntax is correct.

  6. Click on the OK button to add the script expression.

What just happened?

We have added a script validation for the Job attribute. The script is written to do the following:

  1. Assign the current value to the variable called value.

  2. The trimmed value is saved in a variable called trim.

  3. We are checking if the value of trim is equal to MANAGER.

  4. If the trimmed value is equal to MANAGER, then raise a warning from the property file for the resource bundle that says "No Position available to add more Managers".

    To add the warning message, you will have to select the Failure Handling tab and click on the magnifying glass icon.

  5. The ADF warning is displayed from the resource bundle, and in this case, there is no need to add a failure-handling message as we are already displaying a warning to the user.

  6. The return statement true or false signifies whether the result for the expression has passed or failed.

Have a go hero – try more features of Groovy expressions

You should try out more features of Groovy expressions to increase your proficiency in writing efficient scripting code and add declarative validation without having a separate class for the Java API.

You may try the following exercise:

  1. Try adding an attribute called DeptName to the EmpEO entity object and provide the default value as DepName- along with the Deptno entity added at the end.

    For example, if an employee belongs to department number 50, the DeptName attribute should default to DepName-50.

  2. List down all the common methods between Java and Groovy expressions, and note down how these methods differ.

Summary

In this article, we started with the information related to validations in ADF business components. Also, we learned to use all the built-in declarative validators available in ADF and saw how to use Groovy expression to validate business logic.

Resources for Article :


Further resources on this subject:


Oracle ADF 11gR2 Development Beginner's Guide Experience the easiest way to learn, understand, and implement rich Internet applications using Oracle ADF 11gR2 with this book and ebook
Published: April 2013
eBook Price: $29.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


Vinod Krishnan

Vinod Krishnan has over eight years' experience in the Information Technology industry this exposed him to a wide range of technologies that include Java, J2EE, WebLogic, Fusion Middleware, SOA, and Webcenter.

He has been working with Oracle ADF Technologies since 2005, and enhanced his affinity towards ADF after he joined Oracle India. For the last five years, Vinod is actively involved in large implementations of next-generation enterprise applications, utilizing Oracle's JDeveloper and Application Development Framework (ADF) technologies. He holds a B.Tech. in Information Technology from Anna University, Chennai, India.

He is currently responsible for building and deploying applications using the Oracle Fusion Middleware technology stack as a Project Lead in Oracle America.

He is an Oracle Certified Specialist, and the technologies he has worked on include Oracle ADF, SOA, Webcenter, and Identity Management. His contribution towards Jdeveloper and ADF discussion forums is immense. With his experience, he has learned many tips and techniques that will help a new user to learn this technology without any hassles. He writes his own blog (http://vtkrishn.com) that discusses the tips and tricks with using Oracle technologies.

Vinod has had a multifaceted career, he has worked in positions such as Senior Consultant, Senior Applications Engineer, Software Engineer, and Solution Architect for MNCs such as Oracle, Capgemini, and Keane. Currently he is working as a Project Lead in Oracle America.

Books From Packt


Oracle Enterprise Manager Cloud Control 12c: Managing Data Center Chaos
Oracle Enterprise Manager Cloud Control 12c: Managing Data Center Chaos

Oracle APEX 4.0 Cookbook
Oracle APEX 4.0 Cookbook

 Oracle APEX Best Practices
Oracle APEX Best Practices

 Oracle ADF Real World Developer’s Guide
Oracle ADF Real World Developer’s Guide

Oracle Information Integration, Migration, and Consolidation
Oracle Information Integration, Migration, and Consolidation

Oracle ADF Enterprise Application Development—Made Simple
Oracle ADF Enterprise Application Development—Made Simple

Oracle SOA Suite 11g R1 Developer's Guide
Oracle SOA Suite 11g R1 Developer's Guide

 Do more with SOA Integration: Best of Packt
Do more with SOA Integration: Best of Packt


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
7
q
Q
n
q
1
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software