Saturday, March 14, 2009

Some handy code for backing beans ( ADF & JSF )

Here some code which you can use in your backing beans, I use this code all the time. With this you can retrieve the data or actions from the ADF page definition or create new uicomponents with ADF definitions and some JSF methods.

I'll keep this page up to date. Let me know if you have some code.

// print the roles of the current user
for ( String role : ADFContext.getCurrent().getSecurityContext().getUserRoles() ) {
System.out.println("role "+role);

// get the ADF security context and test if the user has the role users
SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
if ( sec.isUserInRole("users") ) {
// is the user valid
public boolean isAuthenticated() {
return ADFContext.getCurrent().getSecurityContext().isAuthenticated();
// return the user
public String getCurrentUser() {
return ADFContext.getCurrent().getSecurityContext().getUserName();

// get the binding container
BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();

// get an ADF attributevalue from the ADF page definitions
AttributeBinding attr = (AttributeBinding)bindings.getControlBinding("test");

// get an Action or MethodAction
OperationBinding method = bindings.getOperationBinding("methodAction");
List errors = method.getErrors();

method = bindings.getOperationBinding("methodAction");
Map paramsMap = method.getParamsMap();
paramsMap.put("param","value") ;

// Get the data from an ADF tree or table
DCBindingContainer dcBindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();

FacesCtrlHierBinding treeData = (FacesCtrlHierBinding)bc.getControlBinding("tree");
Row[] rows = treeData.getAllRowsInRange();

// Get a attribute value of the current row of iterator
DCIteratorBinding iterBind= (DCIteratorBinding)dcBindings.get("testIterator");
String attribute = (String)iterBind.getCurrentRow().getAttribute("field1");

// Get the error
String error = iterBind.getError().getMessage();

// refresh the iterator

// Get all the rows of a iterator
Row[] rows = iterBind.getAllRowsInRange();
TestData dataRow = null;
for (Row row : rows) {
dataRow = (TestData)((DCDataRow)row).getDataProvider();

// Get the current row of a iterator , a different way
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), "#{bindings.testIter.currentRow.dataProvider}", TestHead.class);
TestHead test = (TestHead)ve.getValue(ctx.getELContext());

// Get a session bean
FacesContext ctx = FacesContext.getCurrentInstance();
ExpressionFactory ef = ctx.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(ctx.getELContext(), "#{testSessionBean}", TestSession.class);
TestSession test = (TestSession)ve.getValue(ctx.getELContext());

// main jsf page
DCBindingContainer dc = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
// taskflow binding
DCTaskFlowBinding tf = (DCTaskFlowBinding)dc.findExecutableBinding("dynamicRegion1");
// pagedef of a page fragment
JUFormBinding form = (JUFormBinding) tf.findExecutableBinding("regions_employee_regionPageDef");
// handle to binding container of the region.
DCBindingContainer dcRegion = form;

// return a methodexpression like a control flow case action or ADF pagedef action
private MethodExpression getMethodExpression(String name) {
Class [] argtypes = new Class[1];
argtypes[0] = ActionEvent.class;
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createMethodExpression(elContext,name,null,argtypes);

RichCommandMenuItem menuPage1 = new RichCommandMenuItem();
menuPage1.setText("Page 1");

RichCommandButton button = new RichCommandButton();
MethodExpression me = getMethodExpression("#{bindings."+item+".execute}");
button.addActionListener(new MethodExpressionActionListener(me));

// get a value
private ValueExpression getValueExpression(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
Application app = facesCtx.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesCtx.getELContext();
return elFactory.createValueExpression(elContext, name, Object.class);
// an example how to use this
RichInputText input = new RichInputText();

// catch an exception and show it in the jsf page
catch(Exception e) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
FacesContext.getCurrentInstance().addMessage(null, msg);

FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, msgHead , msgDetail);
facesContext.addMessage(uiComponent.getClientId(facesContext), msg);

// reset all the child uicomponents
private void resetValueInputItems(AdfFacesContext adfFacesContext,
UIComponent component){
List<UIComponent> items = component.getChildren();
for ( UIComponent item : items ) {


if ( item instanceof RichInputText ) {
RichInputText input = (RichInputText)item;
if ( !input.isDisabled() ) {
input.resetValue() ;
} else if ( item instanceof RichInputDate ) {
RichInputDate input = (RichInputDate)item;
if ( !input.isDisabled() ) {
input.resetValue() ;

// redirect to a other url
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
HttpServletResponse response = (HttpServletResponse)ectx.getResponse();
String url = ectx.getRequestContextPath()+"/adfAuthentication?logout=true&end_url=/faces/start.jspx";

try {
} catch (Exception ex) {

// PPR refresh a jsf component

// find a jsf component
private UIComponent getUIComponent(String name) {
FacesContext facesCtx = FacesContext.getCurrentInstance();
return facesCtx.getViewRoot().findComponent(name) ;

// get the adf bc application module
private OEServiceImpl getAm(){
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = fc.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, "#{data.OEServiceDataControl.dataProvider}",
return (OEServiceImpl)valueExp.getValue(elContext);

// change the locale
Locale newLocale = new Locale(this.language);
FacesContext context = FacesContext.getCurrentInstance();

// get the stacktrace of a not handled exception
private ControllerContext cc = ControllerContext.getInstance();

public String getStacktrace() {
if ( cc.getCurrentViewPort().getExceptionData()!=null ) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
return sw.toString();
return null;

// get the selected rows from a table component
RowKeySet selection = resultTable.getSelectedRowKeys();
Object[] keys = selection.toArray();
List<Long> receivers = new ArrayList<Long>(keys.length);
for ( Object key : keys ) {
User user = modelFriends.get((Integer)key);

// get selected Rows of a table 2
for (Object facesRowKey : table.getSelectedRowKeys()) {
Object o = table.getRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
Test testRow = (Test)((DCDataRow)row).getDataProvider() ;


  1. hi,
    I've been your seeing blog for some time and it´s very interesting

    great job!

  2. Hi,
    I have used same code as your getMethodExpresion to create a methodExpression for an existing method accepting ActionEvent parameter. But in order to getMethodExpression for Action method that does not accept ActionEvent parameter i used the following code :

    public static MethodExpression getMethodExpressionAction(String name) {
    Class[] argtypes = new Class[0];
    FacesContext facesCtx = FacesContext.getCurrentInstance();
    Application app = facesCtx.getApplication();
    ExpressionFactory elFactory = app.getExpressionFactory();
    ELContext elContext = facesCtx.getELContext();

    MethodExpression exp=elFactory.createMethodExpression(elContext, name, null,

    catch(Exception e){

    return exp;

    I used the above code because it was complaining on not finding ActionEvent.class as an input parameter.

    can you please check on that?


  3. Hi Dimitrios,

    can you send me an small example, so I can test is myself.

    thanks Edwin

  4. Hi Edwin,
    I found out that MethodExpressions with Different arguments are need for different type of ActionListeners..
    So i created a post about it.
    You can check at:



  5. Hi Edwin,

    Thanks, for this code, I've found some of it very useful. It would be nice to also have a blog post with useful code that can be used when extending the default business component classes. I'm sure people would find this useful too. Could that be something you could put up on your blog too?

    Good work on this on though!

  6. Hi,
    Thanks for your useful code for backing bean.
    Currently I am getting problem about Select one choise . please see here in forums

    I wish you will help me .


  7. Please solution see Select one radio .


  8. Thank you very much.

  9. That was incredible, backing bean to session and managed bean code...

  10. I would like to point out a couple of problems with the way you access the binding container of a fragment in a region:
    JUFormBinding form = (JUFormBinding) tf.findExecutableBinding("regions_employee_regionPageDef");

    1) There is no guarantee, the name "regions_employee_regionPageDef" will always be the same. This is a name generated at runtime that is not part of the definition. It is not part of the public API.
    2) The object retrieved using this mechanism is not valid unless it is made current. There are mechanisms in the framework that ensure the object is in context before accessing it but you bypass the safeguard when you access the object directly. One of the issue is that you might be holding on a released object. So the only time it is safe to access it, is when it is the current binding container.

  11. I am using modified code for resetting the value by using setvalue to null but on clicking reset button is the value being refreshed. Could you tell why ?

  12. Could you tell why reset button has to be clicked twice. It is supposed to refresh the first time or am i missing something.

  13. Hi,

    It seems like you don't set the client attribute on true or something went wrong with the PPR on the uicomponent.

    else you need to send me more details.


  14. Edwin,
    The code fragment is mentioned below and yes i have set the client attribute to true.

    The fragment is mentioned below. Does setting inputvalue to null have some adverse effect on ppr

  15. Hi,

    Are using immediate on the button and maybe you need to refresh the ADF binding or reset the DataControl ( if you are using ADF)

    else you need to make a simple testcase


  16. Hi,

    is there any way to pass parameter in AddActionListener?

    in jsf I can write something like this:

    I need to generate this kind of code programmitically. it generate multiple save links.

    Now I can write programmitically like:

    RichCommandLink saveLink = new RichCommandLink();
    MethodExpression mbForSave =
    new Class[] { ActionEvent.class });
    saveLink.addActionListener(new MethodExpressionActionListener(mbForSave));

    but how to set from and to parameters programmitically?

  17. Hi,

    don't know but in 11g we are now using setPropertyListener , maybe this much easier.


  18. hi can you explain me what is the use of below code...

    private static Object evaluateEL(String el) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory =
    ValueExpression exp =
    expressionFactory.createValueExpression(elContext, el,
    return exp.getValue(elContext);

    1. Hi,

      with this you can provide the el expression and give back the managed bean object or the adf binding object.


  19. hi , Please any one let me know how to update ADF roles programatically from Java code.

    1. Hi,

      do you mean something like this ( only works on ldap providers )

      Or do you mean the application and enterprise roles of ADF security -> jazn.xml


  20. Amazing code ! Love it :)

  21. how can i apply iteration on panel box in ADF?
    Please guide me. Thanks in Advance.

  22. Hi Edwin,

    I was trying to use below code to fetch the logged in user roles, but I am getting 'anonymous-role' only.

    SecurityContext sec = ADFContext.getCurrent().getSecurityContext();
    if ( sec.isUserInRole("users") ) {

    Is there any way I can get the roles using Human Workflow API?
    or is there any way to fetch the roles programatically?

    1. Hi,

      you got a few options

      do this

      ADFContext adfCtx = ADFContext.getCurrent();
      SecurityContext secCntx = adfCtx.getSecurityContext();

      this.username = secCntx.getUserName();

      for (String role : secCntx.getUserRoles()) {
      this.roles = this.roles + role + ", ";

      this should work else make it the first authenticator or use libovd

      or call the identityservice WS

      Hope this helps

  23. Thanks a lot Edwin.

    But when I execute below code :

    String username = secCntx.getUserName();

    for (String role : secCntx.getUserRoles()) {
    //this.roles = this.roles + role + ", ";
    System.out.println(" roles : "+role);

    The result is

    roles : authenticated-role
    roles : anonymous-role

    I am not getting the appropriate application user roles.

    Though I am getting the correct user name.

  24. Hello Edwin Biemond ,
    All our projects and codes are helpful,
    thanks alot for your efforts

    I want ask
    about getting my APplicationModule

    it returns NULL !!!
    and I used it in the beforephase function to create menus

    I know it's long period to ask this question in 2015
    but in our country we recently use ADF

  25. Thank you so much Edwin for the wonderful blog. But i cannot find more from your blog recently.

  26. Dear Biemond

    I have a business case I want to

    fill a table at run time depend on selected value by assigning values for each column and rows in repeated way

  27. Great work Edwin....keep it up !!!