Monday, 19 August 2013

BI Publisher Discoverer integration

BI Publisher Discoverer integration


I shall talk a bit about the benefits of the integration between BI Publisher and Discoverer in the 10.1.3.3 release, and how that shall be of interest to people who want to create reports with more adhoc layouts than are possible with Discoverer, among other benefits.

The first: Discoverer
Discoverer is a BI tool used for adhoc querying, analysis, and reporting of data. It can report against relational as well as Oracle OLAP data sources. It has tens of thousands of customers, and it’s a fine product thank you. You can read more about Discoverer on this blog as well as on OTN.
To begin to cut to the chase, there are two primary enhancements that Discoverer customers have been asking for some time (there are more, but I am picking these two):
1. The limited flexibility when it comes to laying out your Discoverer worksheets. You get a title view, a text area view (basically a title view but at the bottom), a graph, and one table or one pivot table (crosstab). And you can position the graph above, below, to the left, or to the right of the table component.

or

or


or

Now, for adhoc analysis and for many other purposes these layouts are adequate. But sometimes people have felt the need to lay out these views in a more flexible manner.

2. You can schedule a Discoverer worksheet (or worksheets). You can view the results of these scheduled worksheets. You can export a scheduled worksheet. You can email a scheduled worksheet (using Discoverer Viewer). What you cannot do is do all of this in a non-interactive manner. i.e. you cannot tell Discoverer to run a worksheet at a specified date and time, export the results into PDF or XLS, etc..., and then email these results via email to designated people.


The Discoverer Scheduling Manager.


My scheduled Discoverer worksheet in Discoverer Viewer.


This is the scheduled Discoverer worksheet in Viewer.

And this is the email page that I can use to email the scheduled Discoverer worksheet to multiple users, as an attachment (XLS, PDF, HTML, etc...)

The second: BI Publisher (formerly known as XML Publisher) BI Publisher is the enterprise reporting and document creation product from Oracle, and now also part of BI EE. Apart from the millions of uses of BI Publisher, the ones that are pertinent to this post are the ability of BI Publisher to let users create highly formatted reports, schedule them, and have them delivered to a variety of destinations, including email, printer, FTP, WebDAV, etc...

The third: Better Together - what happens when you bring Discoverer and BI Publisher together? No... not a third product, but syncretism! In BI EE 10.1.3.2 BI Publisher was enhanced to let it access Answers based data sources to allow users to create pixel-perfect reports. In BI Publisher 10.1.3.3 this functionality has been logically extended to allow Discoverer data sources – specifically worksheets – to act as data sources to BI Publisher. For this purpose, there were enhancements in both Discoverer and BI Publisher. SOAP web services have been added to Discoverer, for the first time, to expose some functionality of Discoverer that can then be called by programs using these web services. BI Publisher was enhanced to let it recognize and handle Discoverer as a data source.

Therefore, now you can take Discoverer worksheets like this:


And build nice looking reports like this:





- all using the wonder of BI Publisher.
These reports can also be scheduled to run and have the content distributed to users via email (other supported destinations include FTP, WebDAV, Printer, etc...).

And you can use the BI Publisher Template Builder for Microsoft Word to format and layout these reports:


That's the real quick introduction to Discoverer and BI Publisher integration.


Please click on below links for more info

http://bi.abhinavagarwal.net/2007/08/bi-publisher-discoverer-integration-2.html
http://bi.abhinavagarwal.net/2007/08/bi-publisher-discoverer-integration-3.html
http://bi.abhinavagarwal.net/2007/08/bi-publisher-discoverer-integration-4.html


How to split comma separated string and pass to IN clause of select statement

In some cases, we get a comma separated string as output (say from another select statement) that we would need to pass to the IN clause of a select statement.

This article explains how to achieve that using regexp_substr (DB >=10g).

For example, assume a select statement returns the following

'SMITH,ALLEN,WARD,JONES'
Now, we would need to pass this to another select statement as IN clause and get the output.

SQL> select * from emp where ename in ('SMITH,ALLEN,WARD,JONES');

no rows selected
Well, this is not our expected output. We expect the query to return 4 rows.

This can be achieved by splitting the comma separated string to individual strings and pass it to the IN clause.

Oracle provides regexp_substr function, which comes handy for this scenario.

First, we will form a query, that splits this comma separated string and gives the individual strings as rows.

SQL> select regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level) from dual
  2  connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null;


REGEXP_SUBSTR('SMITH,A
----------------------
SMITH
ALLEN
WARD
JONES
The above query iterates through the comma separated string, searches for the comma (,) and then splits the string by treating the comma as delimiter. It returns the string as a row, whenever it hits a delimiter.

We can pass this query to our select statement to get the desired output.

SQL> select * from emp where ename in (
  2  select regexp_substr('SMITH,ALLEN,WARD,JONES','[^,]+', 1, level) from dual
  3  connect by regexp_substr('SMITH,ALLEN,WARD,JONES', '[^,]+', 1, level) is not null );



     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7369 SMITH      CLERK           7902 17-DEC-80        800                    20
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30
      7521 WARD       SALESMAN        7698 22-FEB-81       1250        500         30
      7566 JONES      MANAGER         7839 02-APR-81       2975                    20
Now, the query returns what we expected.

ADF Practice

URL Task Flow Call with HTTP POST Method

As we know a bounded task flow can be invoked by some URL either directly from a browser or from some external application. This feature is enabled if task flow's property "URL invoke" is set to "url-invoke-allowed" and it is commonly used in integration projects. Usually clients (or invokers) use HTTP GET method and pass their parameters in the URL. Let's consider some simple task flow with one required input parameter:
  1.   <task-flow-definition id="task-flow-definition">      
  2.     <input-parameter-definition id="__23">  
  3.       <name id="__24">userName</name>  
  4.       <value id="__67">#{requestScope.userName}</value>  
  5.       <class id="__63">java.lang.String</class>  
  6.       <required/>  
  7.     </input-parameter-definition>      
  8.     ...  
 The task flow can be invoked by the URL like this

  1. http://127.0.0.1:7101/TestApp/faces/adf.task-flow?adf.tfId=task-flow-definition&adf.tfDoc=/WEB-INF/task-flow-definition.xml&userName=xammer  

The client uses a simple html form to construct this GET request:

  1. <html>  
  2.   <head>      
  3.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
  4.   </head>  
  5.   <body>  
  6.    <form action="http://127.0.0.1:7101/TestApp/faces/adf.task-flow">  
  7.    <input type="hidden" name="adf.tfId" value="task-flow-definition"/>    
  8.    <input type="hidden" name="adf.tfDoc" value="/WEB-INF/task-flow-definition.xml"/>    
  9.    <label>       
  10.         User Name   
  11.       <input type="text" name="userName" value="xammer"/>    
  12.    </label>  
  13.       <input type="submit" value="Submit"/>  
  14.     </form>  
  15.     </body>  
  16. </html>   

And it looks like this:

Everything is ok. So far. It works fine for R1 and for R2 as well.
Some clients prefer to use HTTP POST method, and moreover this is their requirement:

  1. <html>  
  2.   <head>      
  3.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>  
  4.   </head>  
  5.   <body>  
  6.    <form action="http://127.0.0.1:7101/TestApp/faces/adf.task-flow" method="POST">  
  7.    <input type="hidden" name="adf.tfId" value="task-flow-definition"/>    
  8.    <input type="hidden" name="adf.tfDoc" value="/WEB-INF/task-flow-definition.xml"/>    
  9.    <label>       
  10.         User Name   
  11.       <input type="text" name="userName" value="xammer"/>    
  12.    </label>  
  13.       <input type="submit" value="Submit"/>  
  14.    </form>  
  15.    </body>  
  16. </html>   
  17.   
  18.     
And it works fine as well. The URL in this case is going to look like this:

  1. http://127.0.0.1:7101/TestApp/faces/adf.task-flow  

All other necessary information like task flow id and parameter value is inside POST request. But the problem is that it works fine for R1 only. If we try it out on R2 we will get the following:

ADF_FACES-30179:For more information, please see the server's error log for an entry beginning with: The UIViewRoot is null. Fatal exception during PhaseId: RESTORE_VIEW 1.

Why? Because of that:

  1. oracle.adfinternal.controller.application.InvokeTaskFlowException: ADFC-02006: A task flow ID is not found in the URL.  
  2.     at oracle.adfinternal.controller.util.UrlParams.getTaskFlowInfo(UrlParams.java:144)  
  3.     at oracle.adfinternal.controller.application.RemoteTaskFlowCallRequestHandler.invokeTaskFlowByUrl(RemoteTaskFlowCallRequestHandler.java:84)  
  4.     at oracle.adfinternal.controller.application.RemoteTaskFlowCallRequestHandler.doCreateView(RemoteTaskFlowCallRequestHandler.java:63)  

All necessary data included task flow id which is supposed to be passed inside POST request is lost. Why?  Because of "loopback". If we discover requests sent from the browser to the server on clicking the Submit button we'll see the following:

Instead of one we have two requests. And the first one (POST) is ours. Exploring the response for this request we can see the following:


 So, instead of sending the "honest" response, the server sends some "loopback" script which generates "window id" and sends the following GET request with generated window id. Cool! But all post data is gone. The GET request is absolutely empty.
Fortunately, the framework doesn't generate any "loopbacks" if the initial POST request has already some "window id". So, the workaround for our case is to develop a servlet filter, setting the "window id" attribute for our request:
  1. public void doFilter(ServletRequest servletRequest,  
  2.                      ServletResponse servletResponse,  
  3.                      FilterChain filterChain)  
  4.   throws IOException, ServletException  
  5. {  
  6.   HttpServletRequest r = (HttpServletRequest) servletRequest;  
  7.   HttpSession s = r.getSession();  
  8.     
  9.   //May be this is not an initial request and window id has been generated earlier  
  10.   //We want all the following requests to work with the same window id   
  11.   //For our use-case this is ok      
  12.   String windowID = (String) s.getAttribute(_WINDOW_ID_KEY);  
  13.   if (windowID == null)  
  14.   {  
  15.     String pathInfo = r.getPathInfo();  
  16.     //This is an initial POST request to get access to the task flow  
  17.     if (("/adf.task-flow").equals(pathInfo) &&  
  18.         "POST".equals(r.getMethod()))  
  19.     {  
  20.       windowID = WINDOW_ID;  
  21.       //Save window id in the session   
  22.       s.setAttribute(_WINDOW_ID_KEY, windowID);  
  23.     }  
  24.   
  25.   }  
  26.   
  27.   //Setup attribute for the request  
  28.   //This will prevent generating of the loopback  
  29.   if (windowID != null)  
  30.     r.setAttribute(_WINDOW_ID_KEY, windowID);  
  31.   
  32.   filterChain.doFilter(servletRequest, servletResponse);  
  33. }  
  34.   
  35. private static final String __WINDOW_MANAGER_KEY = RichWindowManager.class.getName();  
  36. private static final String _WINDOW_ID_KEY = __WINDOW_MANAGER_KEY + "#WINDOW_ID";    
  37. private static final String WINDOW_ID = "wextflow";  

Notice, that this filter should stand before "trinidad" filter in the filter chain:
  1.   <filter>  
  2.     <filter-name>ExtPostFilter</filter-name>  
  3.     <filter-class>com.cs.fusion.core.view.filter.ExtPostFilter</filter-class>  
  4.   </filter>   
  5.   <filter>  
  6.     <filter-name>trinidad</filter-name>  
  7.     <filter-class>org.apache.myfaces.trinidad.webapp.TrinidadFilter</filter-class>  
  8.   </filter>  
  9.   <filter>  
  10.     <filter-name>ServletADFFilter</filter-name>  
  11.     <filter-class>oracle.adf.share.http.ServletADFFilter</filter-class>  
  12.   </filter> 

How to create cascading (depending) auto suggest behavior using BC4J

How to create cascading (depending) auto suggest behavior using BC4J


Let us assume a usecase where we have some text fields with auto suggest feature enabled, and their suggested items could be dependent on one other. For ex : Country, State and City.
This could be modeled by having an EO and VO created based on Person table and read-only look-up VOs created based on Country, State and City tables.
model.jpg
VOs.jpg
Implementing the dependency between LOVs is pretty straight forward. However, implementing the dependency between the auto suggest items is not. In order to achieve the dependency, first we would need couple of methods returning current row's CountryId and StateId. We could add them up in the AMImpl class.
public Number getCurrentCountryId(){
return (Number) this.getPersonView1().getCurrentRow().getAttribute("CountryId");
}

public Number getCurrentStateId(){
return (Number) this.getPersonView1().getCurrentRow().getAttribute("StateId");
}

As we need to filter out the States based on the Country and the City based on the Country & State, we would need to modify the query of these two VOs to include a bind variable in the where clause.
whereClause.jpg
For having the auto suggest, we need to have a view criteria defined for all the three look-up VOs (CountryView, StateView and CityView).

CountryVC.jpg

StateVC.jpg

CityVC.jpg

Generate VOImpl classes for Country, State and City VOs (with Include bind variable accessors option checked), and then expose setBindCountryName (in Country VO), setBindStateName (in State VO) and setBindCityName (in City VO) methods as client interfaces.
And the last part on the model is to pass the current row's CountryId and StateId to the Bind Variables defined in the State and City VOs. Also, we need to get the VCs created above to be executed by default (By editing the VO instance in the AM's data model), so that the auto suggest list would be filtered as and when the users type.
CountryViewAM.jpg

StateViewAM.jpg

CityViewAM.jpg
Here, we specify groovy expression for the CountryId and StateId as adf.object.applicationModule.<methodName>. For more information about using groovy expressions, check out this : http://www.oracle.com/technetwork/developer-tools/jdev/introduction-to-groovy-128837.pdf .
With this, we are done with setting up the model layer for the auto suggest dependency.
In the View layer, we would create an ADF Form based on the Person VO, with all the navigation buttons.
PersonJSPX.jpg
In order to construct the onSuggest items, we would create Tree Bindings for Country VO, State VO and City VO, along with method action bindings for the setBindCountryName, setBindStateName and setBindCityName methods.

pagedef.jpg

Now, we could add af:autoSuggestBehavior for CountryId, StateId and CityId fields. Then, add onSuggest methods in backing bean for populating the on suggest items for each fields.
onSuggest method for Country field :
public List onCountrySuggest(String searchCountryName) {
ArrayList<SelectItem> selectItems = new ArrayList<SelectItem>();

System.out.println(searchCountryName);
//get access to the binding context and binding container at runtime
BindingContext bctx = BindingContext.getCurrent();
BindingContainer bindings = bctx.getCurrentBindingsEntry();
//set the bind variable value that is used to filter the View Object
//query of the suggest list. The View Object instance has a View
//Criteria assigned
OperationBinding setVariable = (OperationBinding) bindings.get("setBind_CountryName");
setVariable.getParamsMap().put("value", searchCountryName);
setVariable.execute();
//the data in the suggest list is queried by a tree binding.
JUCtrlHierBinding hierBinding = (JUCtrlHierBinding) bindings.get("CountryView1");


//re-query the list based on the new bind variable values
hierBinding.executeQuery();

//The rangeSet, the list of queries entries, is of type
//JUCtrlValueBndingRef.
List<JUCtrlValueBindingRef> displayDataList = hierBinding.getRangeSet();

for (JUCtrlValueBindingRef displayData : displayDataList){
Row rw = displayData.getRow();
//populate the SelectItem list
selectItems.add(new SelectItem(
(Integer)rw.getAttribute("Id"),
(String)rw.getAttribute("Name")));
}

return selectItems;
}


onSuggest method for State field :

public List onStateSuggest(String searchStateName) {
ArrayList<SelectItem> selectItems = new ArrayList<SelectItem>();

System.out.println(searchStateName);
//get access to the binding context and binding container at runtime
BindingContext bctx = BindingContext.getCurrent();
BindingContainer bindings = bctx.getCurrentBindingsEntry();
//set the bind variable value that is used to filter the View Object
//query of the suggest list. The View Object instance has a View
//Criteria assigned
OperationBinding setVariable = (OperationBinding) bindings.get("setBind_StateName");
setVariable.getParamsMap().put("value", searchStateName);
setVariable.execute();
//the data in the suggest list is queried by a tree binding.
JUCtrlHierBinding hierBinding = (JUCtrlHierBinding) bindings.get("StateView1");


//re-query the list based on the new bind variable values
hierBinding.executeQuery();

//The rangeSet, the list of queries entries, is of type
//JUCtrlValueBndingRef.
List<JUCtrlValueBindingRef> displayDataList = hierBinding.getRangeSet();

for (JUCtrlValueBindingRef displayData : displayDataList){
Row rw = displayData.getRow();
//populate the SelectItem list
selectItems.add(new SelectItem(
(Integer)rw.getAttribute("Id"),
(String)rw.getAttribute("Name")));
}

return selectItems;
}

onSuggest method for City field :
public List onCitySuggest(String searchCityName) {
ArrayList<SelectItem> selectItems = new ArrayList<SelectItem>();

System.out.println(searchCityName);
//get access to the binding context and binding container at runtime
BindingContext bctx = BindingContext.getCurrent();
BindingContainer bindings = bctx.getCurrentBindingsEntry();
//set the bind variable value that is used to filter the View Object
//query of the suggest list. The View Object instance has a View
//Criteria assigned
OperationBinding setVariable = (OperationBinding) bindings.get("setBind_CityName");
setVariable.getParamsMap().put("value", searchCityName);
setVariable.execute();
//the data in the suggest list is queried by a tree binding.
JUCtrlHierBinding hierBinding = (JUCtrlHierBinding) bindings.get("CityView1");


//re-query the list based on the new bind variable values
hierBinding.executeQuery();

//The rangeSet, the list of queries entries, is of type
//JUCtrlValueBndingRef.
List<JUCtrlValueBindingRef> displayDataList = hierBinding.getRangeSet();

for (JUCtrlValueBindingRef displayData : displayDataList){
Row rw = displayData.getRow();
//populate the SelectItem list
selectItems.add(new SelectItem(
(Integer)rw.getAttribute("Id"),
(String)rw.getAttribute("Name")));
}

return selectItems;
}


Once after this, we could bind this to the af:autoSuggestBehavior's suggestedItems property
<af:inputText value="#{bindings.CountryId.inputValue}" label="#{bindings.CountryId.hints.label}"
columns="#{bindings.CountryId.hints.displayWidth}"
autoSubmit="true"
shortDesc="#{bindings.CountryId.hints.tooltip}" id="it3">
<af:autoSuggestBehavior suggestedItems="#{viewScope.AutoSuggestBean.onCountrySuggest}"/>
</af:inputText>
<af:inputText value="#{bindings.StateId.inputValue}" label="#{bindings.StateId.hints.label}"
columns="#{bindings.StateId.hints.displayWidth}"
autoSubmit="true" partialTriggers="it3"
shortDesc="#{bindings.StateId.hints.tooltip}" id="it4">
<af:autoSuggestBehavior suggestedItems="#{viewScope.AutoSuggestBean.onStateSuggest}"/>
</af:inputText>
<af:inputText value="#{bindings.CityId.inputValue}" label="#{bindings.CityId.hints.label}"
columns="#{bindings.CityId.hints.displayWidth}"
autoSubmit="true" partialTriggers="it4"
shortDesc="#{bindings.CityId.hints.tooltip}" id="it5">
<af:autoSuggestBehavior suggestedItems="#{viewScope.AutoSuggestBean.onCitySuggest}"/>
</af:inputText>


Finally, our output would be
output1.jpg
output2.jpg
output3.jpg


Display Holiday Name in af:calendar

When using af:calendar component in the realtime applications, there is a frequent requirement to display the holdays in it. In this article, we will see how to achieve that.
After setting the environment, we would be expecting the output as shown in the below image.
finalOutput.jpg

Assuming we already have a page with calendar, the individual date level customizations can be done by using DateCustomizer.
For this, we would create a custom class that extends DateCustomizer class.
public class MyDateCustomizer extends DateCustomizer{
public String format(Date date, String key, Locale locale, TimeZone tz)
{
// For illustrative purpose
// Hashmap holding the holiday list
HashMap holidays = new HashMap();
holidays.put(new Date("25-Dec-2012"), "Christmas");
holidays.put(new Date("01-Jan-2013"), "New Year");

if ("af|calendar::month-grid-cell-header-misc".equals(key))
{
return holidays.get(date)!=null?holidays.get(date).toString():null;

}

return null;

}

}

As per the tag doc, following keys are passed to the format method.
  • "af|calendar::day-header-row"
  • "af|calendar::list-day-of-month-link"Year's Day".
  • "af|calendar::list-day-of-week-column"
  • "af|calendar::month-grid-cell-header-day-link"
  • "af|calendar::month-grid-cell-header-misc"
  • "af|calendar::week-header-day-link"
So, in the above code, we return the actual holiday name for the "af|calendar::month-grid-cell-header-misc" key.
In order to use the new DateCustomizer in our calendar, we create an instance of it in the backing bean and bind it to the calendar's dateCustomizer property.
Bean Code :
public class CalendarBean {
private MyDateCustomizer holidays = new MyDateCustomizer(); ;

public CalendarBean() {
}


public void setHolidays(MyDateCustomizer holidays) {
this.holidays = holidays;
}

public MyDateCustomizer getHolidays() {
return holidays;
}
}


Page Source :
<af:calendar id="c1" dateCustomizer="#{viewScope.CalendarBean.holidays}"/>
If needed, the text can be styled to be displayed in different color (as shown in the image at the top). For this, we can have a styleclass in the css
af|calendar::month-grid-cell-header-misc
{
background-color: Yellow;
}

Monday Nov 26, 2012

Restrict number of characters to be typed for af:autoSuggestBehavior

When using AutoSuggestBehavior for a UI Component, the auto suggest list is displayed as soon as the user starts typing in the field. In this article, we will find how to restrict the autosuggest list to be displayed till the user types in couple of characters.
This would be more useful in the low latency networks and also the autosuggest list is bigger. We could display a static message to let the user know that they need to type in more characters to get a list for picking a value from. Final output we would expect is like the below image
FinalOutput1.jpgFinalOutput2.jpg
Lets see how we can implement this. Assuming we have an input text for the users to enter the country name and an autosuggest behavior is added to it.
<af:inputText label="Country" id="it1">
                    <af:autoSuggestBehavior />
                </af:inputText>
Also, assuming we have a VO (we'll name it as CountryView for this example), with a view criteria to filter out the VO based on the bind variable passed. VC.jpg
Now, we would generate View Impl class from the java node (including bind variables) and then expose the setter method of the bind variable to client interface.
In the View layer, we would create a tree binding for the VO and the method binding for the setter method of the bind variable exposed above, in the pagedef file
Pagedef.jpg
As we've already added an input text and an autosuggestbehavior for the test, we would not need to build the suggested items for the autosuggest list.Let us add a method in the backing bean to return us List of select items to be bound to the autosuggest list.
 padding: 5px; background-color: #fbfbfb; min-height: 40px; width: 544px; height: 168px; overflow: auto;">        public List onSuggest(String searchTerm) {
        ArrayList<SelectItem> selectItems = new ArrayList<SelectItem>();
        if(searchTerm.length()>1) {
        //get access to the binding context and binding container at runtime
        BindingContext bctx = BindingContext.getCurrent();
        BindingContainer bindings = bctx.getCurrentBindingsEntry();
        //set the bind variable value that is used to filter the View Object
        //query of the suggest list. The View Object instance has a View
        //Criteria assigned
        OperationBinding setVariable = (OperationBinding) bindings.get("setBind_CountryName");
        setVariable.getParamsMap().put("value", searchTerm);
        setVariable.execute();
        //the data in the suggest list is queried by a tree binding.
        JUCtrlHierBinding hierBinding = (JUCtrlHierBinding) bindings.get("CountryView1");
                                                                                                                                              
        //re-query the list based on the new bind variable values hierBinding.executeQuery();
        //The rangeSet, the list of queries entries, is of type
        //JUCtrlValueBndingRef.
        List<JUCtrlValueBindingRef> displayDataList = hierBinding.getRangeSet();
        
        for (JUCtrlValueBindingRef displayData : displayDataList){
            Row rw = displayData.getRow();
            //populate the SelectItem list
            selectItems.add(new SelectItem(
            (String)rw.getAttribute("Name"),
            (String)rw.getAttribute("Name")));
            }
        
        }
        else{
            SelectItem a = new SelectItem("","Type in two or more characters..","",true);
            selectItems.add(a);
        }
        return selectItems;
    }
So, what we are doing in the above method is, to check the length of the search term and if it is more than 1 (i.e 2 or more characters), the return the actual suggest list. Otherwise, create a read only select item
new SelectItem("","Type in two or more characters..","",true);
and add it to the list of suggested items to be displayed. The last parameter for the SelectItem (boolean) is to make it as readOnly, so that users would not be able to select this static message from the displayed list.
Finally, bind this method to the input text's autosuggestbehavior's suggestedItems property.
<af:inputText label="Country" id="it1">
        <af:autoSuggestBehavior
              suggestedItems="#{AutoSuggestBean.onSuggest}"/>
 </af:inputText>

How to create multi level cascading (dependent) list of values using BC4J

There are quite a number of documentations / blogs on creating cascading (dependent) list of values in ADF Application using BC4J as model.
Some examples
1. https://blogs.oracle.com/shay/entry/got_to_love_cascading_lovs_in
2. http://mjabr.wordpress.com/2011/04/01/cascade-list-of-values/
However, these entries talk about creating list of values for master-detail attributes. In this article, I would be explaining about creating list of values which have master-detail-grand detail relationship (though the implementation is same, the use case is different).
Assuming that we've our model ready, with an VO for Person (based on Person EO), Country, State and City (read-only VOs).



Now, we'll modify the query of the dependent VOs to include a bind variable in their where clause.

We could then create List of Values for the CountryId, StateId and CityId attributes in the Person VO.


Above image shows an example for creating LOV for the CityId attribute. LOV is created for the CountryId and StateId attributes in the similar fashion.
Now that we've created LOV for all the 3 attributes, we need to pass the required values for the bind variable we created previously (in State and City VOs). That is done from the View Accessors tab of Person VO.


Now we are set to go with the dependent LOV. Before running the Tester, we need to make the CountryId and StateId attributes automatically submit their values upon change (by setting Auto Submit UI Hint to true)

 (Above image shows setting Auto Submit UI Hint to true for CountryId attribute. In the same manner, set the Auto Submit UI Hint to true for the StateId attribute as well).
and add make StateId dependent on CountryId, CityId to depend on CountryId and StateId.





We are set to go now. Run the AppModule tester to verify the values.
When using this in jspx page, set the AutoSubmit properties for the CountryId and StateId components, and add the partialTriggers for StateId and CityId components with the Id of CountryId component, as shown below.


T

Interpret af:query's queryEvent and display popup to end user using QueryListener

Found an interesting question on OTN. Based on the question, wired a usecase to try out.

Usecase : Show a warning to user when they try to search the records (af:query component), without specifying a criteria / a wild card "%". I.e, when the user tries to query the entire table, show a warning that querying all the records would take some time.

There are three phases in implementing this usecase.

1. Interpret the query event and get the query criteria.
2. Show the popup.
3. Process the interpreted query based on the outcome of the popup.

Before proceeding with the implementation, we'll create a page for assumption.
a. Page contains a af:query component with a resultant table / read-only table.
b. Has a popup to be shown to the end user.
c. Bound to a bean.

We'll now implement it phase by phase.

First of all, we'll create couple of attributes in the bean and generate accessors to them.
    private RichTable empTable;
    private boolean warnUser=true;
   // Set the default queryListener property value of the af:query component
   // for mexpr.
   private String mexpr = "#{bindings.ImplicitViewCriteriaQuery.processQuery}"; 
    private QueryEvent qEvt;

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

    public RichTable getEmpTable() {
        return empTable;
    }


Now, we need to trap the query event of the af:query component to perform the desired task. We can add a queryListener and bind it to the af:query component

  public void processQuery(QueryEvent queryEvent) {
        // store the queryEvent in a bean attribute, to be used in another method.
        qEvt = queryEvent;
        // Reset the flag. This flag would be used to check if the system has to 
        //raise the popup or not
        warnUser=false;
        DCBindingContainer bc =   
        (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();   
         // Get the view criteria that would be applied.
         // findExecutableBinding method takes two parameters.
         // id of the searchRegion executable binding
         // criteria for the searchRegion executable binding
         // Ex : <searchRegion Criteria="__ImplicitViewCriteria__"      
         // Customizer="oracle.jbo.uicli.binding.JUSearchBindingCustomizer"
         //         Binds="EmpView1Iterator" id="ImplicitViewCriteriaQuery"/>
       


 ViewCriteria vc = 
JUSearchBindingCustomizer.getViewCriteria((DCBindingContainer)bc.findExecutableBinding("ImplicitViewCriteriaQuery"),"__ImplicitViewCriteria__");


        ViewCriteriaRow vcr = (ViewCriteriaRow)vc.get(0);
        // Some logic to set the flag. Here, checking if the Ename attribute has
        // no value specified / used a wildcard expression ("%").
        for(int i=0;i<vcr.getAttributeNames().length;i++) {
           
 if(vcr.getAttributeNames()[i] == "Ename" &&  
("%".equals(vcr.getAttributeValues()[i]) || 
vcr.getAttributeValues()[i]==null)) 
                warnUser=true;
        }
 
        if(warnUser) 
            showPopup();
        else 
            executeQuery();
 
    }


showPopup and executeQuery are custom methods to show the popup and to process the query respectively.

       public void showPopup(){
        UIViewRoot root = FacesContext.getCurrentInstance().getViewRoot();
        RichPopup popup = (RichPopup) root.findComponent("p1");
        RichPopup.PopupHints hints = new RichPopup.PopupHints();
        popup.show(hints);
    }

  // This method invokes the method expression used by af:query component programatically
    public void executeQuery(){
        processMethodExpression(mexpr, new Object[] {qEvt}, new Class[] {QueryEvent.class}); 
        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance(); 
        adfFacesContext.addPartialTarget(empTable); 
 
    }

    private Object processMethodExpression(String methodExpression, Object[] parameters, Class[] expectedParamTypes) { 
        FacesContext fctx = FacesContext.getCurrentInstance(); 
        ELContext elctx = fctx.getELContext(); 
        Application app = fctx.getApplication(); 
        ExpressionFactory exprFactory = app.getExpressionFactory(); 
       
 MethodExpression methodExpr = exprFactory.createMethodExpression(elctx,
 methodExpression, Object.class, expectedParamTypes); 
        return methodExpr.invoke(elctx, parameters); 
        }

Now, we need to bind the custom querListener created above to the af:query component
  <af:query id="qryId2" headerText="Search" disclosed="true"
      value="#{bindings.ImplicitViewCriteriaQuery.queryDescriptor}"
      model="#{bindings.ImplicitViewCriteriaQuery.queryModel}"
      queryListener="#{viewScope.QueryBean.processQuery}".....


We are almost there. Now, when we run the page and query for the records by keeping Ename as null (in the query panel), we would get the popup.

Final step is to handle the user action on the popup and then proceed executing the query / to stop it.

For this, we'll create a dialog listener and bind it to popup.
 public void onDialog(DialogEvent dialogEvent) {
        Outcome o = dialogEvent.getOutcome();
        if(o == Outcome.yes) 
            executeQuery();
 
    }

                <af:popup childCreation="deferred" autoCancel="disabled" id="p1">
                    <af:dialog id="d2" type="yesNo" title="Are you sure?"
                               dialogListener="#{viewScope.QueryBean.onDialog}">
                       
 <af:outputText value="It would be time consuming to query for all 
records. Are you sure you want to continue?" id="ot9"/>
                        <f:facet name="buttonBar"/>
                    </af:dialog>
                </af:popup>


Here is how the runtime would be.


step1.jpg



Enter % for Ename and hit the Search button

step2.jpg



Popup with a warning message displayed

step3.jpg


Clicking on Yes / No on the popup performs respective task (perform query / cancel query).

step4.jpg




Calculating time since last query in adf using java script

In some scenarios, we would need to calculate the time elapsed since the last query execution, without contacting the server (i.e without using af:poll component). This blog is to give an example for this scenario by using javascript.

OTN question : https://forums.oracle.com/forums/thread.jspa?forumID=83&threadID=2411997

Assuming that we have an application with a table in the page, and a commandButton to query the records, we will proceed further to build our usecase.

The logical flow of this implementation would be like,
1. Execute the query
2. When the button clicked, reset the previous time
3. Set the time to 0.
4. Trigger the timer to increment time.
Now, implementation comes.
Lets add an output text to display the time lapsed
<af:outputLabel value="Minutes since last query :" id="ol1"/>
        <af:outputText value="" id="ot9" clientComponent="true"/>

Since we would be accessing the output text from javascript, we would need to make it available to client by setting clientComponent to true.
We now need to add a javascript code to our page, to count the minutes and display in the output text.
        <af:resource type="javascript">

        function updateTimer(){
            var opTxt = AdfPage.PAGE.findComponentByAbsoluteId('ot9');
            var curMins = opTxt.getProperty('value');
            if(curMins == '' || curMins == null)
                opTxt.setProperty('value','0');               
            else
                opTxt.setProperty('value',parseInt(opTxt.getProperty('value')) + 1);
        }

        </af:resource>

In the above code, we find the outputText component (with id ot9), get its value. If the value is blank or null, then set it to 0. If it is a non-zero number, then increment it.
Now, we need to call this method every minute to update the output text. For this, we will add another JS function.
        function startTimer(){
            var opTxt = AdfPage.PAGE.findComponentByAbsoluteId('ot9');
            opTxt.setProperty('value','');
            updateTimer();
            var int=window.setInterval("updateTimer()",60000);
        }

This function finds the outputText (with id ot9), resets its value (i.e set it to blank) and then schedules the function we've created first (updateTimer()) to be called every minute (i.e 60000 milliseconds).
Assuming we have a button to execute the query, we'll add a client listener to the button to execute this function when pressed.
                <af:commandButton actionListener="#{bindings.Execute.execute}" text="Execute"                                       
                                        disabled="#{!bindings.Execute.enabled}"  id="cb1" partialSubmit="true">
                          <af:clientListener method="startTimer" type="action" />
                </af:commandButton>

Ouput would be like below.




An Epic Question "How to call a method when the page loads"

Quite often, there comes a question in OTN, with different subjects, all meaning "How to call a method when my ADF page loads?". More often, people tend to take the approach of ADF Phase Listener by overriding before/afterPhase methods.

In this blog, we will go through different options in achieving it.

1. Method Call Activity as default activity in Taskflow :

If the application is built with taskflows, then this is the best suited approach to take.

1.a. Calling a Data Control Method :

To call a Data Control method (ex: A method in AMImpl exposed as client interface), simply Drag and Drop the method as Default Method Call Activity, then draw a control flow case from the method to your page.


DCMethodTF.jpg

Once after this, drop the taskflow as region in main page. When we run the main page, the Method Call Activity would be called first, and then the page will be rendered.

1.b. Calling a Method in Backing Bean:

To call a method in the backing bean before pageload, we can follow the similar approach as above. Instead of binding the Method Call Activity to an action/method binding in pagedef, we bind to the method. Insert a Method Call Activity (and make it as default) from the Component Palette. Double click on to select a method to bind.

BBMethodTF.jpg



This approach can also be used, to perform some action in backing bean along with calling a method Data Control (just need to add bindings code in backing bean to execute DC method).


2. Using invokeAction Executable :

If the application is built with pages and no taskflows are involved, then this option can be taken into consideration.

In the page definition of the page, add an invokeAction Executable and bind it to the method needed to be executed.

DCMethodInvokeAction.jpg


3.
Using combination of Server and Client Listeners :

If the page does not have any page definition, then to call a method in backing bean, this approach can be taken. In this, a serverListener would be added at the document level, which would be calling the method in backing bean. Along with this, a clientListener would be added with "load" type (i.e will be triggered when the page loads), which would queue a serverEvent to trigger the method.

BBMethodListener.jpg



4. Using Page Phase Listener :

This should be the last resort. Care should be taken when using this approach since the Phase Listener would be called for each request sent by the client.

Executing Put operation of REST service programatically from ADF App

In quite some cases, we would like to call the PUT method on a REST service by constructing the parameters during runtime and pass it on. In this article, we would go through how to deal with such cases when building an ADF Application.
Refer this tutorial for introduction to REST service in where, GET and DELETE methods are explained. In this sample, we'll see how to implement PUT operation using a HashMap. In fact, as like in the above tutorial, we can directly execute the PUT method as well. This article is mainly concentrated on how to construct the parameters dynamically at runtime.
First let us create a simple POJO to hold employee records.


package project1;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement

public class Emp {
    public Emp() {
        super();
    }
    
    private String name;
    private int id;
    private int exp;
    private int salary;

    public Emp(String name, int id, int exp, int salary) {
        super();
        this.name = name;
        this.id = id;
        this.exp = exp;
        this.salary = salary;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setExp(int exp) {
        this.exp = exp;
    }

    public int getExp() {
        return exp;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    public int getSalary() {
        return salary;
    }
    
    public String toString() {
        String empXml = "<name>"+getName()+"</name>"+"\n"+
                       "<id>"+getId()+"</id>"+"\n"+
                        "<experience>"+getExp()+"</experience>"+"\n"+
                       "<salary>"+getSalary()+"</salary>";
        return empXml;                  
    }
}
Then, create a REST service using the for the Employee.

package project1;

import javax.ws.rs.Path;
import java.util.*;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;

import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/test")
public class Service {
    
   static ArrayList<Emp> emp = new ArrayList<Emp>();
  
    public Service() {
        super();
     }
    
    @GET
    @Produces("application/xml")
    public  ArrayList<Emp> getEmps() {
       
        return emp;
        
    }
    
    @DELETE
    public void deleteEmp(@QueryParam("id") int id) {
       emp.remove(getObj(id));
    }
    
    @PUT
    @Consumes("application/xml")
    public void addEmp( Emp e) {
        emp.add(e);
    }
    
    @PUT
    @Path("defaultEmp")
    public Response addEmp() {
        emp.add(new Emp("abc",1,5,10000));
        emp.add(new Emp("xyz",2,7,15000));
        emp.add(new Emp("lmn",3,5,8000));
        return Response.ok().build();
            
    }
    
    @POST
    public void upadteEmp(@QueryParam("id")int id,Emp e) {
      deleteEmp(id);
      addEmp(e);
    }
    
    public Emp getObj(int id) {
        Iterator i = emp.iterator();
        while(i.hasNext()){
        Emp emp = (Emp)i.next();
        if((emp.getId())==id)
        {
            System.out.println(emp.getName());
            return emp;
        }
        } 
        return null;
    }
}

We'll come to the UI part now.

After creating a Fusion Web Application from JDeveloper, create a new URL Data Control for the REST service created above (for GET and PUT Operations).

DataControls.dcx looks like below

DataControls.jpg



Now, our aim is to have a UI, from where we can enter the employee details. Once after having the data, construct parameter object and execute loadData (PUT) method.

This is done by having 4 input texts and bind them to attributes in the backing bean. Drag and Drop the loadData method from RestPut DataControl (and do not specify a value for the parameter).



And the code snippet of the jspx page

<af:panelFormLayout id="pfl1">
    <f:facet name="footer">
        <af:commandButton text="Put"
          disabled="#{!bindings.loadData.enabled}" id="cb1"
          actionListener="#{pageFlowScope.RestBean.performPut}"/>
    </f:facet>
    <af:inputText label="Id" id="it1" 
                  value="#{pageFlowScope.RestBean.id}" autoSubmit="true"/>
    <af:inputText label="Name" id="it2" 
                  autoSubmit="true" value="#{pageFlowScope.RestBean.name}"/>
    <af:inputText label="Exp" id="it3" 
                  value="#{pageFlowScope.RestBean.exp}" autoSubmit="true"/>
    <af:inputText label="Sal" id="it4" 
                  autoSubmit="true" value="#{pageFlowScope.RestBean.sal}"/>
</af:panelFormLayout>

In the backing bean (RestBean), we have 4 attributes with accessors that are mapped to the Text Items.

    private Number id,sal,exp;
    private String name;


    public void setId(Number id) {
        this.id = id;
    }

    public Number getId() {
        return id;
    }

    public void setSal(Number sal) {
        this.sal = sal;
    }

    public Number getSal() {
        return sal;
    }

    public void setExp(Number exp) {
        this.exp = exp;
    }

    public Number getExp() {
        return exp;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }


Now, we'll add an actionListener code in the backing bean, in that, we can construct a Map with the required values and then execute the method by passing Map to it.

    public void performPut(ActionEvent actionEvent) {
        BindingContainer bindings = getBindings();
        Map putParamMap = new HashMap();
        putParamMap.put("id", getId());
        putParamMap.put("name", getName());
        putParamMap.put("exp", getExp());
        putParamMap.put("sal", getSal());

        OperationBinding operationBinding = bindings.getOperationBinding("loadData");
        operationBinding.getParamsMap().put("emp",putParamMap);
        Object result = operationBinding.execute();
        if (!operationBinding.getErrors().isEmpty()) {
            System.out.println("Error processing put operation..");    
        }
    }

    public BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }
In the above code, we find the loadData method from the DataBindings entry, create a Map with all the required attributes to create an Employee record, get the Parameter list for the method and pass the Map to method as parameter to execute it.


Refreshing One Column based on the value of Another Column in ADFdi Table

When using ADF Desktop Integration, quite frequently, we get into a situation where we would like to refresh one column based on the value of another column. In ADF Faces, we can achieve this by setting the autoSubmit property and partialTriggers property for the corresponding columns.

However, in ADFdi, we do not have such option. Though we can achieve this by using LOVs and Dependent LOVs. But, in some scenarios we would like to achieve this when using an Input Text Component.

In this article, we will simulate this Auto Refresh functionality in a ADFdi Table.

Note : Since we would be using VBA code to achieve this, we can use this only on the Macro Enabled Excel Workbooks.

Let us assume that we have a View Object based on the Emp table. We could take an example of having a transient attribute in the VO, that gives the sum of Salary and Commission attributes.

SalPlusComm.jpg



In the above example, we've added a new transient attribute (SalPlusComm) to the EmpVO, that would give the sum of Sal and Comm attributes. Since we need this attribute to get refreshed when either Sal or Comm attribute changes, we set the Sal and Comm attributes as Dependencies. Also, we set the AutoSubmit property (under UI Hints tab) for the Sal and Comm attributes.

SalCommAutoSubmit.jpg


Now, we are done with the model layer. We can now, create a jspx page and then Drag and Drop EmpView as ADF Table. After this, we create an Excel Workbook (macro enabled), enable ADF Desktop Integration for it, set the required Workbook Properties, and then add a Table based on the EmpView.

EmpTable.jpg



As there are no straight forward way in ADFdi to trigger a request to server when a value of a cell is changed, we will now add a DoubleClickActionSet for the Sal and Comm columns. This DoubleClickActionSet will have the Table.RowUpSync and Table.RowDownSync actions.

RowUpSyncDownSync.jpg


Above example image shows the DoubleClickActionSet for Sal column. In the same manner, we need to add the DoubleClickActionSet for the Comm column as well.

Now, we have the workbook, that would fetch the SalPlusComm attribute (after recalculation in the model), when we change the Sal / Comm attribute and then double click on that column. To do this automatically when the user tabs out / presses enter key on the cells, we'll write a bit of VBA Code on the Worksheet where we've this table (Go to Developer Tab and Click on Visual Basic).

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 14 Or Target.Column = 15 Then
    Target.Select
    Application.CommandBars("Cell").Controls("Invoke Action...").Execute
  End If
End Sub
Excel would trigger Worksheet_Change event when a cell in the worksheet is modified. So, we would code our logic in that event. The above code assumes that Sal column is present in the N (14th) column on the worksheet and Comm column is present in O (15th) column. So, we would execute our logic only when the contents in these two columns change.

ADFdi would provide a context menu (Invoke Action...) when a DoubleClickActionSet is added to a particular column. We'll make use of that context menu and invoke it programatically.


InvokeAction.jpg



We invoke that context menu programatically using the following line of code

Application.CommandBars("Cell").Controls("Invoke Action...").Execute

Now, we run our workbook, modify the value of Sal column for any row and tab out of that field would automatically update the value of SalPlusComm column.


EmpTable1.jpg
EmpTable1.jpg
Here, a simple example (Transient Attribute) is taken for the explanation. In the similar fashion, we can also have a DoubleClickActionSet to contain a method in the Impl that would perform this calculation as well.


Dynamic Pie Graph Generation by Drag And Drop Rows from ADF Table

In normal scenarios, we display the graph and chart to get graphical representation of data. In this article, we'll see how to create graph dynamically by dragging the contents from ADF table and dropping on the graph.

Environment : JDeveloper PS5 (11.1.1.6.0)

Assuming that we have a table that displays the Department's details. We'll build a dynamic pie graph to display the Employee details for the departments that are dragged from the Department's table.

DeptEmpChart.jpg



For our usecase, we need to drag the Departments from Table and Drop it on the Pie Chart to get the Employees details corresponding to the Depts selected.

For this, we need to add DragSource in the Dept Table and DropTarget in Emp Chart.

<af:table value="#{bindings.DeptView1.collectionModel}" var="row"
                 rows="#{bindings.DeptView1.rangeSize}"
                 emptyText="#{bindings.DeptView1.viewable ? 'No data to display.' : 'Access Denied.'}"
                 fetchSize="#{bindings.DeptView1.rangeSize}"
                 rowBandingInterval="0"
                 selectionListener="#{bindings.DeptView1.collectionModel.makeCurrent}"
                 rowSelection="multiple" id="t1">
            <af:dragSource discriminant="Dept" 
                           defaultAction="COPY"/>           
            ....
            ....
                  <dvt:pieGraph id="pieGraph1" subType="PIE_MULTI"
                                customLayout="CL_NONE">
                    <af:dropTarget>
                      <af:dataFlavor flavorClass="org.apache.myfaces.trinidad.model.RowKeySet"
                                     discriminant="Dept"/>
                    </af:dropTarget>
            ....
            .... 
Now that we've added the drag source and drop target, we need to have a method in our AM/VO's impl class, that take the department number as input and return the list of employees under it and their details as ArrayList.

    public ArrayList getEmpDetsForDept(int Deptno) {
        ArrayList empDetsAL = new ArrayList();
        getEmpView1().setWhereClause("Deptno=" + Deptno);
        getEmpView1().executeQuery();
        
        
        getEmpView1().first();
                
        if(getEmpView1().getRowCount()>0) {

            empDetsAL.add(new Object[]{""+Deptno,
                                        getEmpView1().getCurrentRow().getAttribute("Ename").toString(),
                                        new Double(getEmpView1().getCurrentRow().getAttribute("Sal").toString())}
                          );

            while (getEmpView1().hasNext()){
                empDetsAL.add(new Object[]{""+Deptno,
                                            getEmpView1().getCurrentRow().getAttribute("Ename").toString(),
                                            new Double(getEmpView1().getCurrentRow().getAttribute("Sal").toString())}
                              );
                getEmpView1().next();
                
            }

            
        }
                                              
        return empDetsAL;
    }
Now, the main part comes. Pie Graphs can be based on ArrayList. So, in our backing bean, we'll have an attribute of type ArrayList. Also, we'll have a variable to to bind the graph for triggering PPR.

    private List chartData=new ArrayList();
    private UIGraph empChart;

    public void setChartData(List chartData) {
        this.chartData = chartData;
    }

    public List getChartData() {
        return chartData;
    }

    public void setEmpChart(UIGraph empChart) {
        this.empChart = empChart;
    }

    public UIGraph getEmpChart() {
        return empChart;
    }

As we need to find out the Departments that are dragged from table, we'll have a method in the backing bean to get the list of dragged Departments, iterate through them, pass each to the AM / VO method created to get Emp details and then construct the ArrayList.

    public DnDAction dropDeptInPie(DropEvent dropEvent) {
        
        RichTable table = (RichTable) dropEvent.getDragComponent(); 
        Transferable t = dropEvent.getTransferable(); 
        DataFlavor<RowKeySet> df = DataFlavor.getDataFlavor(RowKeySet.class, "Dept"); 
        RowKeySet rks = t.getData(df); 
        Iterator iter = rks.iterator();
        if(getChartData()!=null) getChartData().clear();
        while (iter.hasNext()) { 
            List key = (List)iter.next(); 
            table.setRowKey(key); 
            JUCtrlHierNodeBinding rowBinding = (JUCtrlHierNodeBinding) table.getRowData(); 
            Row row = (Row) rowBinding.getRow();
            String Deptno = row.getAttribute("Deptno").toString();
            BindingContainer bindings = getBindings();
            OperationBinding operationBinding = bindings.getOperationBinding("getEmpDetsForDept");
            operationBinding.getParamsMap().put("Deptno", Deptno);
            ArrayList result = (ArrayList)operationBinding.execute();
        

            if (operationBinding.getErrors().isEmpty()) {
                if(getChartData()!=null)getChartData().addAll(result);
                else  setChartData(result);

            }

        }  
        
        
        AdfFacesContext.getCurrentInstance().addPartialTarget(empChart);

        return DnDAction.NONE;

        
    }

    public BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

In order to make the Pie Graph use the ArrayList as source, we need to bind this to the tabularData Property of the pie graph. Let us also bind the chart to the variable we created in backing bean and set its dropListener to the method created above. Now, our pieGraph's source in jspx page would look like

                  <dvt:pieGraph id="pieGraph1" subType="PIE_MULTI"
                                customLayout="CL_NONE"
                                binding="#{pageFlowScope.DnDBean.empChart}"
                                tabularData="#{pageFlowScope.DnDBean.chartData}">
                    <af:dropTarget dropListener="#{pageFlowScope.DnDBean.dropDeptInPie}">
                      <af:dataFlavor flavorClass="org.apache.myfaces.trinidad.model.RowKeySet"
                                     discriminant="Dept"/>
                    </af:dropTarget>


Now, let us run the page, select couple of Departments and Drop them on the Pie chart.

DeptEmpChartData.jpg


Here, we've dragged the departments 10 & 30, and dropped them on the chart to get the Salary of the employees belonging to those departments as slices.


Passing comma separated string as bind variable for VO query's IN operator

Quite often, we want to pass a parameter to the bind variable in the VO's query with a comma separated value, for the where clause with an IN operator. However, normal SQL query that the VO contain interpret that whole comma separated value as a single String and our usecase fail to get fulfilled.

Ex. question in OTN thread : https://forums.oracle.com/forums/thread.jspa?messageID=10125366

To overcome this, Mohammad Jabr has written a blog entry with the help of  Steve Muench's example #126. This has been achieved by using a TYPE and CASTing it to get the list.

In this article, we'll see another option to alter the query using regexp_substr, without having to use a TYPE and CAST.

Let us take an example of a VO created using EMP table with the following query.

SELECT Emp.EMPNO, 
       Emp.ENAME, 
       Emp.JOB, 
       Emp.MGR, 
       Emp.HIREDATE, 
       Emp.SAL, 
       Emp.COMM, 
       Emp.DEPTNO
FROM EMP Emp

EmpViewDefault.jpg


We'll add a where clause to the VO's query with a bind variable that takes comma separated string as input. Here, we would be including regexp_substr function (Oracle DB >=10g), to split the comma separated string and return them as rows.

Now, our Where clause of the VO's query would be looking like

WHERE Emp.ENAME in 
  (select regexp_substr(:Bind_Ename_Comma_Sep_List,'[^,]+', 1, level) 
   from dual 
    connect by 
        regexp_substr(:Bind_Ename_Comma_Sep_List, '[^,]+', 1, level) 
            is not null)
Also, we'll add a Bind Variable Bind_Ename_Comma_Sep_List of String data type. Once after modifying the Where Cluase and after adding the bind variable, our VO would be looking like

EmpView.jpg


To validate our query, let us run the AM tester to check the result

AMTester.jpg


Validate the result by entering a comma separated ENAME list to the bind variable (SMITH,ALLEN,JONES).


AMTesterBindVar.jpg


Check out the query result

AMTesterQueryRes.jpg


As it can be seen, we've passed 3 comma separated Enames to the bind variable, which in turn fetched only those records with the matching 3 Enames.

What does featureOff attribute do in af:panelCollection

Panel Collection in ADF (af:panelCollection) has an attribute - featureOff, which manages the visibility of certain controls / features of panelCollection to the end user.

As per the doc guide, here are the list of valid values for this attribute.

Value Turns off
statusBar Status bar
viewMenu 'View' menu
formatMenu 'Format' menu
columnsMenuItem 'Columns' sub-menu item
columnsMenuItem:col1,col20 Columns with column ID: 'col1' and 'col20' inside 'Columns' sub-menu
freezeMenuItem 'Freeze' menu item
detachMenuItem 'Detach' menu item
sortMenuItem 'Sort' menu item
reorderColumnsMenuItem 'Reorder Columns' menu item
resizeColumnsMenuItem 'Resize Columns' menu item
wrapMenuItem 'Wrap' menu item
showAsTopMenuItem Tree/TreeTable 'Show As Top' menu item
scrollToFirstMenuItem Tree/TreeTable 'Scroll To First' menu item
scrollToLastMenuItem Tree/TreeTable 'Scroll To Last' menu item
freezeToolbarItem 'Freeze' toolbar item
detachToolbarItem 'Detach' toolbar item
wrapToolbarItem 'Wrap' toolbar item
showAsTopToolbarItem Tree/TreeTable 'Show As Top' toolbar item
wrap 'Wrap' menu and toolbar items
freeze 'Freeze' menu and toolbar items
detach 'Detach' menu and toolbar items

In this article, we will find out what happens at runtime when different values are specified for this attribute (Note : This attribute takes a space-separated list of default features to be turned off for the panelCollection - as mentioned above)

1. statusBar

 <af:panelCollection id="pc1" featuresOff="statusBar">

When we set statusBar to the featuresOff attribute, it hides panelCollection's status bar.

statusBar.jpg


2. viewMenu

 <af:panelCollection id="pc1" featuresOff="viewMenu">

When we set viewMenu to the featuresOff attribute, it completely removes the View Menu.

viewMenu.jpg


3. formatMenu

 <af:panelCollection id="pc1" featuresOff="formatMenu">

When we set formatMenu to the featuresOff attribute, it completely removes the Format Menu.

formatMenu.jpg


4. columnsMenuItem

 <af:panelCollection id="pc1" featuresOff="columnsMenuItem">

When we set columnsMenuItem to the featuresOff attribute, it removes the Columns menu item under View menu. Check the next option to hide specific columns.

columnsMenuItem.jpg



5. columnsMenuItem:col1,col20

<af:panelCollection id="pc1" featuresOff="columnsMenuItem:col1,col2">

When we set columnsMenuItem:.. to the featuresOff attribute, it removes the specified columns from the Columns menu item under View menu. If you want to hide the entire Columns menu item, check the previous option.

columnsMenuItem1.jpg

In the above example image, columns c3 and c4 belong to the columns Empno and Ename.

6. freezeMenuItem

<af:panelCollection id="pc1" featuresOff="freezeMenuItem">

When we set freezeMenuItem to the featuresOff attribute, it removes Freeze menu item under View menu .

freezeMenuItem.jpg

7. detachMenuItem

<af:panelCollection id="pc1" featuresOff="detachMenuItem">

When we set detachMenuItem to the featuresOff attribute, it removes Detach menu item under View menu .

detachMenuItem.jpg

8. sortMenuItem

<af:panelCollection id="pc1" featuresOff="sortMenuItem">

When we set sortMenuItem to the featuresOff attribute, it removes entire Sort menu item under View menu .

sortMenuItem.jpg

9. reorderColumnsMenuItem

<af:panelCollection id="pc1" featuresOff="reorderColumnsMenuItem">

When we set reorderColumnsMenuItem to the featuresOff attribute, it removes Reorder Columns... menu item under View menu .

reorderColumnsMenuItem.jpg


10. resizeColumnsMenuItem

<af:panelCollection id="pc1" featuresOff="resizeColumnsMenuItem">

When we set resizeColumnsMenuItem to the featuresOff attribute, it removes Resize Columns... menu item under Format menu .

resizeColumnsMenuItem.jpg

11. wrapMenuItem

<af:panelCollection id="pc1" featuresOff="wrapMenuItem">

When we set wrapMenuItem to the featuresOff attribute, it removes Wrap menu item under Format menu .

wrapMenuItem.jpg

12. showAsTopMenuItem

<af:panelCollection id="pc1" featuresOff="showAsTopMenuItem">

When we set showAsTopMenuItem to the featuresOff attribute, it removes Show as Top and Go to Top menu items under View menu (Applicable for the tree/treeTable) .

showAsTopMenuItem.jpg

13. scrollToFirstMenuItem

<af:panelCollection id="pc1" featuresOff="scrollToFirstMenuItem">

When we set scrollToFirstMenuItem to the featuresOff attribute, it removes Scroll to First menu item under View menu (Applicable for the tree/treeTable) .

scrollToFirstMenuItem.jpg

14. scrollToLastMenuItem

<af:panelCollection id="pc1" featuresOff="scrollToLastMenuItem">

When we set scrollToLastMenuItem to the featuresOff attribute, it removes Scroll to Last menu item under View menu (Applicable for the tree/treeTable) .

scrollToLastMenuItem.jpg

15. freezeToolbarItem

<af:panelCollection id="pc1" featuresOff="freezeToolbarItem">

When we set freezeToolbarItem to the featuresOff attribute, it removes Freeze button from the Toolbar.

freezeToolbarItem.jpg

16. detachToolbarItem

<af:panelCollection id="pc1" featuresOff="detachToolbarItem">

When we set detachToolbarItem to the featuresOff attribute, it removes Detach button from the Toolbar.

detachToolbarItem.jpg

17. wrapToolbarItem

<af:panelCollection id="pc1" featuresOff="wrapToolbarItem">

When we set wrapToolbarItem to the featuresOff attribute, it removes Wrap button from the Toolbar.

wrapToolbarItem.jpg

18. showAsTopToolbarItem

<af:panelCollection id="pc1" featuresOff="showAsTopToolbarItem">

When we set showAsTopToolbarItem to the featuresOff attribute, it removes Go Up, Go to Top and Show as Top buttons from the Toolbar (Applicable for tree/treeTable).

showAsTopToolbarItem.jpg

19. wrap

<af:panelCollection id="pc1" featuresOff="wrap">

When we set wrap to the featuresOff attribute, it removes Wrap menu item from Format Menu as well as from the Toolbar. Equivalent to featuresOff="wrapMenuItem wrapToolbarItem".

wrap.jpg


20. freeze

<af:panelCollection id="pc1" featuresOff="freeze">

When we set freeze to the featuresOff attribute, it removes Freeze menu item from View Menu as well as from the Toolbar. Equivalent to featuresOff="freezeMenuItem freezeToolbarItem".

freeze.jpg


21. detach

<af:panelCollection id="pc1" featuresOff="detach">

When we set detach to the featuresOff attribute, it removes Detach menu item from View Menu as well as from the Toolbar. Equivalent to featuresOff="detachMenuItem detachToolbarItem".

detach.jpg

These options would be useful when using a panelCollection for customizing at end user. A separate options could be provided using these, so that end user can customize the LAF of the panelCollection.

Business Rules Editor for View Objects in JDeveloper 11.1.2.0.0

JDeveloper 11.1.2.0.0 has a new tab in the View Objects Editor - Business Rules.
This easily tend to make people misunderstand that this Editor can be used for adding validation rules for the attributes in the View Object. However, it is not true.

Lets check out what this editor is all about. As the online help for this page states
Use to create and maintain business rules based on Groovy Language expressions and declarative validation rules for this view object including:

  • Validators for transient attributes
  • Bind variable default value expressions for SQL queries
  • Bind variable value mappings for view accessors
  • Transient attribute value expressions
  • Transient attribute value expression recalculation conditions
  • Attribute default value expressions
We'll see how we can use this editor to edit different types :
Transient Attributes : 
We can use this editor for a. adding validation rules, b. edit default value expression
a. As like the Entity Attributes, we can add many validation rules for the transient attributes in VO as well.
Ex.


In the above image, EmpType is a transient attribute on Emp VO.We can see there are two rules added. First one is a validation rule (List Validator), restricting the user to enter either one of the value specified for the attribute. Second one is the default value expression for the attribute. Upon selecting the node, the default value groovy expression would become editable in the Script Expression field below, wherein we can modify it and test the syntax as well.

Note : We can add the validation rule only for the transient attributes which are Updatable. Also, we can edit only the default values which are script expressions only. Not the literal values.

Bind Variables :

Similar to the transient attributes, we can use this editor for modifying and testing the default value expression for the Bind Variables of the VO as well.

Ex :



In the above example image, we can see a Bind Variable (Bind_Hiredate) added to the Query, which has the default value expression as adf.currentDate.

Using this editor, we can modify this expression and test the syntax.

View Accessor :

If we have a bind variable to the VO and use it as List Data Source for any of the attributes in the VO, we can use this editor to change the value of the bind variable in the View Accessor.

Ex :


In the above example image, we have couple of Bind Variables in the View Accessors (they are used as Lists and Dependent Lists for this View Object). Using this editor, we can edit the values of those bind variables.
We can also use this editor for modifying and testing the default value expression on the VO attributes and the re-calculation conditions.


Paritally restricting user entry in the ADF input text - using Java Script

Recently came across a forum post in which the OP wanted to let the users edit the content of the text field partially.
https://forums.oracle.com/forums/thread.jspa?forumID=83&threadID=2259832
Here is an example. Let us assume the input text contains the following text. "You can edit the content inside { this }". In this, users should be able to edit only the content inside { }. I.e Only "this" should be editable.
To achieve this, we can use a java script method, that tracks the cursor position and ignore the user edits if the cursor position is not between the curly braces. After which, the method would be used in the client listener for the input text.
Example code snippet.

<af:inputText label="Partial Editable Text Item" 
id="it1" value="You can edit the content inside { this }" clientComponent="true" >
<af:clientListener  type="keyPress" method="validateValue"  /> 
           
</af:inputText>
<af:resource type="javascript">
               function validateValue(evt){
                       var inputTxt=document.getElementById('it1::content');
                       var startPos = inputTxt.value.indexOf("{");
                       var endPos = inputTxt.value.indexOf("}");
                       var cursorPos = inputTxt.selectionStart;
                          if (cursorPos &lt; startPos+2 || cursorPos > endPos-1) { 
                                   alert("Cannot Edit");
                                   evt.cancel();
                          }
 }
</af:resource>

More complex example by Frank Nimphius http://blogs.oracle.com/jdevotnharvest/entry/get_social_security_numbers_right
Note : Tested the above snippet successfully in Mozilla Firefox and IE 9.

Getting all selected rows in ADF Table with multiple rows selection enabled

When we build a web application which contains an ADF Table (with multiselect option), in many cases, we require to get all the selected rows to process through backing bean. This example will illustrate how to achieve that.

Assuming that we already have an application, that contains an ADF Table with multi-selection enabled (i.e the web page look something like the image shown below).
empTableRT-thumb-301x302-20887.jpg
img empTableRT : Table based on Emp
To access the table in the backing bean (through command button click, for ex.), we add an attribute with accessors in the backing bean and bind it to ADF Table
    RichTable empTable;
    public void setEmpTable(RichTable empTable) {
        this.empTable = empTable;
    }


    public RichTable getEmpTable() {
        return empTable;
    }
code snippet of the af:table in jspx page.

<af:table value="#{bindings.EmpView1.collectionModel}" var="row"
                  rows="#{bindings.EmpView1.rangeSize}"
                  emptyText="#{bindings.EmpView1.viewable ? 'No data to display.' : 'Access Denied.'}"
                  fetchSize="#{bindings.EmpView1.rangeSize}"
                  rowBandingInterval="0"
                  selectedRowKeys="#{bindings.EmpView1.collectionModel.selectedRow}"
                  selectionListener="#{bindings.EmpView1.collectionModel.makeCurrent}"
                  rowSelection="multiple" id="t1"
                  binding="#{backingBeanScope.EmpBean.empTable}">
Let us add a command button in the jspx page to print down the "Ename"s of selected rows.
<af:commandButton text="Print selected Emps" id="cb1" 
      action="#{backingBeanScope.EmpBean.printSelectedEmpNames}"/>

The method printSelectedEmpNames in the backing bean gets the selected row keys from the table, gets the corresponding Enames from the iterator (on which the table is based on) and prints them.
public String printSelectedEmpNames() {
        RowKeySet selectedEmps = getEmpTable().getSelectedRowKeys();    
        Iterator selectedEmpIter = selectedEmps.iterator();
        DCBindingContainer bindings =
                          (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        DCIteratorBinding empIter = bindings.findIteratorBinding("EmpView1Iterator");
        RowSetIterator empRSIter = empIter.getRowSetIterator();
         while(selectedEmpIter.hasNext()){
           Key key = (Key)((List)selectedEmpIter.next()).get(0);
           Row currentRow = empRSIter.getRow(key);
           System.out.println(currentRow.getAttribute("Ename"));
         }
         return null;

      }
We run the page and click button to check the selected rows.
empTableMultiSelect-thumb-321x325-20890.jpg
As we've selected 7 rows, clicking on the "Print selected Emps" button is expected to print 7 Enames.

But..... It just prints only one Ename.

CLARK
Well, this is because of the selectedRowKeys property of the af:table. Let us try removing that and see if we get the expected output.
<af:table value="#{bindings.EmpView1.collectionModel}" var="row"
                  rows="#{bindings.EmpView1.rangeSize}"
                  emptyText="#{bindings.EmpView1.viewable ? 'No data to display.' : 'Access Denied.'}"
                  fetchSize="#{bindings.EmpView1.rangeSize}"
                  rowBandingInterval="0"

                  selectionListener="#{bindings.EmpView1.collectionModel.makeCurrent}"
                  rowSelection="multiple" id="t1"
                  binding="#{backingBeanScope.EmpBean.empTable}">
Now, when we run the page, select 7 rows and click on the print button, it prints out
JONES
ALLEN
CLARK
WARD
SMITH
MARTIN
BLAKE
That is what we expected. Now, the question is why this happens?. It is because, since value of this selectedRowKeys property is #{bindings.EmpView1.collectionModel.selectedRow}, the selectedRowKeys will contain only the "row which is selected last". By unsetting this attribute, we let the table to push all the selected rows to selectedRowKeys, which will help us during
getEmpTable().getSelectedRowKeys();
in the backing bean. JDeveloper automatically adds this property to the ADF Table when it is created by dragging from the data control. So, removing this property from the af:table would get us desired result.