Saturday, November 21, 2009

OAF : "The search cannot be executed because the table has pending changes that would be lost. "

ERROR Message :

"The search cannot be executed because the table has pending changes that would be lost. "

----Below is the solution if you are getting the above messages:

Solution :: Add some code in ProcessFormRequest just After calling the AM method:

if ("N".equals(Neelmani)) {
if (pageContext.getParameter(queryBean.getGoButtonName().toString()) !=
null) {
Serializable Params[] =
{ p1, p2, new Number(pageContext.getUserId()) };
Class[] paramTypes =
{ String.class, String.class, Number.class };
am.invokeMethod("getNameSearchResults", Params,
paramTypes);
OAAdvancedTableBean table =
(OAAdvancedTableBean)webBean.findChildRecursive("EmployeeTBL");
// When handling a user initiated search, we always need to execute
// the query so we pass "false" to queryData().
table.queryData(pageContext, false);
}
}

OAF : Session

How to Handle the Session into OAF?
-------------------------------------------

String myName="Neelmani";
pageContext.putSessionValue("Name",myName);//Set The Value to Session

String myName=(String)pageContext.getSessionValue("Name"); //get The Value from Session

OAF : Partial Page Rendering : PPR

How to Implement PPR into OAF ?

${oa.ABCPVO1.NeelmaniRender} // Set this value for RENDER attribute of the UI Component


Put the below code into ProcessFormRequest
------------------------------------------------------

if ("entityPoplistChange".equals(pageContext.getParameter(OAWebBeanConstants.EVENT_PARAM)))
{
String entitypoplist=pageContext.getParameter("Entitypoplist");
Serializable[] param = {entitypoplist};
am.invokeMethod("handlePositionChangeEvent", param);
}

Put the below code into xxxAMImpl.java
------------------------------------------------

public void handlePositionChangeEvent(String param)
{
OAViewObject vo = (OAViewObject)findViewObject("ABCPVO1");
OARow row = (OARow)vo.first();

if(s.equals("param"))
{
row.setAttribute("NeelmaniRender", Boolean.TRUE);
row.setAttribute("JaiswalRender", Boolean.FALSE);
}
else
{
row.setAttribute("JaiswalRender", Boolean.TRUE);
row.setAttribute("NeelmaniRender", Boolean.FALSE);
}
}

OAF : Add New Row into OA Table :: Add Another Row

Put the below come into ProcessFormRequest
------------------------------------------------------

if(pageContext.getParameter("AddSiteRow") != null)
{
am.invokeMethod("insertEmptyRow");
}

Put the below come into xxxAMImpl.java
------------------------------------------------

public void insertEmptyRow()
{
EmployeesVOImpl empVo = getEmployeesVO1();
EmployeesVORowImpl emptyrow = (EmployeesVORowImpl)empVo.createRow();
empVo.last();
empVo.next();
empVo.insertRow(emptyrow,"ABC"); //'ABC' is HardCod value inserted based on the requirement in this example
siteVo.setCurrentRow(emptyrow);
emptyrow.setNewRowState(Row.STATUS_INITIALIZED);
}

OAF : Set the Where Clause at Run Time.

Put the below code into xxxAMImpl.java
------------------------------------------------

public void empSearch(){

String ssn="1001";
String name="Neelmani";
EmployeesVOImpl empVO = getEmployeesVO3();
empVO.setWhereClause("EMP_SSN = :1 AND EMP_NAME = :2");
empVO.setWhereClauseParam(0,ssn);
empVO.setWhereClauseParam(1,name);
empVO.executeQuery();
}

OAF : Error Message

Put the below code into xxxAMImpl.java
------------------------------------------------

public void errorMessage(){


if (Row1.getClientId() ==null)
{
MessageToken[] errToken = {new MessageToken("ABC", Row1.getClientName()),
new MessageToken("XYZ", Row1.getClintId())};
throw new OAException("ABC","ABC_VALIDATION_NULL", errToken);
}

}

OAF : Confirmation message

Put the below code into xxxAMImpl.java
------------------------------------------------

public void confirmationMessage(){

String ok="Hello";
if(ok.equals("Hello")){
String msg = this.getOADBTransaction().getMessage("ABC","ABC_ADD_MESSAGE_SUCCESS", null);
throw new OAException(msg,OAException.CONFIRMATION);
}
}

ADF : Insert the Row into Table.

INSERT

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.driver.OracleDriver;
public class TestClass {
public TestClass() {
}
Get the Connection
----------------------
public static Connection getConnection() throws SQLException {
String username = "hr";
String password = "hr";
String thinConn = "jdbc:oracle:thin:@10.18.2.49:1521:XE";
DriverManager.registerDriver(new OracleDriver());
Connection conn =
DriverManager.getConnection(thinConn, username, password);
conn.setAutoCommit(true);
return conn;
}

CODE
-------

public String insert() throws SQLException {
// Add event code here...
System.out.println("Inside insert::");
Connection conn= null;
PreparedStatement ps=null;
ResultSet rs= null;
String query ="INSERT INTO DEPARTMENTS(DEPARTMENT_ID,DEPARTMENT_NAME) values(?,?)";
System.out.println("Query:::>> "+query);
conn=getConnection();
ps=conn.prepareStatement(query);
System.out.println("Inserting Values::");
ps.setString(1,"999");
ps.setString(2, "CID");
ps.executeUpdate();
ps.close();
System.out.println("Exiting::");
return "success";
}
}

11G : Insert the row into ADF table using Store Procedure.


public String insert() throws SQLException{
// Add event code here...
System.out.println("Insert()...");
System.out.println("empid..."+empid);
System.out.println("startdate..."+startdate);
System.out.println("enddate..."+enddate);
System.out.println("jobid..."+jobid);
System.out.println("deptid..."+deptid);
System.out.println("::::::::::::::");
String procedure="{ call ADD_JOB_HISTORY(?,?,?,?,?) }";
CallableStatement cs=null;
Connection conn=null;
ResultSet rs=null;
try {
conn = DBConnectionClass.getConnection();
cs = conn.prepareCall(procedure);
cs.setString(1, empid); //IN
cs.setDate(2, startdate); //IN
cs.setDate(3, enddate); //IN
cs.setString(4, jobid); //IN
cs.setString(5, deptid); //IN
cs.execute();
rs = cs.getResultSet();
} catch (SQLException e) {
System.out.println("Inside Catch-Exception- "+e);
} finally {
System.out.println("Inside Finally");
cs.close();
}
return "success";
}


Store Procedure
-------------------
create or replace
PROCEDURE add_job_history
( p_emp_id job_history.employee_id%type
, p_start_date job_history.start_date%type
, p_end_date job_history.end_date%type
, p_job_id job_history.job_id%type
, p_department_id job_history.department_id%type
)
IS
BEGIN
INSERT INTO job_history (employee_id, start_date, end_date,
job_id, department_id)
VALUES(p_emp_id, p_start_date, p_end_date, p_job_id, p_department_id);
END add_job_history;


-----------------------
      public String getFirstName(){
           Connection con = null;
           Statement stmt = null;
           ResultSet rs = null;
           String FirstName = null;
           try {
               con = ConnectionClass.getConnection();
               stmt = con.createStatement();
               String query = "Select first_name from employees where empId = '101'";
               rs = stmt.executeQuery(query);
               while(rs.next()){
                   FirstName = rs.getString("first_name");
               }
           }
           catch(Exception e){
               e.printStackTrace();
           }
           finally{
               ConnectionClass.close(rs,stmt,con);
           }
           return corpBr;
       }

JSF 1.2 : Session

How to Create Session ?
-----------------

FacesContext fctx=FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest)fctx.getExternalContext().getRequest();
HttpSession session=req.getSession();

How to Set the Value into Session ?
------------------------------
session.setAttribute("userid", login); /// where login is the value which comes from the login screen
session.setAttribute("password", pwd); /// where password is the value which comes from the login screen
System.out.println("Login/Password set in to Session...");


How to Get the Value from Session ?
--------------------------------

String u = (String)session.getAttribute("userid"); //getting arrribute from session
System.out.println("UserName from Session-> "+u);
String p = (String)session.getAttribute("password");//getting arrribute from session
System.out.println("Password from Session-> "+p);

How to Invalidate the Session ?
---------------------

HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
session.invalidate();

11G : How to insert the Row Progamatically in ADF Table?

public String Insert() {

try{
FacesContext fctx=FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest)fctx.getExternalContext().getRequest();
HttpSession session=req.getSession();
String username=(String)session.getAttribute("username");
String amDef = "mail.model.queries.AppModule";
String config = "AppModuleLocal";
ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
ViewObject mailVO=am.findViewObject("MailView1");
mailVO.executeQuery();
MailViewRowImpl mailRow=(MailViewRowImpl)mailVO.createRow();


 SequenceImpl mailSeq = new SequenceImpl("TEST_MAIL_SEQ", am );

 mailRow.setMailId(mailSeq .getSequenceNumber());
mailRow.setReceiver(to);
mailRow.setSender(username);
mailRow.setCc(cc);
mailRow.setCc(bcc);
mailRow.setCc(subject);
mailRow.setCc(message);

mailVO.insertRow(mailRow);
am.getTransaction().commit();
}catch(Exception e){

}
finally{
            if(am=null){
                Configuration.releaseRootApplicationModule(am, true);
            }
}

return "success";
}

11G : How to delete the row Progamatically in ADF ?

public String deleteDepartments() {
// Add event code here...
String seletedDept=JSFUtils.resolveExpression("#{bindings.DepartmentId.inputValue}").toString();
System.out.println("SeletedDepartment:: "+seletedDept);

String amDef = "model.queries.AppModule";
String config = "AppModuleLocal";
ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
ViewObject deptVO=am.findViewObject("DepartmentsView1");
RowSetIterator DeptIter=deptVO.createRowSetIterator("DeptIter");
int rowcount= deptVO.getRowCount();
if(rowcount > 0)
{
DeptIter.setRangeStart(0);
DeptIter.setRangeSize(rowcount);
for (int i = rowcount-1; i >= 0 ; i--)
{
DepartmentsViewRowImpl depteRow = (DepartmentsViewRowImpl)DeptIter.getRowAtRangeIndex(i);
if(depteRow.getAttribute("DepartmentId").toString().equals(seletedDept)){
depteRow.remove();
}
}
}
}

ADF : getConnection

ADF 11g : How to get the current connection in ADF?

//put the code into XXXImpl.java (AM)

private Connection getCurrentConnection() throws SQLException {
/* Note that we never execute this statement, so no commit really happens */
PreparedStatement st = getDBTransaction().createPreparedStatement("commit",1);
Connection conn = st.getConnection();
st.close();
return conn;
}


ADF : Util Classes

import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.model.binding.DCParameter;
import oracle.adf.share.logging.ADFLogger;
import oracle.adfinternal.view.faces.bi.util.JsfUtils;
import oracle.binding.AttributeBinding;
import oracle.binding.BindingContainer;
import oracle.binding.ControlBinding;
import oracle.binding.OperationBinding;
import oracle.jbo.ApplicationModule;
import oracle.jbo.Key;
import oracle.jbo.Row;
import oracle.jbo.uicli.binding.JUCtrlValueBinding;
/**
* A series of convenience functions for dealing with ADF Bindings.
* Note: Updated for JDeveloper 11
* */
public class ADFUtils {
public static final ADFLogger LOGGER = ADFLogger.createADFLogger(ADFUtils.class);
/**
* Get application module for an application module data control by name.
* @param name application module data control name
* @return ApplicationModule
*/
public static ApplicationModule getApplicationModuleForDataControl(String name) {
return (ApplicationModule)JsfUtils.resolveExpression("#{data." + name +
".dataProvider}");
}
/**
* A convenience method for getting the value of a bound attribute in the
* current page context programatically.
* @param attributeName of the bound value in the pageDef
* @return value of the attribute
*/
public static Object getBoundAttributeValue(String attributeName) {
return findControlBinding(attributeName).getInputValue();
}
/**
* A convenience method for setting the value of a bound attribute in the
* context of the current page.
* @param attributeName of the bound value in the pageDef
* @param value to set
*/
public static void setBoundAttributeValue(String attributeName,
Object value) {
findControlBinding(attributeName).setInputValue(value);
}
/**
* Returns the evaluated value of a pageDef parameter.
* @param pageDefName reference to the page definition file of the page with the parameter
* @param parameterName name of the pagedef parameter
* @return evaluated value of the parameter as a String
*/
public static Object getPageDefParameterValue(String pageDefName,
String parameterName) {
BindingContainer bindings = findBindingContainer(pageDefName);
DCParameter param =
((DCBindingContainer)bindings).findParameter(parameterName);
return param.getValue();
}
/**
* Convenience method to find a DCControlBinding as an AttributeBinding
* to get able to then call getInputValue() or setInputValue() on it.
* @param bindingContainer binding container
* @param attributeName name of the attribute binding.
* @return the control value binding with the name passed in.
*
*/
public static AttributeBinding findControlBinding(BindingContainer bindingContainer,
String attributeName) {
if (attributeName != null) {
if (bindingContainer != null) {
ControlBinding ctrlBinding =
bindingContainer.getControlBinding(attributeName);
if (ctrlBinding instanceof AttributeBinding) {
return (AttributeBinding)ctrlBinding;
}
}
}
return null;
}
/**
* Convenience method to find a DCControlBinding as a JUCtrlValueBinding
* to get able to then call getInputValue() or setInputValue() on it.
* @param attributeName name of the attribute binding.
* @return the control value binding with the name passed in.
*
*/
public static AttributeBinding findControlBinding(String attributeName) {
return findControlBinding(getBindingContainer(), attributeName);
}
/**
* Return the current page's binding container.
* @return the current page's binding container
*/
public static BindingContainer getBindingContainer() {
return (BindingContainer)JSFUtils.resolveExpression("#{bindings}");
}
/**
* Return the Binding Container as a DCBindingContainer.
* @return current binding container as a DCBindingContainer
*/
public static DCBindingContainer getDCBindingContainer() {
return (DCBindingContainer)getBindingContainer();
}
/**
* Get List of ADF Faces SelectItem for an iterator binding.
*
* Uses the value of the 'valueAttrName' attribute as the key for
* the SelectItem key.
*
* @param iteratorName ADF iterator binding name
* @param valueAttrName name of the value attribute to use
* @param displayAttrName name of the attribute from iterator rows to display
* @return ADF Faces SelectItem for an iterator binding
*/
public static List selectItemsForIterator(String iteratorName,
String valueAttrName,
String displayAttrName) {
return selectItemsForIterator(findIterator(iteratorName),
valueAttrName, displayAttrName);
}
/**
* Get List of ADF Faces SelectItem for an iterator binding with description.
*
* Uses the value of the 'valueAttrName' attribute as the key for
* the SelectItem key.
*
* @param iteratorName ADF iterator binding name
* @param valueAttrName name of the value attribute to use
* @param displayAttrName name of the attribute from iterator rows to display
* @param descriptionAttrName name of the attribute to use for description
* @return ADF Faces SelectItem for an iterator binding with description
*/
public static List selectItemsForIterator(String iteratorName,
String valueAttrName,
String displayAttrName,
String descriptionAttrName) {
return selectItemsForIterator(findIterator(iteratorName),
valueAttrName, displayAttrName,
descriptionAttrName);
}
/**
* Get List of attribute values for an iterator.
* @param iteratorName ADF iterator binding name
* @param valueAttrName value attribute to use
* @return List of attribute values for an iterator
*/
public static List attributeListForIterator(String iteratorName,
String valueAttrName) {
return attributeListForIterator(findIterator(iteratorName),
valueAttrName);
}
/**
* Get List of Key objects for rows in an iterator.
* @param iteratorName iterabot binding name
* @return List of Key objects for rows
*/
public static List keyListForIterator(String iteratorName) {
return keyListForIterator(findIterator(iteratorName));
}
/**
* Get List of Key objects for rows in an iterator.
* @param iter iterator binding
* @return List of Key objects for rows
*/
public static List keyListForIterator(DCIteratorBinding iter) {
List attributeList = new ArrayList();
for (Row r : iter.getAllRowsInRange()) {
attributeList.add(r.getKey());
}
return attributeList;
}
/**
* Get List of Key objects for rows in an iterator using key attribute.
* @param iteratorName iterator binding name
* @param keyAttrName name of key attribute to use
* @return List of Key objects for rows
*/
public static List keyAttrListForIterator(String iteratorName,
String keyAttrName) {
return keyAttrListForIterator(findIterator(iteratorName), keyAttrName);
}
/**
* Get List of Key objects for rows in an iterator using key attribute.
*
* @param iter iterator binding
* @param keyAttrName name of key attribute to use
* @return List of Key objects for rows
*/
public static List keyAttrListForIterator(DCIteratorBinding iter,
String keyAttrName) {
List attributeList = new ArrayList();
for (Row r : iter.getAllRowsInRange()) {
attributeList.add(new Key(new Object[] { r.getAttribute(keyAttrName) }));
}
return attributeList;
}
/**
* Get a List of attribute values for an iterator.
*
* @param iter iterator binding
* @param valueAttrName name of value attribute to use
* @return List of attribute values
*/
public static List attributeListForIterator(DCIteratorBinding iter,
String valueAttrName) {
List attributeList = new ArrayList();
for (Row r : iter.getAllRowsInRange()) {
attributeList.add(r.getAttribute(valueAttrName));
}
return attributeList;
}
/**
* Find an iterator binding in the current binding container by name.
*
* @param name iterator binding name
* @return iterator binding
*/
public static DCIteratorBinding findIterator(String name) {
DCIteratorBinding iter =
getDCBindingContainer().findIteratorBinding(name);
if (iter == null) {
throw new RuntimeException("Iterator '" + name + "' not found");
}
return iter;
}
public static DCIteratorBinding findIterator(String bindingContainer, String iterator) {
DCBindingContainer bindings =
(DCBindingContainer)JSFUtils.resolveExpression("#{" + bindingContainer + "}");
if (bindings == null) {
throw new RuntimeException("Binding container '" +
bindingContainer + "' not found");
}
DCIteratorBinding iter = bindings.findIteratorBinding(iterator);
if (iter == null) {
throw new RuntimeException("Iterator '" + iterator + "' not found");
}
return iter;
}
public static JUCtrlValueBinding findCtrlBinding(String name){
JUCtrlValueBinding rowBinding =
(JUCtrlValueBinding)getDCBindingContainer().findCtrlBinding(name);
if (rowBinding == null) {
throw new RuntimeException("CtrlBinding " + name + "' not found");
}
return rowBinding;
}
/**
* Find an operation binding in the current binding container by name.
*
* @param name operation binding name
* @return operation binding
*/
public static OperationBinding findOperation(String name) {
OperationBinding op =
getDCBindingContainer().getOperationBinding(name);
if (op == null) {
throw new RuntimeException("Operation '" + name + "' not found");
}
return op;
}
/**
* Find an operation binding in the current binding container by name.
*
* @param bindingContianer binding container name
* @param opName operation binding name
* @return operation binding
*/
public static OperationBinding findOperation(String bindingContianer,
String opName) {
DCBindingContainer bindings =
(DCBindingContainer)JSFUtils.resolveExpression("#{" + bindingContianer + "}");
if (bindings == null) {
throw new RuntimeException("Binding container '" +
bindingContianer + "' not found");
}
OperationBinding op =
bindings.getOperationBinding(opName);
if (op == null) {
throw new RuntimeException("Operation '" + opName + "' not found");
}
return op;
}
/**
* Get List of ADF Faces SelectItem for an iterator binding with description.
*
* Uses the value of the 'valueAttrName' attribute as the key for
* the SelectItem key.
*
* @param iter ADF iterator binding
* @param valueAttrName name of value attribute to use for key
* @param displayAttrName name of the attribute from iterator rows to display
* @param descriptionAttrName name of the attribute for description
* @return ADF Faces SelectItem for an iterator binding with description
*/
public static List selectItemsForIterator(DCIteratorBinding iter,
String valueAttrName,
String displayAttrName,
String descriptionAttrName) {
List selectItems = new ArrayList();
for (Row r : iter.getAllRowsInRange()) {
selectItems.add(new SelectItem(r.getAttribute(valueAttrName),
(String)r.getAttribute(displayAttrName),
(String)r.getAttribute(descriptionAttrName)));
}
return selectItems;
}
/**
* Get List of ADF Faces SelectItem for an iterator binding.
*
* Uses the value of the 'valueAttrName' attribute as the key for
* the SelectItem key.
*
* @param iter ADF iterator binding
* @param valueAttrName name of value attribute to use for key
* @param displayAttrName name of the attribute from iterator rows to display
* @return ADF Faces SelectItem for an iterator binding
*/
public static List selectItemsForIterator(DCIteratorBinding iter,
String valueAttrName,
String displayAttrName) {
List selectItems = new ArrayList();
for (Row r : iter.getAllRowsInRange()) {
selectItems.add(new SelectItem(r.getAttribute(valueAttrName),
(String)r.getAttribute(displayAttrName)));
}
return selectItems;
}
/**
* Get List of ADF Faces SelectItem for an iterator binding.
*
* Uses the rowKey of each row as the SelectItem key.
*
* @param iteratorName ADF iterator binding name
* @param displayAttrName name of the attribute from iterator rows to display
* @return ADF Faces SelectItem for an iterator binding
*/
public static List selectItemsByKeyForIterator(String iteratorName,
String displayAttrName) {
return selectItemsByKeyForIterator(findIterator(iteratorName),
displayAttrName);
}
/**
* Get List of ADF Faces SelectItem for an iterator binding with discription.
*
* Uses the rowKey of each row as the SelectItem key.
*
* @param iteratorName ADF iterator binding name
* @param displayAttrName name of the attribute from iterator rows to display
* @param descriptionAttrName name of the attribute for description
* @return ADF Faces SelectItem for an iterator binding with discription
*/
public static List selectItemsByKeyForIterator(String iteratorName,
String displayAttrName,
String descriptionAttrName) {
return selectItemsByKeyForIterator(findIterator(iteratorName),
displayAttrName,
descriptionAttrName);
}
/**
* Get List of ADF Faces SelectItem for an iterator binding with discription.
*
* Uses the rowKey of each row as the SelectItem key.
*
* @param iter ADF iterator binding
* @param displayAttrName name of the attribute from iterator rows to display
* @param descriptionAttrName name of the attribute for description
* @return ADF Faces SelectItem for an iterator binding with discription
*/
public static List selectItemsByKeyForIterator(DCIteratorBinding iter,
String displayAttrName,
String descriptionAttrName) {
List selectItems = new ArrayList();
for (Row r : iter.getAllRowsInRange()) {
selectItems.add(new SelectItem(r.getKey(),
(String)r.getAttribute(displayAttrName),
(String)r.getAttribute(descriptionAttrName)));
}
return selectItems;
}
/**
* Get List of ADF Faces SelectItem for an iterator binding.
*
* Uses the rowKey of each row as the SelectItem key.
*
* @param iter ADF iterator binding
* @param displayAttrName name of the attribute from iterator rows to display
* @return List of ADF Faces SelectItem for an iterator binding
*/
public static List selectItemsByKeyForIterator(DCIteratorBinding iter,
String displayAttrName) {
List selectItems = new ArrayList();
for (Row r : iter.getAllRowsInRange()) {
selectItems.add(new SelectItem(r.getKey(),
(String)r.getAttribute(displayAttrName)));
}
return selectItems;
}
/**
* Find the BindingContainer for a page definition by name.
*
* Typically used to refer eagerly to page definition parameters. It is
* not best practice to reference or set bindings in binding containers
* that are not the one for the current page.
*
* @param pageDefName name of the page defintion XML file to use
* @return BindingContainer ref for the named definition
*/
private static BindingContainer findBindingContainer(String pageDefName) {
BindingContext bctx = getDCBindingContainer().getBindingContext();
BindingContainer foundContainer =
bctx.findBindingContainer(pageDefName);
return foundContainer;
}
public static void printOperationBindingExceptions(List opList){
if(opList != null && !opList.isEmpty()){
for(Object error:opList){
LOGGER.severe( error.toString() );
}
}

*********************************************
 /**
     * Find an operation binding in the current binding container by name.
     *
     * @param name operation binding name
     * @return operation binding
     */
    public static OperationBinding findOperation(String name) {
        OperationBinding operation = getDCBindingContainer().getOperationBinding(name);
        if (operation == null) {
            throw new RuntimeException("Operation '" + name + NOT_FOUND);
        }
        return operation;
    }

*********************************************
 public static void refreshCurrentPage() {
        FacesContext context = FacesContext.getCurrentInstance();
        String currentView = context.getViewRoot().getViewId();
        ViewHandler vh = context.getApplication().getViewHandler();
        UIViewRoot x = vh.createView(context, currentView);
        context.setViewRoot(x);
    }

*********************************************
 public static String resolveFromResourceBundle(String paResourceBundle,
                                                   String paKey) {
        StringBuilder expression = new StringBuilder();
        expression.append("#{adfBundle['").append(paResourceBundle).append("'].").append(paKey).append("}");
        return resolveExpression(expression.toString(), String.class);
    }

*************************

  public static String resolveFromResourceBundle(String paResourceBundle,
                                                   String paKey,
                                                   Map dynamicParams) {
        // Determine the string from the resource bundle
        String resourceBundleValue =
            resolveFromResourceBundle(paResourceBundle, paKey);
        // Replace the dynamic parts of the string by looping through the map
        if (dynamicParams != null && !dynamicParams.isEmpty()) {
            for (Map.Entry entry : (Set)dynamicParams.entrySet()) {
                Object value = entry.getValue();
                // Transforming the key to the exact representation in the resource bundle string
                String key = "\\{" + entry.getKey() + "\\}";
                // Handling some special cases of a date
                if (value instanceof java.sql.Date) {
                    // Format the date before putting it into the string
                    java.sql.Date newDate = (java.sql.Date)value;
                    SimpleDateFormat formatDate =
                        new SimpleDateFormat(DATEFORMATPATTERN);
                    value = formatDate.format(newDate);
                }
                // Replacing all occurances of the key with the value
                resourceBundleValue =
                        resourceBundleValue.replaceAll(key, (String)value);
            }
        }
        // Returning the result String
        return resourceBundleValue;
    }

**************************************
 /**
     * Find an operation binding in the current binding container by name.
     *
     * @param name operation binding name
     * @return operation binding
     */
    public static OperationBinding findOperation(String name) {
        OperationBinding operation = getDCBindingContainer().getOperationBinding(name);
        if (operation == null) {
            throw new RuntimeException("Operation '" + name + NOT_FOUND);
        }
        return operation;
    }

*****************************************
    /**
    * Programmatic evaluation of EL.
    *
    * @param el EL to evaluate
    * @return Result of the evaluation
    */
    public 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);
    }
   
    /**
    * Programmatic invocation of a method that an EL evaluates to.
    * The method must not take any parameters.
    *
    * @param el EL of the method to invoke
    * @return Object that the method returns
    */
    public static Object invokeEL(String el) {
    return invokeEL(el, new Class[0], new Object[0]);
    }
   
    /**
    * Programmatic invocation of a method that an EL evaluates to.
    *
    * @param el EL of the method to invoke
    * @param paramTypes Array of Class defining the types of the parameters
    * @param params Array of Object defining the values of the parametrs
    * @return Object that the method returns
    */
    public static Object invokeEL(String el, Class[] paramTypes,
    Object[] params) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory =
    facesContext.getApplication().getExpressionFactory();
    MethodExpression exp =
    expressionFactory.createMethodExpression(elContext, el,
    Object.class, paramTypes);
   
    return exp.invoke(elContext, params);
    }
   
    /**
    * Sets a value into an EL object. Provides similar functionality to
    * the tag, except the from is
    * not an EL. You can get similar behavior by using the following...
   
    * setEL(to, evaluateEL(from))
    *
    * @param el EL object to assign a value
    * @param val Value to assign
    */
    public static void setEL(String el, Object val) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory expressionFactory =
    facesContext.getApplication().getExpressionFactory();
    ValueExpression exp =
    expressionFactory.createValueExpression(elContext, el,
    Object.class);
   
    exp.setValue(elContext, val);
    }
*****************************************

}

JSF : Util Classes

import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.MethodExpression;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import oracle.adf.model.binding.DCBindingContainer;
/**
* General useful static utilies for working with JSF.
* NOTE: Updated to use JSF 1.2 ExpressionFactory.
*
*/
public class JSFUtils {
private static final String NO_RESOURCE_FOUND = "Missing resource: ";
/**
* Method for taking a reference to a JSF binding expression and returning
* the matching object (or creating it).
* @param expression EL expression
* @return Managed object
*/
public static Object resolveExpression(String expression) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class);
return valueExp.getValue(elContext);
}
public static String resolveRemoteUser() {
FacesContext facesContext = getFacesContext();
ExternalContext ectx = facesContext.getExternalContext();
return ectx.getRemoteUser();
}
public static String resolveUserPrincipal() {
FacesContext facesContext = getFacesContext();
ExternalContext ectx = facesContext.getExternalContext();
HttpServletRequest request = (HttpServletRequest)ectx.getRequest();
return request.getUserPrincipal().getName();
}
public static Object resloveMethodExpression(String expression,
Class returnType,
Class[] argTypes,
Object[] argValues) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
MethodExpression methodExpression =
elFactory.createMethodExpression(elContext, expression, returnType,
argTypes);
return methodExpression.invoke(elContext, argValues);
}
/**
* Method for taking a reference to a JSF binding expression and returning
* the matching Boolean.
* @param expression EL expression
* @return Managed object
*/
public static Boolean resolveExpressionAsBoolean(String expression) {
return (Boolean)resolveExpression(expression);
}
/**
* Method for taking a reference to a JSF binding expression and returning
* the matching String (or creating it).
* @param expression EL expression
* @return Managed object
*/
public static String resolveExpressionAsString(String expression) {
return (String)resolveExpression(expression);
}
/**
* Convenience method for resolving a reference to a managed bean by name
* rather than by expression.
* @param beanName name of managed bean
* @return Managed object
*/
public static Object getManagedBeanValue(String beanName) {
StringBuffer buff = new StringBuffer("#{");
buff.append(beanName);
buff.append("}");
return resolveExpression(buff.toString());
}
/**
* Method for setting a new object into a JSF managed bean
* Note: will fail silently if the supplied object does
* not match the type of the managed bean.
* @param expression EL expression
* @param newValue new value to set
*/
public static void setExpressionValue(String expression, Object newValue) {
FacesContext facesContext = getFacesContext();
Application app = facesContext.getApplication();
ExpressionFactory elFactory = app.getExpressionFactory();
ELContext elContext = facesContext.getELContext();
ValueExpression valueExp =
elFactory.createValueExpression(elContext, expression,
Object.class);
//Check that the input newValue can be cast to the property type
//expected by the managed bean.
//If the managed Bean expects a primitive we rely on Auto-Unboxing
Class bindClass = valueExp.getType(elContext);
if (bindClass.isPrimitive() || bindClass.isInstance(newValue)) {
valueExp.setValue(elContext, newValue);
}
}
/**
* Convenience method for setting the value of a managed bean by name
* rather than by expression.
* @param beanName name of managed bean
* @param newValue new value to set
*/
public static void setManagedBeanValue(String beanName, Object newValue) {
StringBuffer buff = new StringBuffer("#{");
buff.append(beanName);
buff.append("}");
setExpressionValue(buff.toString(), newValue);
}
/**
* Convenience method for setting Session variables.
* @param key object key
* @param object value to store
*/
public static void storeOnSession(String key, Object object) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getSessionMap();
sessionState.put(key, object);
}
/**
* Convenience method for getting Session variables.
* @param key object key
* @return session object for key
*/
public static Object getFromSession(String key) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getSessionMap();
return sessionState.get(key);
}
public static String getFromHeader(String key) {
FacesContext ctx = getFacesContext();
ExternalContext ectx = ctx.getExternalContext();
return ectx.getRequestHeaderMap().get(key);
}
/**
* Convenience method for getting Request variables.
* @param key object key
* @return session object for key
*/
public static Object getFromRequest(String key) {
FacesContext ctx = getFacesContext();
Map sessionState = ctx.getExternalContext().getRequestMap();
return sessionState.get(key);
}
/**
* Pulls a String resource from the property bundle that
* is defined under the application <message-bundle> element in
* the faces config. Respects Locale
* @param key string message key
* @return Resource value or placeholder error String
*/
public static String getStringFromBundle(String key) {
ResourceBundle bundle = getBundle();
return getStringSafely(bundle, key, null);
}
/**
* Convenience method to construct a FacesMesssage
* from a defined error key and severity
* This assumes that the error keys follow the convention of
* using _detail for the detailed part of the
* message, otherwise the main message is returned for the
* detail as well.
* @param key for the error message in the resource bundle
* @param severity severity of message
* @return Faces Message object
*/
public static FacesMessage getMessageFromBundle(String key,
FacesMessage.Severity severity) {
ResourceBundle bundle = getBundle();
String summary = getStringSafely(bundle, key, null);
String detail = getStringSafely(bundle, key + "_detail", summary);
FacesMessage message = new FacesMessage(summary, detail);
message.setSeverity(severity);
return message;
}
/**
* Add JSF info message.
* @param msg info message string
*/
public static void addFacesInformationMessage(String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_INFO, msg, "");
ctx.addMessage(getRootViewComponentId(), fm);
}
/**
* Add JSF error message.
* @param msg error message string
*/
public static void addFacesErrorMessage(String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, "");
ctx.addMessage(getRootViewComponentId(), fm);
}
/**
* Add JSF error message for a specific attribute.
* @param attrName name of attribute
* @param msg error message string
*/
public static void addFacesErrorMessage(String attrName, String msg) {
FacesContext ctx = getFacesContext();
FacesMessage fm =
new FacesMessage(FacesMessage.SEVERITY_ERROR, attrName, msg);
ctx.addMessage(getRootViewComponentId(), fm);
}
// Informational getters
/**
* Get view id of the view root.
* @return view id of the view root
*/
public static String getRootViewId() {
return getFacesContext().getViewRoot().getViewId();
}
/**
* Get component id of the view root.
* @return component id of the view root
*/
public static String getRootViewComponentId() {
return getFacesContext().getViewRoot().getId();
}
/**
* Get FacesContext.
* @return FacesContext
*/
public static FacesContext getFacesContext() {
return FacesContext.getCurrentInstance();
}
/*
* Internal method to pull out the correct local
* message bundle
*/
private static ResourceBundle getBundle() {
FacesContext ctx = getFacesContext();
UIViewRoot uiRoot = ctx.getViewRoot();
Locale locale = uiRoot.getLocale();
ClassLoader ldr = Thread.currentThread().getContextClassLoader();
return ResourceBundle.getBundle(ctx.getApplication().getMessageBundle(),
locale, ldr);
}
/**
* Get an HTTP Request attribute.
* @param name attribute name
* @return attribute value
*/
public static Object getRequestAttribute(String name) {
return getFacesContext().getExternalContext().getRequestMap().get(name);
}
/**
* Set an HTTP Request attribute.
* @param name attribute name
* @param value attribute value
*/
public static void setRequestAttribute(String name, Object value) {
getFacesContext().getExternalContext().getRequestMap().put(name,
value);
}
/*
* Internal method to proxy for resource keys that don't exist
*/
private static String getStringSafely(ResourceBundle bundle, String key,
String defaultValue) {
String resource = null;
try {
resource = bundle.getString(key);
} catch (MissingResourceException mrex) {
if (defaultValue != null) {
resource = defaultValue;
} else {
resource = NO_RESOURCE_FOUND + key;
}
}
return resource;
}
/**
* Locate an UIComponent in view root with its component id. Use a recursive way to achieve this.
* @param id UIComponent id
* @return UIComponent object
*/
public static UIComponent findComponentInRoot(String id) {
UIComponent component = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext != null) {
UIComponent root = facesContext.getViewRoot();
component = findComponent(root, id);
}
return component;
}
/**
* Locate an UIComponent from its root component.
* Taken from http://www.jroller.com/page/mert?entry=how_to_find_a_uicomponent
* @param base root Component (parent)
* @param id UIComponent id
* @return UIComponent object
*/
public static UIComponent findComponent(UIComponent base, String id) {
if (id.equals(base.getId()))
return base;
UIComponent children = null;
UIComponent result = null;
Iterator childrens = base.getFacetsAndChildren();
while (childrens.hasNext() && (result == null)) {
children = (UIComponent)childrens.next();
if (id.equals(children.getId())) {
result = children;
break;
}
result = findComponent(children, id);
if (result != null) {
break;
}
}
return result;
}
/**
* Method to create a redirect URL. The assumption is that the JSF servlet mapping is
* "faces", which is the default
*
* @param view the JSP or JSPX page to redirect to
* @return a URL to redirect to
*/
public static String getPageURL(String view) {
FacesContext facesContext = getFacesContext();
ExternalContext externalContext = facesContext.getExternalContext();
String url =
((HttpServletRequest)externalContext.getRequest()).getRequestURL().toString();
StringBuffer newUrlBuffer = new StringBuffer();
newUrlBuffer.append(url.substring(0, url.lastIndexOf("faces/")));
newUrlBuffer.append("faces");
String targetPageUrl = view.startsWith("/") ? view : "/" + view;
newUrlBuffer.append(targetPageUrl);
return newUrlBuffer.toString();
}

// Get the error


String error = iterBind.getError().getMessage();













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

// find a jsf component

private UIComponent getUIComponent(String name) {

FacesContext facesCtx = FacesContext.getCurrentInstance();

return facesCtx.getViewRoot().findComponent(name) ;

}

// change the locale

Locale newLocale = new Locale(this.language);

FacesContext context = FacesContext.getCurrentInstance();

context.getViewRoot().setLocale(newLocale);
}

**************************************

 public static void writeJavaScriptToClient(String paScript) {
        FacesContext fctx = FacesContext.getCurrentInstance();
        ExtendedRenderKitService erks = null;
        erks =
Service.getRenderKitService(fctx, ExtendedRenderKitService.class);
        erks.addScript(fctx, paScript);
    }

**************************************

/**
     * method for removing Session variables.
     * @param
     *
     */
    public static void removeFromSession(String key) {
        FacesContext ctx = getFacesContext();
        Map sessionState = ctx.getExternalContext().getSessionMap();
        sessionState.remove(key);
    }