Pages

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");
attr.setInputValue("test");

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

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


// 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
bindings.refreshControl();
iterBind.executeQuery();
iterBind.refresh(DCIteratorBinding.RANGESIZE_UNLIMITED);

// 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.setId("page1");
menuPage1.setText("Page 1");
menuPage1.setActionExpression(getMethodExpression("page1"));

RichCommandButton button = new RichCommandButton();
button.setValueExpression("disabled",getValueExpression("#{!bindings."+item+".enabled}"));
button.setId(item);
button.setText(item);
MethodExpression me = getMethodExpression("#{bindings."+item+".execute}");
button.addActionListener(new MethodExpressionActionListener(me));
footer.getChildren().add(button);


// 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();
input.setValueExpression("value",getValueExpression("#{bindings."+item+".inputValue}"));
input.setValueExpression("label",getValueExpression("#{bindings."+item+".hints.label}"));
input.setId(item);
panelForm.getChildren().add(input);



// 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 ) {

resetValueInputItems(adfFacesContext,item);

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

// 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 {
response.sendRedirect(url);
} catch (Exception ex) {
ex.printStackTrace();
}

// PPR refresh a jsf component
AdfFacesContext.getCurrentInstance().addPartialTarget(UIComponent);


// 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}",
Object.class);
return (OEServiceImpl)valueExp.getValue(elContext);
}


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


// 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);
cc.getCurrentViewPort().getExceptionData().printStackTrace(pw);
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()) {
table.setRowKey(facesRowKey);
Object o = table.getRowData();
JUCtrlHierNodeBinding rowData = (JUCtrlHierNodeBinding)o;
Row row = rowData.getRow();
Test testRow = (Test)((DCDataRow)row).getDataProvider() ;
}

30 comments:

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

    great job!

    ReplyDelete
  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,
    argtypes);

    try{
    exp.getMethodInfo(elContext);
    }
    catch(Exception e){
    (e.getMessage());
    }


    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?

    thanx.

    ReplyDelete
  3. Hi Dimitrios,

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

    thanks Edwin

    ReplyDelete
  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:

    http://dstas.blogspot.com/2009/03/adding-different-actionlisteners.html

    Regards,

    Dimitrios.

    ReplyDelete
  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!

    ReplyDelete
  6. Hi,
    Thanks for your useful code for backing bean.
    Currently I am getting problem about Select one choise . please see here in forums http://forums.oracle.com/forums/thread.jspa?messageID=3506622&#3506622

    I wish you will help me .

    regards.
    zakir
    =====

    ReplyDelete
  7. Please solution see Select one radio .

    http://zakirpro.blogspot.com/2009/06/usefull-code-to-get-new-value-of-select.html

    zakir
    =====

    ReplyDelete
  8. Thank you very much.

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

    ReplyDelete
  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.

    ReplyDelete
  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 ?

    ReplyDelete
  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.

    ReplyDelete
  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.

    thanks.

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

    https://gist.github.com/1226450

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

    ReplyDelete
  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

    thanks

    ReplyDelete
  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 =
    facesContext.getApplication().getExpressionFactory().createMethodExpression(facesContext.getELContext(),
    "#{pageFlowScope.myBean.saveMethod}",
    null,
    new Class[] { ActionEvent.class });
    saveLink.addActionListener(new MethodExpressionActionListener(mbForSave));


    but how to set from and to parameters programmitically?

    ReplyDelete
  17. Hi,

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

    thanks

    ReplyDelete
  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 =
    facesContext.getApplication().getExpressionFactory();
    ValueExpression exp =
    expressionFactory.createValueExpression(elContext, el,
    Object.class);
    return exp.getValue(elContext);
    }

    ReplyDelete
    Replies
    1. Hi,

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

      thanks

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

    ReplyDelete
    Replies
    1. Hi,

      do you mean something like this ( only works on ldap providers ) http://biemond.blogspot.nl/2011/10/using-fmw-identitystore-for-your-user.html

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

      Thanks

      Delete
  20. Amazing code ! Love it :)

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

    ReplyDelete
  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?

    ReplyDelete
    Replies
    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 + ", ";
      }

      http://biemond.blogspot.nl/2011/10/using-fmw-identitystore-for-your-user.html

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

      or call the identityservice WS
      http://biemond.blogspot.nl/2012/04/how-to-use-human-workflow-web-services.html

      Hope this helps

      Delete
  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.

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

    I want ask
    about getting my APplicationModule
    getAm();

    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
    :D

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

    ReplyDelete
  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

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

    ReplyDelete