37.1 Globally Extending ADF Business Components Functionality

One of the powerful features of framework-based development is the ability to extend the base framework to change a built-in feature to behave differently or to add a new feature that can be used by all of your applications.

37.1.1 How To Create a Framework Extension Class

An ADF Business Components framework extension class is Java class you write that extends one of the framework's base classes to:

Augment a built-in feature works with additional, generic functionality

Change how a built-in feature works, or even to

Workaround a bug you encounter in a generic way

Once you've created a framework extension class, any new ADF components you create can be based on your customized framework class instead of the base one. Of course, you can also update the definitions of existing components to use the new framework extension class as well.

To create a framework extension class:

Identify a project to contain the framework extension class.

You can create it in the same project as your business service components if you believe it will only be used by components in that project. Alternatively, if you believe you might like to reuse the framework extension class across multiple Fusion web applications, create a separate FrameworkExtensions project to contain the framework extension classes.

Ensure the BC4J Runtime library is in the project's libraries list.

Use the Libraries page of the Project Properties dialog to verify this and to add the library if missing.

In the New Gallery, in the General category, select Java Class to create the new class.

In the Create Java Class dialog, specify the appropriate framework base class from the oracle.jbo.server package in the Extends field.

Figure 37-1 illustrates what it would look like to create a custom framework extension class named CustomAppModuleImpl in the com.yourcompany.fwkext package to customize the functionality of the base application module component. To quickly find the base class you're looking for, use the Browse button next to the Extends field that launches the JDeveloper Class Browser. Using its Search tab, you can type in part of the class name (including using * as a wildcard) to quickly subset the list of classes to find the one you're looking for.

When you click OK, JDeveloper creates the custom framework extension class for you in the directory of the project's source path corresponding to the package name you've chosen.

Note:

Some ADF Business Components component classes exist in both a server-side and a remote-client version. For example, if you use the JDeveloper Class Browser and type ApplicationModuleImpl into the Match Class Name field on the Search tab, the list will show two ApplicationModuleImpl classes: one in the oracle.jbo.server package and the other in the oracle.jbo.client.remote package. When creating framework extension classes, use the base ADF classes in the oracle.jbo.server package.

37.1.2 What Happens When You Create a Framework Extension Class

After creating a new framework extension class, it will not automatically be used by your application. You must decide which components in your project should make use of it. The following sections describe the available approaches for basing your ADF components on your own framework extension classes.

37.1.3 How to Base an ADF Component on a Framework Extension Class

You can set the base classes for any ADF component using the Java page of any ADF Business Components wizard or editor.

If you created your framework extension classes in a separate project, visit the Dependencies page of the Project Properties dialog for the project containing your business components and mark the FrameworkExtension project as a project dependency.

If you have packaged your framework extension classes in a Java archive (JAR) file, create a named library definition to reference its JAR file and also list that library in the library list of the project containing your business components. To create a library if missing, use the Manage Libraries dialog available from the Tools > Manage Libraries main menu item. To verify or adjust the project's library list, use the Libraries page of the Project Properties dialog.

After you ensure the framework classes are available to reference, you can create the ADF component. Every ADF Business Components wizard and editor displays the same Class Extends button on the Java page so you can use the technique to choose your desired framework extension base class(es) both for new components or existing ones.

There is no fixed limit on how many levels of framework extension classes you create. For example, after creating a company-level CustomAppModuleImpl to use for all application modules in all Fusion web applications that your company creates, some later project team might encounter the need to further customize that framework extension class. That team could create a SomeProjectCustomAppModuleImpl class that extends the CustomAppModuleImpl and then include the project-specific custom application module code in there as shown in Example 37-1.

Then, any application modules created as part of the implementation of this specific project can use the SomeProjectCustomAppModuleImpl as their base class instead of the CustomAppModuleImpl.

To create an ADF component based on a framework extension class:

In the Application Navigator, double-click the desired component.

In the overview editor, click the Java navigation tab and click the Edit Java options button.

In the Select Java Options dialog, click Classes Extends.

In the Override Base Classes dialog, enter the fully-qualified name of the framework base classes you wish to override. You can also use the Browse button to use the JDeveloper Class Browser to find the classes quickly.

When you use the Class Browser to select a custom base class for the component, the list of available classes is automatically filtered to show only classes that are appropriate. For example, when clicking Browse in Figure 37-2 to select an application module Object base class, the list will only show classes available in the current project's library list which extend the oracle.jbo.server.ApplicationModule class either directly or indirectly. If you don't see the class you're looking for, either you extended the incorrect base class or you have chosen the wrong component class name to override.

Figure 37-2 Specifying a Custom Base Class for a New Application Module

37.1.4 How to Define Framework Extension Classes for All New Components

If you decide to use a specific set of framework extension classes as a standard for a given project, you can use the Project Properties dialog to define your preferred base classes for each component type. Setting these preferences for base classes does not affect any existing components in the project, but the component wizards will use the preferences for any new components created.

To define project-level preferences for framework extension classes:

In the Application Navigator, right-click the model project that will contain the extension classes and choose Project Properties.

In the Project Properties dialog, expand Business Components > Base Classes in the tree.

On the Business Components page, enter the fully-qualified name of that class in the Application Module Object class name field.

For example, to indicate that any new application modules created in the project should use the CustomAppModuleImpl class by default, enter the fully-qualified name of that class in the componentNameObject class name field as shown in Figure 37-3.

37.1.5 How to Define Framework Extension Classes for All New Projects

When you want to apply the same base class preferences to each new project that you create in JDeveloper, you can define the preferences at a global level using the Preferences dialog. Base classes that you specify at the global level will not alter your existing projects containing ADF components.

To define global preferences for framework extension classes:

In the Tools menu, choose Preferences.

In the Preferences dialog, expand Business Components > Base Classes in the tree.

On the Business Components page, enter the fully-qualified name of that class in componentNameObject class name field.

The page displays the same options for specifying the preferred base classes for each component type as shown in Figure 37-3.

37.1.6 What Happens When You Base a Component on a Framework Extension Class

When an ADF component you create extends a custom framework extension class, JDeveloper updates its XML component definition to reflect the custom class name you've chosen.

37.1.6.1 XML-Only Components

For example, assume you've created the YourService application module in the com.yourcompany.yourapp package, with a custom application module base class of CustomAppModuleImpl. If you have opted to leave the component as an XML-only component with no custom Java file, its XML component definition (YourService.xml) will look like what you see in Example 37-2. The value of the ComponentClass attribute of the AppModule tag is read at runtime to identify the Java class to use to represent the component.

Figure 37-4 illustrates how the XML-only YourService application module relates to your custom extension class. At runtime, it uses the CustomAppModuleImpl class which inherits its base behavior from the ApplicationModuleImpl class.

37.1.6.2 Components with Custom Java Classes

If your component requires a custom Java class, as you've seen in previous chapters you open the Java page of the component editor and check the appropriate checkbox to enable it. For example, when you enable a custom application module class for the YourServer application module, JDeveloper creates the appropriate YourServiceImpl.java class. As shown in Example 37-3, it also updates the component's XML component definition to reflect the name of the custom component class.

Figure 37-5 illustrates how the YourService application module with its custom YourServiceImpl class is related to your framework extension class. At runtime, it uses the YourServiceImpl class which inherits its base behavior from the CustomAppModuleImpl framework extension class which, in turn, extends the base ApplicationModuleImpl class.

37.1.7 What You May Need to Know About Updating the Extends Clause in Custom Component Java Files

If you have an ADF component with a custom Java class and later decide to base the component on a framework extension class, use the Class Extends button on the Java page of the component's overview editor to change the component's base class. Doing this updates the component's XML component definition to reflect the new base class, and also modifies the extends clause in the component's custom Java class. If you manually update the extends clause without using the component editor, the component's XML component definition will not reflect the new inheritance and the next time you open the editor, your manually modified extends clause will be overwritten with what the component editor believes is the correct component base class.

37.2 Creating a Layer of Framework Extensions

Before you begin to develop application-specific business components, Oracle recommends that you consider creating a complete layer of framework extension classes and setting up your project-level preferences to use that layer by default. You might not have any custom code in mind to put in these framework extension classes yet, but you will be glad you heeded this recommendation the first time you encounter a need to:

Failure to set up these preferences at the outset can present your team with a substantial inconvenience if you discover mid-project that all of your entity objects, for example, require a new generic feature, augmented built-in feature, or a generic bug workaround. Putting a complete layer of framework classes in place at the start of your project is an insurance policy against this inconvenience and the wasted time related to dealing with it later in the project. JDeveloper will automatically use framework classes when you create them.

37.2.1 How to Create Your Layer of Framework Extension Layer Classes

A common set of customized framework base classes in a package name of your own choosing like com.yourcompany.adfextensions, each importing the oracle.jbo.server.* package, would consist of the following classes:

For your convenience, the FrameworkExtensions project of the AdvancedExamples workspace in the StandaloneExamples module of the Fusion Order Demo application contains a set of these classes. You can select the com.yourcompany.adfextensions package in the Application Navigator and choose the Refactor > Rename option from the context menu to change the package name of all the classes to a name you prefer.

For completeness, you may also want to create customized framework classes for the following classes as well, note however that overriding anything in these classes would be a fairly rare requirement.

37.2.2 How to Package Your Framework Extension Layer in a JAR File

Use the Create Deployment Profile: JAR File dialog to create a JAR file containing the classes in your framework extension layer. This is available in the New Gallery in the General > Deployment Files category.

Give the deployment profile a name like FrameworkExtensions and click OK. By default the JAR file will include all class files in the project. Since this is exactly what you want, when the JAR Deployment Profile Properties dialog appears, you can just click OK to finish.

Note:

Do not use the ADF Library JAR archive type to package your framework extension layer. You create the ADF Library JAR file when you want to package reusable components to share in the JDeveloper Resource Catalog. For details about working with ADF components and the ADF Library JAR archive type, see Section 33.2, "Packaging a Reusable ADF Component into an ADF Library."

Finally, to create the JAR file, right-click the project folder in the Application Navigator and choose Deploy - YourProfileName - to JAR File on the context menu. A Deployment tab appears in the JDeveloper Log window that should display feedback like:

37.2.3 How to Create a Library Definition for Your Framework Extension JAR File

JDeveloper uses named libraries as a convenient way to organize the one or more JAR files that comprise reusable component libraries.

To define a library for your framework extensions JAR file:

Choose Tools > Manage Libraries from the JDeveloper main menu.

In the Manage Libraries dialog, select the Libraries tab.

Select the User folder in the tree and click the New button.

In the Create Library dialog that appears, name the library "Framework Extension Layer" and select the Class Path node and click Add Entry.

Use the Select Path Entry dialog that appears to select the FrameworkExtensions.jar file that contains the class files for the framework extension components, then click Select.

Select the Source Path node and click Add Entry.

Use the Select Path Entry dialog that appears to select the ..\FrameworkExtensions\src directory where the source files for the framework extension classes reside, then click Select.

Click OK to dismiss the Create Library dialog and define the new library.

When finished, you will see your new "Framework Extension Layer" user-defined library, as shown in Figure 37-6. You can then add this library to the library list of any project where you will be building business services, and your custom framework extension classes will be available to reference as the preferred component base classes.

37.3 Customizing Framework Behavior with Extension Classes

One of the common tasks you'll perform in your framework extension classes is implementing custom application functionality. Since framework extension code is written to be used by all components of a specific type, the code you write in these classes often needs to work with component attributes in a generic way. To address this need, ADF provides API's that allow you to access component metadata at runtime. It also provides the ability to associate custom metadata properties with any component or attribute. You can write your generic framework extension code to leverage runtime metadata and custom properties to build generic functionality, which if necessary, only is used in the presence of certain custom properties.

Note:

The example in this section refers to the ProgrammaticallySetProperties project of the AdvancedExamples application workspace in the StandaloneExamples module of the Fusion Order Demo application.

37.3.1 How to Access Runtime Metadata For View Objects and Entity Objects

Figure 37-7 illustrates the three primary interfaces ADF provides for accessing runtime metadata about view objects and entity objects. The ViewObject interface extends the StructureDef interface. The class representing the entity definition (EntityDefImpl) also implements this interface. As its name implies, the StructureDef defines the structure and the component and provides access to a collection of AttributeDef objects that offer runtime metadata about each attribute in the view object row or entity row. Using an AttributeDef, you can access its companion AttributeHints object to reference hints like the display label, format mask, tooltip, etc.

37.3.2 How to Implement Generic Functionality Using Runtime Metadata

In Section 6.4.1, "ViewObject Interface Methods for Working with the View Object's Default RowSet" you learned that for read-only view objects the findByKey() method and the setCurrentRowWithKey builtin operation only work if you override the create() method on the view object to call setManageRowsByKey(true). This can be a tedious detail to remember if you create a lot of read-only view objects, so it is a great candidate for automating in a framework extension class for view objects.

Assume a FrameworkExtensions project contains a FODViewObjectImpl class that is the base class for all view objects in the application. This framework extension class for view objects extends the base ViewObjectImpl class and overrides the create() method as shown in Example 37-5 to automate this task. After calling the super.create() to perform the default framework functionality when a view object instance is created at runtime, the code tests whether the view object is a read-only view object with at least one attribute marked as a key attribute. If this is the case, it invokes setManageRowsByKey(true).

The isReadOnlyNonEntitySQLViewWithAtLeastOneKeyAttribute() helper method determines whether the view object is read-only by testing the combination of the following conditions:

isFullSql() is true

This method returns true if the view object's SQL query is completely specified by the developer, as opposed to having the select list derived automatically based on the participating entity usages.

getEntityDefs() is null

This method returns an array of EntityDefImpl objects representing the view object's entity usages. If it returns null, then the view object has no entity usages.

It goes on to determine whether the view object has any key attributes by looping over the AttributeDef array returned by the getAttributeDefs() method. If the isPrimaryKey() method returns true for any attribute definition in the list, then you know the view object has a key.

37.3.3 How to Implement Generic Functionality Driven by Custom Properties

In JDeveloper, when you create application modules, view objects, and entity objects you can select the General navigation tab in the overview editor for these business components and expand the Custom Properties section to define custom metadata properties for any component. These are name/value pairs that you can use to communicate additional declarative information about the component to the generic code that you write in framework extension classes. You can use the getProperty() method in your code to conditionalize generic functionality based on the presence of, or the specific value of, one of these custom metadata properties.

For example, the FODViewObjectImpl framework extension class overrides the view object's insertRow() method as shown in Example 37-6 to conditionally force a row to be inserted and to appear as the last row in the row set. If any view object extending this framework extension class defines a custom metadata property named InsertNewRowsAtEnd, then this generic code executes to insert new rows at the end. If a view object does not define this property, it will have the default insertRow() behavior.

Example 37-6 Conditionally Inserting New Rows at the End of a View Object's Default RowSet

In addition to defining component-level custom properties, you can also define properties on view object attributes, entity object attributes, and domains. At runtime, you access them using the getProperty() method on the AttributeDef interface for a given attribute.

37.3.4 How to Configure Design Time Custom Property Names

Once you have written framework extension classes that depend on custom properties, you can set a JDeveloper preference so that your custom property names show in the list on the Custom Properties section of the corresponding component editor. To set up these pre-defined custom property names, choose Tools > Preferences from the JDeveloper main menu and open the Business Components > Property Names tab in the Preferences dialog.

37.3.5 What You May Need to Know About the Kinds of Attributes

In addition to providing information about an attribute's name, Java type, SQL type, and many other useful pieces of information, the AttributeDef interface contains the getAttributeKind() method that you can use to determine the kind of attribute it represents. This method returns a byte value corresponding to one of the public constants in the AttributeDef interface listed in Table 37-1.

Table 37-1 Entity Object and View Object Attribute Kinds

Public AttributeDef Constant

Attribute Kind Description

ATTR_PERSISTENT

Persistent attribute

ATTR_TRANSIENT

Transient attribute

ATTR_ENTITY_DERIVED

View object attribute mapped to an entity-level transient attribute

ATTR_SQL_DERIVED

SQL-Calculated attribute

ATTR_DYNAMIC

Dynamic attribute

ATTR_ASSOCIATED_ROWITERATOR

Accessor attribute returning a RowSet of set of zero or more Rows

ATTR_ASSOCIATED_ROW

Accessor attribute returning a single Row

37.3.6 What You May Need to Know About Custom Properties

You may find it handy to programmatically set custom property values at runtime. While the setProperty() API to perform this function is by design not available to clients on the ViewObject, ApplicationModule, or AttributeDef interfaces in the oracle.jbo package, code you write inside your ADF components' custom Java classes can use it.

The ADF wizards will only "see" your interfaces after they have been successfully compiled.

After your have implemented your CustomApplicationModuleImpl class, you can create a new application module which exposes the global extension interface and is based on your custom framework extension class. For this purpose you use the overview editor for application modules.

To create a custom application module interface:

In the Application Navigator, double-click the application module for which you want to create the custom interface.

For example, you might create a new ProductModule application module which exposes the global extension interface CustomApplicationModule and is based on the CustomApplicationModuleImpl framework extension class.

In the overview editor, select the Java navigation tab and click the Edit Java options icon.

The Java Classes page should show an existing Java class for the application module identified as Application Module Class.

By default, JDeveloper generates the Java class for application modules you create. However, if you disabled this feature, click the Edit Java options button in the Java Classes section and select Generate Application Module Class. Click OK to add a Java class to the project from which you will create the custom interface.

In the Select Java Options dialog, click Class Extends.

In the Override Base Classes dialog, specify the name of the framework base class you want to override and click OK.

For example, you might select CustomApplicationModuleImpl as the base class for the application module.

In the Java Classes page of the overview editor, expand the Client Interface section and click the Edit application module client interface button.

In the Edit Client Interface dialog, click the Interfaces button.

In the Select Interfaces to Extend dialog, select the desired custom application module interface from the available list and click OK.

For example, you might shuttle the CustomApplicationModule interface to the Selected list to be one of the custom interfaces that clients can use with your component.

In the Edit Client Interfaces dialog, ensure that at least one method appears in the Selected list.

Note:

You need to select at least one method in the Selected list in the Edit Client Interfaces dialog, even if it means redundantly selecting one of the methods on the global extension interface. Any method will do in order to get JDeveloper to generate the custom interface.

Click OK.

The Java Classes page displays the new custom interface for the application module identified as Application Module Client Interface.

When you dismiss the Edit Client Interfaces dialog and return to the application module overview editor, JDeveloper generates the application module custom interface. For example, the custom interface ProductModule automatically extends both the base ApplicationModule interface and your CustomApplicationModule extension interface like this:

Once you've done this, then client code can cast your ProductModule application module to a CustomApplicationModule interface and invoke the generic extension methods it contains in a strongly-typed way.

Note:

The basic steps are the same for exposing methods on a ViewObjectImpl framework extension class, as well as for a ViewRowImpl extension class.

37.5 Invoking Stored Procedures and Functions

You can write code in the custom Java classes for your business components to invoke database stored procedures and functions. Here you'll consider some simple examples based on procedures and functions in a PL/SQL package; however, using the same techniques, you also can invoke procedures and functions that are not part of a package.

37.5.2 How to Invoke Stored Procedure with Only IN Arguments

Invoking stored procedures that accept only IN-mode arguments — which is the default PL/SQL parameter mode if not specified — requires using a JDBC PreparedStatement object. The DBTransaction interface provides a createPreparedStatement() method to create this object for you in the context of the current database connection. You could use a helper method like the one shown in Example 37-9 to simplify the job of invoking a stored procedure of this kind using a PreparedStatement. Importantly, by using a helper method, you can encapsulate the code that closes the JDBC PreparedStatement after executing it. The code performs the following basic tasks:

Creates a JDBC PreparedStatement for the statement passed in, wrapping it in a PL/SQL begin...end block.

Loops over values for the bind variables passed in, if any.

Sets the value of each bind variable in the statement.

Notice that since JDBC bind variable API's use one-based numbering, the code adds one to the zero-based for loop index variable to account for this.

Executes the statement.

Closes the statement.

Example 37-9 Helper Method to Simplify Invoking Stored Procedures with Only IN Arguments

Notice the question marks used as JDBC bind variable placeholders for the arguments passed to the function. JDBC also supports using named bind variables, but using these simpler positional bind variables is also fine since the helper method is just setting the bind variable values positionally.

37.5.3 How to Invoke Stored Function with Only IN Arguments

Invoking stored functions that accept only IN-mode arguments requires using a JDBC CallableStatement object in order to access the value of the function result after executing the statement. The DBTransaction interface provides a createCallableStatement() method to create this object for you in the context of the current database connection. You could use a helper method like the one shown in Example 37-10 to simplify the job of invoking a stored function of this kind using a CallableStatement. The helper method encapsulates both the creation and clean up of the JDBC statement being used.

The code performs the following basic tasks:

Creates a JDBC CallableStatement for the statement passed in, wrapping it in a PL/SQL begin...end block.

Registers the first bind variable for the function return value.

Loops over values for the bind variables passed in, if any.

Sets the value of each bind user-supplied bind variable in the statement.

Notice that since JDBC bind variable API's use one-based numbering, and since the function return value is already the first bind variable in the statement, the code adds two to the zero-based for loop index variable to account for these.

Executes the statement.

Returns the value of the first bind variable.

Closes the statement.

Example 37-10 Helper Method to Simplify Invoking Stored Functions with Only IN Arguments

Notice the question marks are used as JDBC bind variable placeholders for the arguments passed to the function. JDBC also supports using named bind variables, but using these simpler positional bind variables is also fine since the helper method is just setting the bind variable values positionally.

37.5.4 How to Call Other Types of Stored Procedures

Calling a stored procedure or function like devguidepkg.proc_with_out_args that includes arguments of OUT or IN OUT mode requires using a CallableStatement as in the previous section, but is a little more challenging to generalize into a helper method. Example 37-11 illustrates the JDBC code necessary to invoke the devguidepkg.proc_with_out_args procedure.

The code performs the following basic tasks:

Defines a PL/SQL block for the statement to invoke.

Creates the CallableStatement for the PL/SQL block.

Registers the positions and types of the OUT parameters.

Sets the bind values of the IN parameters.

Executes the statement.

Creates a JavaBean to hold the multiple return values

The DateAndStringBean class contains bean properties named dateVal and stringVal.

In order to allow the custom method to be a legal candidate for inclusion in an application module's custom service interface (if desired), the bean needs to implement the java.io.Serializable. interface. Since this is a "marker" interface, this involves simply adding the implements Serializable keywords without needing to code the implementation of any interface methods.

37.6 Accessing the Current Database Transaction

Since the ADF Business Components components abstract all of the lower-level database programming details for you, you typically won't need direct access to the JDBC Connection object. Unless you use the reserved release mode described in Section 40.2.2.3.3, "About Reserved Release Level," there is no guarantee at runtime that your application will use the exact same application module instance or JDBC Connection instance across different web page requests. Since inadvertently holding a reference to the JDBC Connection object in this type of pooled services environment can cause unpredictable behavior at runtime, by design, the ADF Business Components layer has no direct API to obtain the JDBC Connection. This is an intentional attempt to discourage its direct use and inadvertent abuse.

However, on occasion it may come in handy when you're trying to integrate third-party code with ADF Business Components, so you can use a helper method like the one shown in Example 37-12 to access the connection.

Never cache the JDBC connection obtained using the helper method from Example 37-12 in your own code anywhere. Instead, call the helper method each time you need it to avoid inadvertently holding a reference to a JDBC Connection that might be used in another request by another user at a later time do to the pooled services nature of the ADF runtime environment.

37.7 Working with Libraries of Reusable Business Components

As with other Java components, you can create a JAR file containing one of more packages of reusable ADF components. Then, in other projects you can import one or more packages of components from this component library to reference those in a new application.

37.7.1 How To Create a Reusable Library of Business Components

Use the Create Business Components Archive Profile dialog to create a JAR file containing the Java classes and XML component definitions that comprise your business components library. This is available in the New Gallery in the General > Deployment Profiles category.

Note:

If you don't see the Deployment Profiles category in the New Gallery, set the Filter By dropdown list at the top of the dialog to the All Technologies choice to make it visible.

Give the deployment profile a name like ReusableComponents and click OK. As the Project Properties dialog shows in Figure 37-8, the ReusableComponents business components deployment archive profile contains two nested JAR deployment profiles:

Common.deploy

MiddleTier.deploy

These two nested profiles are standard JAR deployment profiles that are pre-configured to bundle:

All of the business components custom java classes and XML component definitions into a ReusableComponentsCSMT.jar archive

All of the client interfaces, message bundle classes, and custom domains into a ReusableComponentsCSCommon.jar

They are partitioned this way in order to simplify deployment of ADF Business Components-based applications. The *CSMT.jar is an archive of components designed to be deployed only on the middle tier application server. The *CSCommon.jar is common both to the application server and to the remote client tier in the deployment scenario when the client interacting with the application module is running in a different physical server from the application module with which it is working.

To create the JAR files, in the Application Navigator right-click the Business Components project folder and choose Deploy and the ReusableComponents profile. A Deployment tab appears in the JDeveloper Log window that should display feedback like:

37.7.2 How To Import a Package of Reusable Components from a Library

Once you have created a reusable library of business components, you can import one or more packages of components from that library in other projects to reference them. When you import a package of business components from a library, the components in that package are available in the various Available lists of the ADF Business Components component wizards and editor, however they do not display in the Application Navigator nor are they editable. The only components that appear in the Application Navigator are the ones in the source path for the current project.

Tip:

If you require components that are editable and display in the Application Navigator. Add additional business components from a directory that is not currently part of your project's source path, then open the Project Content page of the Project Properties dialog and add the parent directory for these other components as one of the directories in the Java Content list. In contrast to imported packages of components, additional components added to your project's source path will be fully editable and will appear in the Application Navigator.

To import a package of business components from a library:

Define a library for your JAR file on the Libraries tab of the Project Properties dialog of the importing project.

You can define the library as a project-level library or a user-level library. Be sure to include both the *CSMT.jar and the *CSCommon.jar in the class path of the library definition.

Include the new library in your importing project's library list.

With the importing project selected in the Application Navigator, choose Import from the File menu.

In the Import dialog, select Business Components from the list.

Use the file open dialog to navigate into your library's *CSMT.jar file — as if it were a directory — and select the XML component definition file from any components in the package whose components you want to import.

Acknowledge the alert that confirms the successful importing of the package.

Repeat steps 3-6 again for each package of components you want to import.

Assuming that there was an entity object like Product in the package(s) of components you imported, you could then create a new view object in the importing project using the imported Product component as its entity usage. This is just one example. You can reference any of the imported components as if they were in the source path of your project. The only difference is that you cannot edit the imported components. In fact, the reusable component library JAR file might only contain the XML component definition files and the Java *.class files for the components without any source code.

37.7.3 How to Remove an Imported Package from a Project

If you mistakenly import a package of components, or wish to remove an imported package of components that you are not using, you can use the Project Properties dialog to do this.

To unimport a package:

In the Application Navigator, right-click the model project that contains the package you want to unimport and choose Project Properties.

In the Project Properties dialog, select Business Components > Imports.

Select the project from the list of imported projects and click Delete.

Click OK to save the changes to the workspace in JDeveloper.

Caution:

Do not remove an imported package if your project still has components that reference it. If you do, JDeveloper will throw exceptions when the project is opened, or your application may have unpredictable behavior. In the Business Components: Imports page of the Project Properties dialog, click the Show Usages button to ensure that there are no references to any of the components in the imported package before manually removing the package entry from the *.jpx file.

37.7.4 What Happens When You Import a Package of Reusable Components from a Library

When you import a package of components into a project named YourImportingProjectName, JDeveloper adds a reference to that package in the YourImportingProjectName.jpx file in the root directory of your importing project's source path. As part of this entry, it includes a design time project named _LocationURL whose value points to the JAR file in which the imported components reside.

37.7.5 What You May Need to Know About Imported Projects

Components in imported libraries are not editable. If a project imports a package containing business components, the importing project cannot add new components to that same package. The importing project can reference the imported components in new components created in any other package, but cannot add new components to the imported package

Additionally, if you make changes to your imported components and update the JAR file that contains them, you need to close and reopen any importing projects in order to pickup the changes. This does not require exiting out of JDeveloper. You can select your importing project in the Application Navigator, choose Close from the File menu, and then re-expand the project's nodes to close and reopen the project. When you do this, JDeveloper will reread the components from the updated version of the imported JAR file.

37.8 Customizing Business Components Error Messages

Note:

The example in this section refers to the CustomizedErrorMessages project of the AdvancedExamples application workspace in the StandaloneExamples module of the Fusion Order Demo application.

You can customize any of the builtin ADF Business Components error messages by providing an alternative message string for the error code in a custom message bundle.

Note:

For your convenience, the CustomizedErrorMessages project in the AdvancedExamples workspace of the Fusion Order Demo lets you test the custom message bundle sample described in this section. Before you run the ProductModule, you will need to run the addProductsTableConstraint.sql script to set up the sample with the corresponding database constraint. When you run the ProductModule application module in the Business Component Browser, you can blank out the ProductId attribute and click the Validate button. This will show the custom error message for the JBO error. Rollback the change and then enter undefined in the ProductName attribute. You can view the custom error message for the database error by clicking Commit (clicking Validate won't perform a commit to the database, so the database error is not generated in that case).

37.8.1 How to Customize Base ADF Business Components Error Messages

Assume you want to customize the builtin error message:

JBO-27014: Attribute Name is Product is required

If you have requested the Oracle ADF source code from Oracle Worldwide Support, you can look in the CSMessageBundle.java file in the oracle.jbo package to see that this error message is related to the combination of the following lines in that message bundle file:

The numbered tokens {2} and {1} are error message placeholders. In this example the {l} is replaced at runtime with the name of the entity object and the {2} with the name of the attribute.

To create a custom message bundle file:

In the Application Navigator, right-click the model project that you want to add the message bundle file to and choose Project Properties.

In the Project Properties dialog, select Business Components > Options.

The Custom Message Bundles to use in this Project list displays at the bottom of the dialog.

Click New.

Enter a name and package for the custom message bundle in the Create MessageBundle class dialog and click OK.

Note:

If the fully-qualified name of your custom message bundle file does not appear in the Custom Message Bundles to use in this Project list, click the Remove button, then click the Add button to add the new message bundle file created. When the custom message bundle file is correctly registered, it's fully-qualified class name should appear in the list, as shown in Figure 37-9.

Figure 37-9 Project Properties Displays Message Resource Bundles

Click OK to dismiss the Project Properties dialog and open the new custom message bundle class in the source editor.

Edit the two-dimensional String array in the custom message bundle class to contain any customized messages you'd like to use.

37.8.2 What Happens When You Customize Base ADF Business Components Error Messages

After adding this message to your custom message bundle file, if you test the application using the Business Component Browser and try to blank out the value of a mandatory attribute, you'll now see your custom error message instead of the default one:

JBO-27014: You must provide a value for Name

You can add as many messages to the message bundle as you want. Any message whose error code key matches one of the built-in error message codes will be used at runtime instead of the default one in the oracle.jbo.CSMessageBundle message bundle.

37.8.3 How to Customize Error Messages for Database Constraint Violations

If you enforce constraints in the database, you might want to provide a custom error message in your Fusion web application to display to the end user when one of those constraints is violated. For example, assume a constraint called NAME_CANNOT_BEGIN_WITH_U gets added to the application's PRODUCTS_BASE table using the following DDL statement shown in Example 37-14.

To define a custom error message in your application, you add a message to a custom message bundle with the constraint name as the message key. Example 37-15 shows the CustomMessageBundle.java class when it defines a message with the key NAME_CANNOT_BEGIN_WITH_U which matches the name of the database constraint name defined in Example 37-14.

37.8.4 How to Implement a Custom Constraint Error Handling Routine

If the default facility for assigning a custom message to a database constraint violation does not meet your needs, you can implement your own custom constraint error handling routine. Doing this requires creating a custom framework extension class for the ADF transaction class, which you then configure your application module to use at runtime.

To write a custom framework extension class for the ADF transaction, create a class like the CustomDBTransactionImpl shown in Example 37-16. This example overrides the transaction object's postChanges() method to wrap the call to super.postChanges() with a try/catch block in order to perform custom processing on any DMLConstraintException errors that might be thrown. In this simple example, the only custom processing being performed is a call to ex.setExceptions(null) to clear out any nested detail exceptions that the DMLConstraintException might have. Instead of this, you could perform any other kind of custom exception processing required by your application, including throwing a custom exception, provided your custom exception extends JboException directly or indirectly.

37.8.4.2 Configuring an Application Module to Use a Custom Database Transaction Class

In order for your application module to use a custom database transaction class at runtime, you must:

Provide a custom implementation of the DatatabaseTransactionFactory class that overrides the create() method to return an instance of the customized transaction class.

Configure the value of the TransactionFactory property to be the fully-qualified name of this custom transaction factory class.

Example 37-17 shows a custom database transaction factory class that does this. It returns a new instance of the CustomDBTransactionImpl class when the framework calls the create() method on the database transaction factory.

To complete the job, use the Properties tab of the Create Business Components Configuration dialog to assign the value devguide.advanced.customerrors.CustomDatabaseTransactionFactory to the TransactionFactory property, as shown in Figure 37-10. You can open the Create Business Components Configuration dialog from the Configuration page of the overview editor for the application module by clicking the Create new configuration objects button. When you run the application using this configuration, your custom transaction class will be used.

37.9 Creating Extended Components Using Inheritance

Whenever you create a new business component, if necessary, you can extend an existing one to create a customized version of the original. As shown in Figure 37-11, the ProductsByName view object extends the Products view object to add a named bind variable named TheStatus and to customize the WHERE clause to reference that bind variable.

Figure 37-11 ADF Business Components Can Extend Another Component

While the figure shows a view object example, this component inheritance facility is available for all component types. When one component extends another, the extended component inherits all of the metadata and behavior from the parent it extends. In the extended component, you can add new features or customize existing features of its parent component both through metadata and Java code.

Note:

The example in this section refers to the BaseProject project of the AdvancedExamples workspace in the StandaloneExamples module of the Fusion Order Demo application.

37.9.1 How To Create a Component That Extends Another

To create an extended component, use the component wizard in the New Gallery for the type of component you want to create. For example, to create an extended view object, you use the Create View Object wizard. On the Name page of the wizard — in addition to specifying a name and a package for the new component — provide the fully-qualified name of the component that you want to extend in the Extends field. To pick the component name from a list, use the Browse button next to the Extends field. Then, continue to create the extended component in the normal way using the remaining panels of the wizard.

37.9.2 How To Extend a Component After Creation

After you define an extended component, JDeveloper lets you change the parent component from which an extended component inherits. You can use the overview editor for the component to accomplish this.

To change the parent component after creation:

Double-click the component.

In the overview editor for the component, click the General navigation tab and click the Refactor object extends button next to the Extends field.

In the Select Parent dialog, choose the desired component to extend from the package list.

To change the extended component to not inherit from any parent, select the None checkbox in the Select Parent dialog. This has the same effect as if you deleted the component and recreated to accomplish this.

37.9.3 What Happens When You Create a Component That Extends Another

ADF business components you create are comprised of an XML component definition and an optional Java class. When you create a component that extends another, JDeveloper reflects this component inheritance in both the XML component definition and in any generated Java code for the extended component.

37.9.3.1 Understanding an Extended Component's XML Descriptor

JDeveloper notes the name of the parent component in the new component's XML component definition by adding an Extends attribute to the root component element. Any new declarative features you add or any aspects of the parent component's definition you've overridden appear in the extended component's XML component definition. In contrast, metadata that is purely inherited from the parent component is not repeated for the extended component.

Example 37-18 shows what the ProductsByName.xml XML component definition for the ProductsByName view object looks like. Notice the Extends attribute on the ViewObject element, the Variable element related to the additional bind variable added in the extended view object, and the overridden value of the Where attribute for the WHERE clause that was modified to reference the theProductName bind variable.

37.9.3.2 Understanding Java Code Generation for an Extended Component

If you enable custom Java code for an extended component, JDeveloper automatically generates the Java classes to extend the respective Java classes of its parent component. In this way, the extended component can override any aspect of the parent component's programmatic behavior as necessary. If the parent component is an XML-only component with no custom Java class of its own, the extended component's Java class extends whatever base Java class the parent would use at runtime. This could be the default ADF Business Components framework class in the oracle.jbo.server package, or could be your own framework extension class if you have specified that in the Extends dialog of the parent component.

In addition, if the extended component is an application module or view object and you enable client interfaces on it, JDeveloper automatically generates the extended component's client interfaces to extend the respective client interfaces of the parent component. If the respective client interface of the parent component does not exist, then the extended component's client interface directly extends the appropriate base ADF Business Components interface in the oracle.jbo package.

37.9.4 What You May Need to Know

37.9.4.1 You Can Use Parent Classes and Interfaces to Work with Extended Components

Since an extended component is a customized version of its parent, code you write that works with the parent component's Java classes or its client interfaces works without incident for either the parent component or any customized version of that parent component.

For example, assume you have a base Products view object with custom Java classes and client interfaces like:

class ProductsImpl

row class ProductsRowImpl

interface Products

row interface ProductsRow

If you create a ProductsByName view object that extends Products, then you can use the base component's classes and interface to work both with Products and ProductsByName.

Example 37-19 illustrates a test client program that works with the Products, ProductsRow, ProductsByName, and ProductsByNameRow client interfaces. A few interesting things to note about the example are the following:

You can use parent Products interface for working with the ProductsByName view object that extends it.

Alternatively, you can cast an instance of the ProductsByName view object to its own more specific ProductsByName client interface.

You can test if row ProductsRow is actually an instance of the more specific ProductsByNameRow before casting it and invoking a method specific to the ProductsByNameRow interface.

37.9.4.2 Class Extends is Disabled for Extended Components

When you create an extended component, the Class Extends button on the Java page of the extended component's wizard is disabled. Additionally, in the application module editor's Java page, when you click Edit java options, the Class Extends button in the Java dialog appears disabled. This is due to the fact that JDeveloper automatically extends the appropriate class of its parent component, so it does not make sense to allow you to select a different class.

37.9.4.3 Interesting Aspects You Can Extend for Key Component Types

Entity Objects

When you create an extended entity object, you can introduce new attributes, new associations, new validators, and new custom code. You can override certain declarative aspects of existing attributes as well as overriding any method from the parent component's class.

View Objects

When you create an extended view object, you can introduce new attributes, new view links, new bind variables, and new custom code. You can override certain declarative aspects of existing attributes as well as overriding any method from the parent component's class.

Application Modules

When you create an extended application module, you can introduce new view object instances or new nested application module instance and new custom code. You can also override any method from the parent component's class.

When you create an extended view object like ProductsByName, if that view object adds an addition attribute like SomeExtraAttr and has a custom view row class enabled, then its attribute constants will be computed relative to the maximum value of the attribute constants in the parent component:

Additional attributes would have index values of MAXATTRCONST+1, MAXATTRCONST+2, etc.

37.10 Substituting Extended Components in a Delivered Application

If you deliver packaged applications that can require on-site customization for each potential client of your solution, ADF Business Components offers a useful feature to simplify that task.

Note:

The example in this section refers to the BaseProject project and the ExtendAndSubstitute project of the AdvancedExamples workspace in the StandaloneExamples module of the Fusion Order Demo application.

All too often, on-site application customization is performed by making direct changes to the source code of the delivered application. This approach demonstrates its weaknesses whenever you deliver patches or new feature releases of your original application to your clients. Any customizations they had been applied to the base application's source code need to be painstakingly re-applied to the patched or updated version of the base application. Not only does this render the application customization a costly, ongoing maintenance expense, it can introduce subtle bugs due to human errors that occur when reapplying previous customizations to new releases.

ADF Business Components offers a superior, component-based approach to support application customization that doesn't require changing — or even having access to — the base application's source code. To customize your delivered application, your customers can:

Import one or more packages of components from the base application into a new project.

Create new components to effect the application customization, extending appropriate parent components from the base application as necessary.

When the customer runs your delivered application with a global component substitution list defined, their customized application components are used by your delivered application without changing any of its code. When you deliver a patched or updated version of the original application, their component customizations apply to the updated version the next time they restart the application without needing to re-apply any customizations.

37.10.1 How To Substitute an Extended Component

To define global component substitutions, use the Project Properties dialog in the project where you have created extended components based on the imported components from the base application.

Note:

You can only substitute a component in the base application with an extended component that inherits directly or indirectly from the base one.

To substitute an extended component:

In the Application Navigator, right-click the model project that you want to add the extended component to and choose Project Properties.

In the Project Properties dialog, select Business Components > Substitutions.

In the Substitutions page, select the base application's component in the Available list.

Select the customized, extended component to substitute in the Substitute list.

Click Add.

For example, assume that you have created the view object CustomizedProducts in a package that extends the base view object Products. To substitute the CustomizedProducts view object for the legacy Products view object, you would select these view objects as shown in Figure 37-12 to define the component substitution.

Figure 37-12 Defining Business Components Substitutions

37.10.2 What Happens When You Substitute

When you define a list of global component substitutions in a project named YourExtendsAndSubstitutesProject, the substitution list is saved in the YourExtendsAndSubstitutesProject.jpx in the root directory of the source path.

The file will contain Substitute elements as shown in Example 37-21, one for each component to be substituted.

37.10.3 How to Enable the Substituted Components in the Base Application

To have the original application use the set of substituted components, define the Java system property Factory-Substitution-List and set its value to the name of the project whose *.jpx file contains the substitution list. The value should be just the project name without any *.jpr or *.jpx extension.

Creates new extended components in a distinct package name called CustomizedProduct and CustomizedProducts

Defines a component substitution list to use the extended components.

When creating the extended components, assume that you:

Added an extra view attribute named ExtraViewAttribute to the CustomizedProducts view object.

Added a new validation rule to the CustomizedProduct entity object to enforce that the product name cannot be the letter "Q".

Overrode the getChecksum() method in the CustomizedProduct.java class to return "I am the CustomizedProduct Class".

If you define the Factory-Substitution-List Java system property set to the value ExtendsAndSubstitutes, then when you run the exact same test client class shown in Example 37-19 the output of the sample will change to reflect the use of the substituted components as shown in Example 37-22.

Example 37-22 Results of Running TestClient.java with System Property Set

Printing attribute for a row in VO 'Products'
ProdId=100
Name=Washing Machine W001
Checksum=I am the CustomizedProduct Class
ExtraViewAttribute=Extra Attr Value
The name cannot be Q!
Printing attribute for a row in VO 'ProductsById'
ProdId=119
Name=Ice Maker I012
Checksum=I am the CustomizedProduct Class
SomeExtraAttr=SomeExtraAttrValue
## Called someExtraFeature of ProductsByNameRowImpl
The name cannot be Q!

Compared to the output from Example 37-19, notice that in the presence of the factory substitution list, the Products view object in the original test program now has the additional ExtraViewAttribute, now reports a Checksum attribute value of "I am the CustomizedProduct Class", and now disallows the assignment of the product name to have the value "Q". These component behavior changes were performed without needing to modify the original Java or XML source code of the delivered components.