JDeveloper: Prevent Navigation from Field on Failed Validation

This post shows how to implement a use case where you don’t want the user to leave a field which has a validation error. ADF does a good job enforcing that all validations are checked at the time you submit the data. However, if you want the user to correct an error in a field directly, you have to implement it yourself.

Use Case

A validation error can be a mandatory field which the user has not filled in or a where the user has filled in wrong data. In such a case you want that the user must correct the error before she/he is allowed to move to the next field.


We start with a fragment whihc holds two af:inputText components. One we use to simulate a mandatory input text and the other for a normal input text field.


The ‘Test’ button is used to submit the form. If we hit the Test button without any data in the fields we get


as hte ID field is marks required. One you enter something into this field you can successfully submit the form


That is the normal behavior ADF gives you out of the box. The use case  we implement here requires, that the user can’t leave the field once an error is shown for the field. So if the user sets the cursor to the ID field he can’t navigate away from it until he fixes the error. He can’t even click hte button. ADF would allow the user to leave the ID field to enter some value into the Name field.

So how do we prevent the user leaving the field by clicking in another field or clicking on a button?

We use an af:clientListener which listens for the ‘blur’ event checking if the field contains a value. If not, we set the focus back to the component and cancel the ongoing even. Setting the focus back to the component is essential as the blur event tell us that we loose the focus. This only happens if the user navigates away from the field.

 function setFocusWhenValidateFail(event) {
   var element = event.getSource();
   var val = element.getValue();
   var cid = element.getClientId();
   console.log("Value=" + val);
   if (val == null) {

The JavaScript function above shows this. This function is called via an af:clientListener we added to the af:inputText component

 <af:inputText label="ID (mandatory)" id="it1" required="true" 
     value="#{bindings.myId1.inputValue}" autoSubmit="true">
   <af:clientListener method="setFocusWhenValidateFail" type="blur"/>

This is it. But wait, what if we like to check if the value entered by the user is valid?

Now, this add another complexity. For this we need to either code the validation in JavaScript or we have to call a bean method which can do the complex check on hte server side model. For easy checks it’s no problem to implement them in JavaScript in the ‘else’ part of the function above.

To call a server side method we need to add an af:serverListener which calls a bean method

 <af:inputText label="ID (mandatory)" id="it1" required="true" 
     value="#{bindings.myId1.inputValue}" autoSubmit="true">
   <af:clientListener method="setFocusWhenValidateFail" type="blur"/>
   <af:serverListener type="validateServerListener" 

and we change the JavaScript function

 function setFocusWhenValidateFail(event) {
   var element = event.getSource();
   var val = element.getValue();
   var cid = element.getClientId();
   console.log("Value=" + val);
   if (val == null) {
   else {
     console.log("call server with " + cid + " and " + val)
     //call bean method validateServerListener
     AdfCustomEvent.queue(element, "validateServerListener", 
         fcid : cid, fvalue : val
       }, false);

Note that we add two parameters to the call to the bean method. The first parameter fcid is the client id of the component which calls the bean method. The second parameter fvalue is the value the user has entered into the field. We see why we need the parameters when we talk about the bean method.

In the bean we implement the custom validateServerListener method. First we get the two parameters from the ClientEvent and log them to the console. At this point we can e.g. call an application module method with the parameter  we got. In this simple same we just check the value for a specific value, in this case ’88’. When the value is ’88’ we add a  FacesMessage to the component with the clientId we got as second parameter.

However, just adding the FacesMessage wont be enough. At this point he focus has already shifted out of the component and the message would not displayed until the component is selected again. The event.cancel() in the JavaScript function does not prevent that the focus is shifted out of the component. The solution is to reset the focus to the component from the bean again. For this we add JavaScript code which will be executed after the event has finished. The JavaScript searches for the component by it’s Id and then calls component.focus()  to set the focus back to this component.

   public void handleValidationEvent(ClientEvent ce) {
        // get client id from event
        Object obj = ce.getParameters().get("fcid");
        String clientId = "";
        if (obj != null) {
            clientId = obj.toString();

        // get field value from event     
        String val = "";
        Object obj2 = ce.getParameters().get("fvalue");
        if (obj2 != null) {
            val = obj2.toString();
        logger.info("client id =" + clientId + " value=" + val);
        // do a check if hte value if OK
        // here we check against 88 to keep it simple. You can check against other model values here too!
        if ("88".equals(val)) {
            // check failed -> add message to the component and set the focus back to the component
            FacesContext facesContext = FacesContext.getCurrentInstance();
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Wrong vlaue");
            facesContext.addMessage(clientId, msg);
            // javascript to set focus to component identified by it's clientId
            String script = "var t=document.getElementById('" + clientId + "::content');t.focus();";

    //generic, reusable helper method to call JavaScript on a client
    private void writeJavaScriptToClient(String script) {
        FacesContext fctx = FacesContext.getCurrentInstance();
        ExtendedRenderKitService erks = null;
        erks = Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
        erks.addScript(fctx, script);

Sample Application

You can download the sample application from GitHub BlogNoNavigationValidation. The sample doesn’t use a model layer, so no DB connection is needed.


Undo Reorder of Columns in af:table

A question on OTN about how to undo a reorder of columns in an af:table can be undone. In this blog I show how to undo such a reorder to show the columns of an af:table in their natural order.
The natural order is defined when you create the table. You can move the attributes in the create dialog or delete attributes you don’t want to see in the UI from the table.

In the image above we see the dialog after we drop a VO as table onto a page. To change is order of the columns in the table you can use the arrows on the right (in the red rectangle). Once you save the table you can reorder the columns in the property editor of the af:table.


The order of the columns you see in the dialog or the property editor is what is called default order of the columns. This default order can be different than the order of the attributes in the query the VO is based on.
The page we drop the af:table on is very simple. It is build from a quick layout and has a header for the page title and a panelCollection which holds the table.


We can reorder the columns in the UI by dragging a column and dropping it at a different location.

The question now is how to undo this manual reorder without refreshing the browser window.

To understand how this is implemented, we need to look how the the reorder is done in the first place. A table is build from one or more columns. Each of the columns describes the data to be shown in the column, the header to show and the display index which is the order of the columns shown in the UI. If the display index is less then zero (e.g. -1) the default order is used. Any other positive number is used to show the columns in ascending order of these display index.
To undo any reorder of the columns is an af:table we simply have to get to each column and set it’s display index to -1.

public class UndoColumnReorderBean {
    private static ADFLogger _logger = ADFLogger.createADFLogger(UndoColumnReorderBean.class);
    private RichTable table;

    public UndoColumnReorderBean() {

    public void undoColunmReorder(ActionEvent actionEvent) {
        _logger.info("Undo reorder...");
        // get the tables child components
        List<UIComponent> children = this.table.getChildren();
        for (UIComponent comp : children) {
            // check if the child is a column
            if (comp instanceof RichColumn) {
                RichColumn col = (RichColumn) comp;
                // if hte display index is greater 0 set it to -1
                if (col.getDisplayIndex() >= 0) {
                    _logger.info("...unset column "+col);
        _logger.info("... done!");

    public void setTable(RichTable table) {
        this.table = table;

    public RichTable getTable() {
        return table;

The bean above has a method undoColumnReorder which is an action event Listener triggered by clicking the ‘Undo Column Reorder’ button. This method uses the af:table component which is bound to the bean as property. It iterates over the child components of the table, checking if the child is a RichColumn (or af:column in the UI) and if yes sets its display index to -1;
To show the change in the UI, we have to ppr the table by adding the button as partial Trigger to the table


After clicking the button in the ui the table again looks like


so the default order of the columns is shown again.

You can download the application from GitHub BlogUndoColumnReorder. The sample is build using JDev but you can do the same with any other JDev version 11g or 12c you use. It uses the HR DB schema.

Reset Table Filter when Navigating to Page

This blog is a continuation of an older blog about how to reset the filters of an af:table component from a bean (How to reset a filter on an af:table the 12c way). In the older blog I described the technique to reset the filters defined in the FilterableQueryDescriptor of a filterable af:table.

Now users on OTN JDev & ADF space ask for a small variation of the use case. The filter should reset whenever a navigation takes place to the page which holds the af:table. No button should be clicked to reset the filter values.

As the original technique can still be used, I don’t go into detail about how to do this. It’s described in the other blog for JDev versions 12c. The same technique can be applied to 11g but different Java code has to be used (see How to reset a filter on an af:table). I changed the sample application, which you can download (see link at the end of the blog), so that the query panel with the af:table has an additional button to navigate to a different page.

Run through

After starting the application we see the page with an empty table as no search was done. Clicking hte search button will give us


The ‘Navigate’ button simply navigate to another view which holds twu buttons which let you navigate back to the original page.


The ‘back without clear filter’ just navigates back to the page, whereas the ‘back with clear filter’ navigates to a method in the task-flow which prepares the af:table for reset. This is the bounded task flow:


The EmpQueryPanel holds the af:query with the result table as shown in the first image. The view is marked as default activity in the task flow. When you first run the application (page RTFQPTest.jsf) the task flow is added as region to the page showing the query panel with the result table.

When you hit the search button on the page the table shows all employees. Now we can filter the results like ‘FirstName’ contain ‘s’ and ‘LastName’ contains ‘k’


Now if we hit the ‘Navigate’ button we go to the page shown in image 2 with the two buttons. If we click on hte ‘back without clear filter’ we come back to the page as shown above. The filter values are still present!

If we click on the ‘back with clear filter’ we see


so the filter values are cleared. So, how is it done?


In the original sample we had a button which we used to trigger a method which get the FilterableQueryDescriptor from the table. This descriptor holds the filter values which are cleared by looping over all ConjunctionCriterion which are the filter values. Here is the full method for 12c

 * method to reset filter attributes on an af:table
 * @param actionEvent event which triggers the method
 public void resetTableFilter12c(ActionEvent actionEvent) {
   FilterableQueryDescriptor queryDescriptor = (FilterableQueryDescriptor) getEmpTable().getFilterModel();
   if (queryDescriptor != null &amp;&amp; queryDescriptor.getFilterConjunctionCriterion() != null) {
     logger.info("Filter found...");
     ConjunctionCriterion cc = queryDescriptor.getFilterConjunctionCriterion();
     List&lt;Criterion&gt; lc = cc.getCriterionList();
     if (!lc.isEmpty()){
       logger.info("...iterating criterions...");
     for (Criterion c : lc) {
       if (c instanceof AttributeCriterion) {
         AttributeCriterion ac = (AttributeCriterion) c;
         Object object = ac.getValue();
         logger.info("...found " + ac.getAttribute().getName() + " value: " + object);
         if (object != null) {
getEmpTable().queueEvent(new QueryEvent(getEmpTable(), queryDescriptor));

public void setEmpTable(RichTable empTable) {
 this.empTable = empTable;

public RichTable getEmpTable() {
 return empTable;

A look into the log after clicking hte ‘back with clear flter’ shows


We see that the for loop caught all filters and resetted every filter to null.

The interesting part is how we triggered the call of the method resetTableFilter12c. As there is no button or other action event involved we use a trick. We add a method to the ‘ShortDesc’ property of the af:table which points to a bean method


Now, whenever the af:table is rendered it goes to the bean method asking for the test for hte short description. We use the call of this method as trigger to reset the filters. As this method is called multiple times during the JSF lifecycle, we need some kind of flag which tells us that the reset operation is done already. Otherwise we will spende lots of time calling the reset method without need.

public void setShortDescription(String shortDescritopn) {
logger.info("Set ShortDescription called");
this.shortDescription = shortDescritopn;

public String getShortDescription() {
logger.info("get ShortDescription called");
AdfFacesContext adfFacesCtx = AdfFacesContext.getCurrentInstance();

// get the PageFlowScope Params
Map<String, Object> scopePageFlowScopeVar = adfFacesCtx.getPageFlowScope();
Boolean reset = (Boolean) scopePageFlowScopeVar.getOrDefault("resetFilter", Boolean.FALSE);
boolean flip = reset.booleanValue();
if (flip) {
logger.info("ResetTable Filter!");
scopePageFlowScopeVar.put("resetFilter", Boolean.FALSE);
logger.info("Unset filter reset flag!");

return shortDescription;

As there are cases where the short description is ask for which we don’t want to use as triggers to clear the filters, we need another flag which we can check. For this we set a flag in the pageFlowScope of hte bounded task flow named ‘resetFilter’.  in the method we get the pageFlowScope and read the flag (lines 8-13). Only when the flag is set to true in the pageFlowScope we call theresetTableFilter12c method (line 14-19) and reset the flag to false.

The only thing left to do is to set the flag in the pageFlowScope when we liek the filters to get cleared when navigating to the page. For this we use the method action ‘resetTableFilter’ which is defined in the task flow. This method action points to a bean method


which puts the flag ‘resetFilter’ with a value of ‘Boolean.TRUE’ into the pageFlowScope:

public void setRestFlag() {
AdfFacesContext adfFacesCtx = AdfFacesContext.getCurrentInstance();
// get the PageFlowScope Params
Map<String, Object> scopePageFlowScopeVar = adfFacesCtx.getPageFlowScope();
scopePageFlowScopeVar.put("resetFilter", Boolean.TRUE);
logger.info("Set filter reset flag!");


You can download the sample application from GitHub:  BlogResetTableFilter12c

The sample uses JDev and the HR DB schema.

Naviagting an af:table in pagination mode from a bean

A question on the JDeveloper and ADF OTN forum asked about how to navigate to a specific page of an af:table in pagination mode. As of JDeveloper adf tables can be rendered in scroll mode or in pagination mode where only a specific number of rows are visible in the table.

af:table in pagination mode

To navigate the pages there is a small navigation toolbar below the table which allows to enter a page number or to navigate to the previous, next, first or last page.

The problem to solve is how to navigate the paginated table from within a java bean?

The table doesn’t offer any navigation listeners or methods you can bind bean methods to. Luckily there is the RangeChangeEvent one of the FacesEvents which can e used to notify a component that change in the range has taken place.

All we have to do to navigate the table in pagination mode is to calculate the needed parameters

  • oldStart: The previous start of this UIComponent’s selected range, inclusive
  • oldEnd: The previous end of this UIComponent’s selected range, exclusive
  • newStart: The new start of this UIComponent’s selected range, inclusive
  • newEnd: The new end of this UIComponent’s selected range, exclusive

We add an input field to the page which allow us to enter a page number and a button which we use to call an action listener in a bean.

The running application looks like

Running application

Another button is used to calculate the index of the selected row in the whole rowset, the index on the page and the page number. The row index and the index of the row on the page are zero based, page numbers start with 1. Let’s look at the code:

public void onGotoPage(ActionEvent actionEvent) {
BindingContainer bindingContainer = BindingContext.getCurrent().getCurrentBindingsEntry();
// get number of page to goto
AttributeBinding attr = (AttributeBinding) bindingContainer.getControlBinding("gotopage1");
Integer newPage = (Integer) attr.getInputValue();
if (newPage == null) {
// page one starts at index 0 so subtract 1 from the pagen number
DCIteratorBinding iter = (DCIteratorBinding) bindingContainer.get("EmployeesView1Iterator");
// calculate the old and new rages for the RangeChangeEvent
int range = iter.getRangeSize(); // note both the table and we take the page size from the iterator's RangeSize
int oldStart = iter.getRangeStart();
int oldEnd = oldStart + range;
int newStart = newPage * range;
int newEnd = newStart + range;
// find the table
UIViewRoot iViewRoot = FacesContext.getCurrentInstance().getViewRoot();
UIComponent table = iViewRoot.findComponent("t1");
// build the event and fire it
RangeChangeEvent event = new RangeChangeEvent(table, oldStart, oldEnd, newStart, newEnd);
// update the table

Line 2-8 we get the new page number we want to navigate to. Line 9-10 we subtract 1 from the given number as the page is zero based internally. In Line 11 we get the iterator which we need to get the range size and the start of the current range (lines 13-15). These values are oldStart and oldEnd. Lines 16-17 we calculate the new start range as page to go multiplied with the range. The newEnd parameter is the newStart pus the range size.
In lines 18-20 we get to the table component on the page. Then we create the RangeChangeEvent and broadcast the event to the table component in lines 21-23. Finally we ppr the table to see the change in the UI.

To show how to calculate the other way around, to get from the selected row in a table to the index on the page, the page number and the index in the rowset we added another button ‘GetPageOfSelectedRow’which calls a listener in the same bean which builds a string with the needed information.

public void onGetCurrentPage(ActionEvent actionEvent) {
BindingContainer bindingContainer = BindingContext.getCurrent().getCurrentBindingsEntry();
DCIteratorBinding iter = (DCIteratorBinding) bindingContainer.get("EmployeesView1Iterator");
// calculate index and page number. Index is zero based!
int currentRowIndex = iter.getRowSetIterator().getCurrentRowIndex();
_logger.info("CurrentRowIndex: " + currentRowIndex);
int currentPage = currentRowIndex / iter.getRangeSize();
_logger.info("Current Page:" + currentPage);
int indexOnPage = (currentRowIndex % iter.getRangeSize());
_logger.info("Current index on Page:" + indexOnPage);
// get an ADF attributevalue from the ADF page definitions
AttributeBinding attr = (AttributeBinding) bindingContainer.getControlBinding("selectedRow1");
StringBuffer sb = new StringBuffer();
sb.append("row index overall: ");
sb.append(" row index on page: ");
sb.append(" Page: ");

To get the index of the selected row in the whole rowset we need the iterator and get the RowSetIterator from it. The rowSetIterator method getCurrentRowIndex() returns the index of the current row (line 5). The current page is calculated by dividing the current index through the range size (line 7). The final information is the index of the selected row on the page which is calculated as the current index modulo the range size (line 10). The rest of the listener build a string out of this information and writes it to a pageDef variable which is referenced in an outputfield on the page.

<af:outputText value="#{bindings.selectedRow1.inputValue}" id="ot8" partialTriggers="b2"/>

Here are some images from the sample application.

The sample application is build using JDev 12.1.3 and uses the HR DB schema. The sample can be downloaded from  Github

JDev 12.2.1: Remote Task Flows in Action

The new JDeveloper version 12.2.1 is just out and has a lot of new features to investigate. In this post we see how remote task flows work. Yes, they are finally here and they are working. At least if you install a patch available from support.oracle.com.
The downloadable version on JDev 12.2.1 has a small bug which prevents you from running remote task flows (refer to https://community.oracle.com/thread/3816032). Support and the dev team quickly delivered a patch for this. To get the patch, open a service request and ask for a patch for bug 22132843.

Let’s start. We need two applications to show how remote task flows are implmented. One is the remote task flow producer, one consumes the remote task flow. An application can be both, producer and consumer. For this sample we keep it simple and define one app as producer and one as consumer.

Producer Application
This application is really simple as it consists of only one page and one task flow which shows the departments and its employees of the HR DB schema.

Remote Task Flow Producer Application

Remote Task Flow Producer Application

The image above shows the running application stand alone. The single page has the header and a simple task flow beneath it to show the departments and their employees.

There are two properties to set in the task flow.
1) in must be remote invocable
2) the transaction must be isolated

Next we have to make the application aware that it should be a remote task flow producer. For this we edit the projects properties and select the ‘ADF Task Flow’ node.

Project Properties for Producer Application

Project Properties for Producer Application

Please note is the second checkbox selected which allows anonymous users to access the remote task flow. This should not be used in a production environment as this would allow anybody to access the task flow. The doc shows how to secure the access to a remote task flow (see link below).

These settings will add a special servlet and a servlet filter to the web.xml file of the application.

There are more things to consider which you find in the docs at How to Configure an Application to Render Remote Regions

That’s it for the simple producer application.

Consumer Application
The second application is simple too. Here we use a single page which again uses the HR DB schema to show the departments as an editable table in a panel splitter. On the right of this we show the remote task flow of the producer application.

Consumer Application

Consumer Application

In the image above the remote task flow isn’t visible as it is not added at the moment.
To make the remote task flow available we need to run the producer application. Here we have to be careful if we try this out using the embedded WebLogic Server. As only one application can be started in debug mode, we need to start the producer application as a normal application.
Run Producer Application

Run Producer Application

In the consumer application we set the project properties for the ADF Task Flow to allow it to consume remote task flows

Consumer Application Project Properties

Consumer Application Project Properties

Now we create a remote task flow connection. Open the resource palette and select to create a ‘Remote Region Producer…’ from the IDE connections.
Here we fill in the needed info like the path to the remote producer servlet which will get us the names of all remote task flows the application holds. To access the remote task flow we define the URL endpoint

The details about what to fill in are again from the doc.

In the consumer application we now open the one page and drag the remote task flow from the ressource palette onto the page and drop it in the right hand splitter

Drop Remote Region in Consumer Application

Drop Remote Region in Consumer Application

This will give us the known image in design mode as if you use a normal region
Consumer Page

Consumer Page

We are ready to run the consumer application and get
Running Consumer Application

Running Consumer Application


You can download the sample application from GitHub:
Consumer Application
Producer Application
Both application use the HR DB schema. Make sure to adjust the DB connection to point to your db server.

dvt:treemap showing node detail in popup

This post describes how to implement an dvt:treemap which shows a af:popup when the user clicks on a detail node in the map.
The documentation of the dvt:treemap component tell us that the dvt:treemapnode supports the af:showPopupBehaviortag and reacts on the ‘click’ and ‘mouseHover’ events.
This is part of the solution and allows us to begin implementing the use case. We add an af:showPopupBehavior to the nodes we want to show detail information for.

After creating a default Fusion Web Application which uses the HR DB schema, we begin with creating the data model for the model project. For this small sample the departments and employees tables will be sufficient.

The views are named according to their usage to make it easier to understand the model. This is all we need for the model.

Let’s start with the UI which only consist of a single page. The page has a header part and a center part. In the center area we build the treemap by dragging the Departments from the data controls onto the page and dropping it as treemap. After that, in the dialog we specify the first level of the map to be the departmentId (which shows the department name as the label) and the for the second level we choose the employeeId (which shows the last name of the employee as label) from the employees. The whole process is shown in the gallery below.

The resulting treemap is very basic in it’s features, e.g. there is no legend as you see later.
In the next step we create an af:popup to show the nodes detail information. This process is outlined in the next gallery. We drag the popup component onto the page below the af:treemap component

One thing to take note of are the properties of the popup. First we set the content delivery to ‘lazyUncached’, which makes sure that the data is loaded every time the popup is opened. Otherwise we’ll see only the data from the first time the popup has been opened. Second change is to set the launcherVar to ‘source’. This is the variable name we later use to access the node data. Third change is to set the event context to ‘launcher’. This means that events delivered by the popup and its descendents are delivered in the context of the launch source.

The treemap for example, when an event is delivered ‘in context’ then the data for the node clicked is made ‘current’ before the event listener is called, so if getRowData() is called on the collectionModel in the event listener it will return the data of the node that triggered the event. This is exactly what we need.

Finally we add a popupFetchListener to the popup which we use to get the data from the current node to a variable in the bindings. In the sample this variable ‘nodeInfo’ is defined in the variable iterator of the page and an attribute binding ‘nodeInfo1’ is added. More info on this can be found here.

The code below shows the popupFetchListener:

package de.hahn.blog.treemappopup.view.beans;

import javax.el.ELContext;
import javax.el.ExpressionFactory;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;

import oracle.adf.model.BindingContext;
import oracle.adf.share.logging.ADFLogger;
import oracle.adf.view.rich.event.PopupFetchEvent;

import oracle.binding.AttributeBinding;
import oracle.binding.BindingContainer;

 * Treemap handler bean
 * @author Timo Hahn
public class TreemapBean {
    private static ADFLogger logger = ADFLogger.createADFLogger(TreemapBean.class);

    public TreemapBean() {

     * listen to popup fetch.
     * @param popupFetchEvent event triggerd the fetch
    public void fetchListener(PopupFetchEvent popupFetchEvent) {
        // retrieve node information 
        String lastName = (String) getValueFromExpression("#{source.currentRowData.lastName}");
        Integer id = (Integer) getValueFromExpression("#{source.currentRowData.EmployeeId}");
        //build info string
        String res = lastName + " id: " + id;
        logger.info("Information: " + res);
        // get the binding container
        BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();

        // get an ADF attributevalue from the ADF page definitions
        AttributeBinding attr = (AttributeBinding) bindings.getControlBinding("nodeInfo1");
        //set the value to it

    // get a value as object from an expression
    private Object getValueFromExpression(String name) {
        FacesContext facesCtx = FacesContext.getCurrentInstance();
        Application app = facesCtx.getApplication();
        ExpressionFactory elFactory = app.getExpressionFactory();
        ELContext elContext = facesCtx.getELContext();
        Object obj = elFactory.createValueExpression(elContext, name, Object.class).getValue(elContext);
        return obj;

Finally we have to design the popup to show the node info from the attribute binding ‘nodeInfo1’. The popup uses a dialog with an af:outputText like

Show the node info in the popup

Show the node info in the popup

and set an af:showPopupBehavior to the node showing the employees

Running the finished application brings up the treemap, not pretty but enough to see this use case working. If we click on an employee node we see the popup with the last name of the employee and the employee id, the primary key of the selected row in the employees iterator.

You can download the sample application which was build using JDeveloper 12.1.3 and the HR DB schema from GitHub.

Master/Detail using af:tree for master and af:form for detail

A question on OTN JDeveloper and ADF forum about a sample for a master/detail navigation using a tree as master and a form as detail cought my attention. I quickly setup a sample I like to share in this post.

Frank Nimphius wrote an article How-to select multiple parent table rows and synchronize a detail table with the combined resul about this which is quite complex as it not only shows how the synchronization is done but adds CRUD operation to the tree too.
My sample is for beginners and only shows how to do the synchronization of the tree navigation and the detail from. If you need more functionality please refer to Frank’s article.

Problem description
At first the use case sounds easy. However, using a tree has it’s pitfalls. The tree navigation doesn’t synchronize the child node iterators with the node selection. This means that when we select a child node that the current row of the child iterator is not set to the selected row. This is shown in the gallery below:

As we see, in the second picture the form show the wrong data for the selected node. The form shows the first child row of the selected parent node.

Page layout
the sample uses a panel splitter which holds the af:tree on the left and the detail af:form on the right panel. This is shown in the gallery below:

The af:form has a partialTrigger set which listens to updates of the af:tree. The af:tree was build by dragging the Departments from the data control onto the left panel of the splitter. This created the markup
Default selectionListener of af:tree

Default selectionListener of af:tree

with the default selectionListener marked in blue. This is where we need to make the change.

To make the use case work, we have to use a custom selectionListener for the af:tree. The gallery below shows how a request scoped bean and the selectionListener is created:

The last image shows that the bean is automatically registered in the task flow (in adfc-config.xml in this case).
Now that we have created the selectionListener method in the bean, we can code it like

     * Custom managed bean method that takes a SelectEvent input argument
     * to generically set the current row corresponding to the selected row
     * in the tree.
     * This method is not generic as it uses the normal binding.iterator.model.makecurrent the ui component uses.
     * The child iterator must be known too to select the child not in the chile view.
     * @param selectionEvent object passed in by ADF Faces when configuring
     * this method to become the selection listener
    public void onTreeNodeSelection(SelectionEvent selectionEvent) {
        //original selection listener set by ADF
        String adfSelectionListener = "#{bindings.Departments.treeModel.makeCurrent}";
        //make sure the default selection listener functionality is
        //preserved. you don't need to do this for multi select trees
        //as the ADF binding only supports single current row selection

        FacesContext fctx = FacesContext.getCurrentInstance();
        Application application = fctx.getApplication();
        ELContext elCtx = fctx.getELContext();
        ExpressionFactory exprFactory = application.getExpressionFactory();

        MethodExpression me = null;
        me = exprFactory.createMethodExpression(elCtx, adfSelectionListener, Object.class, new Class[] { SelectionEvent.class });
        me.invoke(elCtx, new Object[] { selectionEvent });

        RichTree tree = (RichTree)selectionEvent.getSource();
        TreeModel model = (TreeModel)tree.getValue();

        //get selected nodes
        RowKeySet rowKeySet = selectionEvent.getAddedSet();
        Iterator<Object> rksIterator = (Iterator<Object>)rowKeySet.iterator();
        //for single select configurations,this only is called once
        while (rksIterator.hasNext()) {
            List<Object> key = (List<Object>)rksIterator.next();
            JUCtrlHierBinding treeBinding = null;
            CollectionModel collectionModel = (CollectionModel)tree.getValue();
            treeBinding = (JUCtrlHierBinding)collectionModel.getWrappedData();
            JUCtrlHierNodeBinding nodeBinding = null;
            nodeBinding = treeBinding.findNodeByKeyPath(key);
            Row rw = nodeBinding.getRow();
            //print first row attribute. Note that in a tree you have to
            //determine the node type if you want to select node attributes
            //by name and not index
            String rowType = rw.getStructureDef().getDefName();

            // check the node type as we don'T have to do anything is the parent node is selected
            if (rowType.equalsIgnoreCase("DepartmentsView")) {
                logger.info("This row is a department: " + rw.getAttribute("DepartmentId"));
            } else if (rowType.equalsIgnoreCase("EmployeesView")) {
                // for the child node we search the row which was selected in the tree
                logger.info("This row is an employee: " + rw.getAttribute("EmployeeId"));
                Object attribute = rw.getAttribute("EmployeeId");
                // make the selected row the current row in the child iterator
                DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
                DCIteratorBinding iterBind = (DCIteratorBinding)dcBindings.get("EmployeesOfDepartmentsIterator");
            } else {
                // tif you end here your tree has more then two node types
            // ... do more useful stuff here

Line 15 holds the original selectionListener expression from the af:tree. This we need to select the master node and row.
Lines 16-30 preserve the original function by executing the expression.
lines 31-38 check if there are selected nodes in the tree. Here we have to remember that a selected node in a tree isn’t just a rowKey the selectionListener always returns a set of nodes. If the tree is set to single selection the set contains exactly one node.
lines 39-49 get the data model of the tree and getting the node data (or row) and it’s type. This type we use to distinguish between master and detail selection.
Lines 51-65 do exactly this. In case of a master node (Departments) there is nothing to do as the default iterator does all the work. In case of a detail node (Employees) we have to do the magic.
Lines 54-61 Here we get the PK of the child row from the node and set the current row in the child iterator to this row (line 61).

That’s it. when we now run the application we see that the detail form synchronizes with the selected node in the tree.

The sample needs the HR DB schema. You can download the code for the sample, which was build using JDeveloper, from GitHub. Please note that if you run the sample in your environment, that you have to change the DB connection to the HR DB schema according to your environment.

The Git Experience (Part 4)

In this part of the ‘Git Experience’ series we are looking at GitFlow. GitFlow is a branching model which helps you and your company to structure your work in a way which is understandable and has proven it’s value in many projects. I don’t want to copy all information given in the link about GitFolw but only use the image from the blog post:

GitFlow Model

GitFlow Model

What we see in this image is a timeline of development with releases, hot fixes, development and feature branches and how they work together. We like to use this model to structure the work of the development. The development needs to set up the software for releases which are delivered to the customer or an internal server. Then there is the need to supply hot fixes if a release version has a major bug. Nevertheless development has to develop for the next release, probably breaking the task into smaller pieces we call features. To keep this features in our repository as well we use feature branches which are merged back to the development branch once they are ready and tested.

The development branch is the grapevine for the development. Feature branches as well as release branches are started from the development branch. Once a release is ready the release branch is merged and tagged on the master branch and merged to the development branch.

IMPORTANT: you never work directly on the master branch!

In the last part ‘The Git Experience (Part 3)’ we started a new repository on GitHub which we use in this part to introduce GitFlow on it. There are several ways to do this. You can use the command line and execute the git commands from there. Or you use shell scripts to put multiple git commands as a unit of work together and call the script to e.g. start a new feature branch. The last and least complicated way is to use a tool which already has set up the scripts for you and gives you a nice GUI to work with.

We follow the last suggested way and use a tool with graphical user interface. As JDeveloper does not support the usage of GitFlow with a GUI we use an external tool like ‘SmartGit’ or ‘Source Tree’ which both come with a graphical user interface supporting GitFlow. For the remainder of this blog we use SmartGit as it’s available for Windows and Linux operating systems. It’s free for non commercial use.

Once we started SmartGit we can add our local repository to be shown in SmartGit. Don’t be confused this with cloning a repository. Cloning fetches a remote repository from a remote server and creates a local copy of it on your pc. As we already have the local repository on out machines we just add the local repository.

For those of you how did not create the repository in the last part you can clone it from my GitHub server repository using ‘https://github.com/tompeez/BlogReadConfigFile.git&#8217; as url for the clone command.

After this SmartGit looks the same as the last image after adding the repository. You now can play with the SmartGit UI (or any other too you are using). One thing I like to bring to attention is the ‘Log’ button. Clicking this button opens a new window which shows the timeline of all commits.

Right now we only see two nodes which were created during creation of the repository.

Let the fun begin: Introduce GitFlow to the project

Now that the local repository is up in the tool of choise, lets introduce GitFlow to it. For this we click the GitFlow Button, select the ‘Full’ radio button and leave the rest of the options as is.

This will add another branch to the repository named ‘develop’

Repository after GitFlow Introduction

Repository after GitFlow Introduction

However, this  new branch is not the current branch as the ‘master’ branch is still marked current. Please also note the different color of the GitFlow button. In this shape it starts a HotFix as the master branch is the current branch and all hot fixes are started from the master branch, or better a release tag on the master branch.

GitFlow Button: Start HotFix

GitFlow Button: Start HotFix

We change this by double clicking the develop branch to get

and see the GitFlow button changes to a different default action, ‘Start Feature’ as we are now working on the develop branch. Before we start our first feature we take a look at the GitHub remote repository:

GitHub Timeline

GitHub Timeline

As we see the remote repository still only have one branch ‘master’. This is a lesson we have to learn fast. Everything we do, we do only locally. The remote repository doesn’t know about our work until we tell about it or push our changes to the remote repository.

Let’s push the ‘develop’ branch to the remote repository by clicking the Push button

Last thing to do is to do some house keeping on the GitHub side. Here we set the ‘develop’ Branch as ‘default’ branch.

Now we are ready to start our first feature. Remember that the feature branch is only created on the local repository and not automatically pushed to the remote GitHub repository. If you like the feature branch to be visible in the remote repository you have to push it there after creating it.

We create a feature ‘Feature_1’ (you should choose a more meaningful name!):

As we see the new branch is the current working branch. We now make some changes e.g. adding a header above the table and then look at the changes in the SmartGit and GitHub UI.

We add a panelGroupLayout to the top facet of the panelStretchLayout to add a header telling us what we see and another text telling that this was added with ‘Feature-1’. This is just for the time we are playing with the GitFlow features. We later can safely remove this second text.

As we see, all tools showing the same changed files. The interesting thing is that we see a changed index.java file. The only change we made was to add something to the index.jsf file!

Well, this second change was not intended but is the result of a setting in JDeveloper which adds a property to a backing bean for every component we add to the index.jsf file. Before we remove this nonsense setting let’s save the changes to our repository and look at the different tools:

In the first image we see an interesting info: ‘Outgoing (1)’. This means that SmartGit knows that this branch isn’t connected to the remote repository and can’t seen there. This isn’t really necessary as Git is a distributed version control system, but other users can’t get to this branch if the PC holding it isn’t available (due to network restrictions or because it’s offline).

After this the new branch is visible and tracked in GitHub. Now we can remove the not needed nor wanted index.java backing bean.

Why is it there in the first place?

If we create a new view in a task flow we have the option to activate the automatic component binding to a backing bean in this dialog

Automatic Component Binding

Automatic Component Binding

Well, it’s either a bug in JDev 12.1.3 or a saved configuration I made to investigate something else which uses automatic component binding. Les’s assume the latter and remove this setting.

Now we have to remove line 76 in the index.jsf file, fix the bindings in index.jsf by replacing them (find: binding=\”#{backingBeanScope.backing_index..*\”), remove the bean from adfc-config.xml and finally remove the index.java file from the project

Now we can compile the source, test the application and then save the changes in the repository. Don’t forget to push the changes to the remote repository!

If you use SmartGit to commit the changes you can commit and push in one command by clicking the ‘Commit & Push’ button in the dialog. The final timeline in SmartGit looks like

SmartGit Timeline

SmartGit Timeline

Time to wrap everything up. We made some changes and now are finished with our feature. We now finish the feature in SmartGit by clicking the GitFlow button and follow the dialog

The second image shows the options we have to finish a feature. Here we can decide to remove the feature branch completely or, as we do, keep it for later. As features are not used by GitFlow to build a release or hot fix on them, there is generally no need to keep them after they are finished and merged back into the development branch.

The final thing to make the circle is to build a release from the current development branch.

We add a release note part to the README.MD file to make the release visible in the file too. Now we commit the change (not shown) and finish the release

In image 2 we can set the options we want to use to finish the release. The one we change from the default is that we like to keep the release branch so that we can see it in the timeline. This is not necessary as you can’t do anything with the branch (beside cherry picking :)). The last image shows the SmartGit timeline where we see all commits and the different branches used. This show look like the GitFlow image we started this blog with.

This finishes part 4 of the blog. The repository (and it’s branches) and be cloned or loaded from GitHub.