Wednesday, December 29, 2010

Programmatically Getting and Setting Expression Values

You need to have ADFUtils and JSF Utils Class in you application and within your backing bean you can used below code to resolve and set expression values. Also if your managed bean is having session scope you can use below code:
************************************
JSFUtils.setExpressionValue("#{UserBean.uid}","tanveer");

UserDetails userBean = (UserDetails)JSFUtils.getFromSession("UserBean");

String myExpVal = (String)JSFUtils.resolveExpression("#{UserBean.uid}");
*****************************************

ADFUtils Code:
*********************************************
package bhc.view;

import java.util.ArrayList;
import java.util.List;

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.binding.AttributeBinding;
import oracle.binding.BindingContainer;

import oracle.binding.ControlBinding;

import oracle.binding.OperationBinding;

//import oracle.fodemo.storefront.jsf.util.JSFUtils;

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
*
* @author Duncan Mills
* @author Steve Muench
*
* $Id: ADFUtils.java 2513 2007-09-20 20:39:13Z ralsmith $.
*/
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;
}

/**
* @param bindingContainer
* @param iterator
* @return
*/
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;
}

/**
* @param name
* @return
*/
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;
}

/**
* @param opList
*/
public static void printOperationBindingExceptions(List opList){
if(opList != null && !opList.isEmpty()){
for(Object error:opList){
LOGGER.severe( error.toString() );
}
}
}
}

***************************************************************************************************
JSFUtils.java
***************************************************************************************************


package bhc.view;

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;

/**
* General useful static utilies for working with JSF.
* NOTE: Updated to use JSF 1.2 ExpressionFactory.
*
* @author Duncan Mills
* @author Steve Muench
* @author Ric Smith
*
* $Id: JSFUtils.java 2383 2007-09-17 16:25:37Z drmills $
*/
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
//I could do a more comprehensive check and conversion from the object
//to the equivilent primitive but life is too short
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) {
// TODO: Need a way to associate attribute specific messages
// with the UIComponent's Id! For now, just using the view id.
//TODO: make this use the internal getMessageFromBundle?
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.
* Taken from http://www.jroller.com/page/mert?entry=how_to_find_a_uicomponent
* @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();
}

}

Tuesday, December 28, 2010

Iterator Range Size

The iterator by default works with Range Size of 25, to make it work for all the records set the size of iterator to -1 inside pagedefinition iterator properties to avoid below error.

javax.servlet.ServletException: oracle.jbo.InvalidParamException: JBO-25006: Value 26 passed as parameter rangeIndex to method ViewRowSetIteratorImpl.insertRowAtRangeIndex is invalid: index outside range.

Access Application Module, ViewObject programmatically from Managed/Backing Beans

At times we need to programmatically update viewobject and do lot of other funtions on them. To achieve this we have to first connect to application module as it is able to query all the view objects in it.
The code which is required is:
ApplicationModule am = ADFUtils.getApplicationModuleForDataControl("AppModuleDataControl");



Note: The view objects which you are trying to access should be part of your jsf page definition (in executables), else you will not be able to refer it.

Monday, December 27, 2010

ADF 11g - SelectOneChoice Values based upon another SelectOneChoice component independent of base datasource.

Requirement: ADF BC - Selectonechoice without base datasource create as per my earlier post. Now I need a second selectonechoice from DB without base datasource based upon the value selected in first SelectOneChoice.

Step1: Create the view object with bind variable (Value for this will be provided at run time).
Step2: Create a Executing With Parameter binding in page definition for this view.
Step3: In Executables section of PageDefinition create an iterator for this view object.
Step4: Create a list in bindings for specific attribute(similar to create list without basedatasource)
Step5: Drag and drop selectOncechoice from component pallete on JSF page. Bind it to the list which we created earlier.
Step6: Set the autosubmit of the first selectonechoice to true and partial trigger of second selectonechoice to first selectonechoice value.
Step7: Now create valuechangelistener for first selectonechoice and put below code.

public void RptYrMoSubValChg(ValueChangeEvent valueChangeEvent) {
Bindings bindings = getBindings();
if(soc1.getValue()!=null) {
tempIter=((DCBindingContainer)getBindings()).findIteratorBinding("SubmTypeLovIterator");
tempRow=tempIter.getRowAtRangeIndex(Integer.parseInt(soc1.getValue().toString()));
this.subType = tempRow.getAttribute("SubmTypeCd").toString();
System.out.println("Selected Submission Type"+subType);

operationBinding = bindings.getOperationBinding("ExecuteWithParams");
Object result = operationBinding.execute();
if (!operationBinding.getErrors().isEmpty()) {
System.out.println("ERROR");
}

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

Thursday, December 23, 2010

ADF Fileupload - InputFile with autosubmit & valuechange listener

Issue Description: JSF page have inputFile component to upload file which return uploadFile object.
I have binded this component to backingbeans uploadFile object. Also this component has autosubmit true and value change listener method and this form has submit button at the end. I want the value changelister to validate file type and few other validations and submit button to upload document to specific location on server. The problem is the value changelister is working fine but the submit button action method was returning null for this.uploadFile object (this does not happen when I set autosubmit property to false for inputFile component).

Sol: I created inputFile and a (hidden) textfield. I binded the textfield to the uploadfile object in backing bean instead of the inputFile component. The autosubmit and valuchangelistener remains as its is I just assigned the value to this textfield the upload file object as input which I can typecast in the submit action button. sample code:

package demo.view.backing;

import demo.view.ExcelADF;

import demo.view.UnitSubmission;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.ArrayList;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import javax.faces.event.ValueChangeEvent;

import oracle.adf.view.rich.component.rich.RichDocument;
import oracle.adf.view.rich.component.rich.RichForm;
import oracle.adf.view.rich.component.rich.input.RichInputFile;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.nav.RichCommandButton;
import oracle.adf.view.rich.component.rich.output.RichMessages;

import oracle.adf.view.rich.context.AdfFacesContext;

import org.apache.myfaces.trinidad.context.RequestContext;
import org.apache.myfaces.trinidad.model.UploadedFile;

public class SampleFileUpload {
private RichForm f1;
private RichDocument d1;
private RichInputFile if1;
private RichCommandButton cb1;
private RichMessages m1;
private UploadedFile uploadedFile;
private UploadedFile uploadedFile1;
private String filename;
private long filesize;
private String filecontents;
private String filetype;

ArrayList dataHolder;
private RichInputText it1;


public void setF1(RichForm f1) {
this.f1 = f1;
}

public RichForm getF1() {
return f1;
}

public void setD1(RichDocument d1) {
this.d1 = d1;
}

public RichDocument getD1() {
return d1;
}


public void setIf1(RichInputFile if1) {
this.if1 = if1;
}

public RichInputFile getIf1() {
return if1;
}


public void setCb1(RichCommandButton cb1) {
this.cb1 = cb1;
}

public RichCommandButton getCb1() {
return cb1;
}

public void setM1(RichMessages m1) {
this.m1 = m1;
}

public RichMessages getM1() {
return m1;
}



public UploadedFile getUploadedFile() {
return uploadedFile;
}

public void setFilename(String filename) {
this.filename = filename;
}

public String getFilename() {
return filename;
}

public void setFilesize(long filesize) {
this.filesize = filesize;
}

public long getFilesize() {
return filesize;
}

public void setFilecontents(String filecontents) {
this.filecontents = filecontents;
}

public String getFilecontents() {
return filecontents;
}

public void setFiletype(String filetype) {
this.filetype = filetype;
}

public String getFiletype() {
return filetype;
}


public void setDataHolder(ArrayList dataHolder) {
this.dataHolder = dataHolder;
}

public ArrayList getDataHolder() {
return dataHolder;
}


public void fileUpdate(ValueChangeEvent valueChangeEvent) {
RichInputFile inputFileComponent = (RichInputFile)valueChangeEvent.getComponent();
UploadedFile newFile = (UploadedFile)valueChangeEvent.getNewValue();
newFile = (UploadedFile)valueChangeEvent.getNewValue();
it1.setValue(newFile);
// this.uploadedFile = newFile;
if (!newFile.getFilename().endsWith("xls")) {
FacesContext.getCurrentInstance().addMessage(inputFileComponent.getClientId(FacesContext.getCurrentInstance()),
new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Only Excel files are allowed",
"This file (" +
newFile.getFilename() +
") is not allowed; the extension is not allowed."));
inputFileComponent.resetValue();
inputFileComponent.setValid(false);
}



}



public String SubmitAction() {
uploadedFile = (UploadedFile)it1.getValue();
System.out.println("File Name: "+uploadedFile.getFilename());
return null;
}

public void setUploadedFile1(UploadedFile uploadedFile1) {
this.uploadedFile1 = uploadedFile1;
}

public UploadedFile getUploadedFile1() {
return uploadedFile1;
}


public void setIt1(RichInputText it1) {
this.it1 = it1;
}

public RichInputText getIt1() {
return it1;
}
}

Thursday, December 16, 2010

java.lang.ClassNotFoundException: oracle.bpel.services.workflow.WorkflowException

Error during deployment of ADF 11g application server:
In Application Resources Pallette -> weblogic-application.xml add below lines

Thursday, December 2, 2010

ADF SelectOneChoice without base datasource

PageDefinition:
Create Iterator in your executables section.
and create a list binding in your bindings section to this iterator.
Sample page definition code:




















Page:
Drag and drop the selectonechoice component and bind it to above created binding.

Note that selectonechoice will return index, use iterator bind to get the value at selected index below is backing bean code
public void choiceListListener(ValueChangeEvent valueChangeEvent) {
DCIteratorBinding iter=((DCBindingContainer)getBindings()).findIteratorBinding("Departments1View1Iterator");
Row r=iter.getRowAtRangeIndex((Integer)valueChangeEvent.getNewValue());
System.out.println("Attr names"+r.getAttribute("DepartmentId"));
System.out.println("Attr names"+r.getAttribute("DepartmentName"));
System.out.println("atr1");
//set value of your variable equal to "value"
}