Deepak Kumar's Blog
Oracle SOA, ADF, BPEL
Tuesday, 9 June 2015
ADFUtils and JSFUtils
JSFUtils
package view.utils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.el.ELContext; import javax.el.ExpressionFactory; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import javax.faces.model.SelectItem; import oracle.adf.model.BindingContext; import oracle.adf.model.DataControlFrame; 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.adf.view.rich.component.rich.RichPopup; import oracle.adf.view.rich.component.rich.RichQuery; import oracle.adf.view.rich.component.rich.data.RichTable; import oracle.adf.view.rich.component.rich.data.RichTree; import oracle.adf.view.rich.context.AdfFacesContext; import oracle.adf.view.rich.model.QueryDescriptor; import oracle.adf.view.rich.model.QueryModel; 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.RowIterator; import oracle.jbo.uicli.binding.JUCtrlHierBinding; import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding; import oracle.jbo.uicli.binding.JUCtrlValueBinding; import oracle.jbo.uicli.binding.JUEventBinding; import org.apache.myfaces.trinidad.event.SelectionEvent; import org.apache.myfaces.trinidad.model.CollectionModel; import org.apache.myfaces.trinidad.model.ModelUtils; import org.apache.myfaces.trinidad.model.RowKeySet; import org.apache.myfaces.trinidad.model.RowKeySetImpl; import org.apache.myfaces.trinidad.render.ExtendedRenderKitService; import org.apache.myfaces.trinidad.util.Service; /** * A series of convenience functions for dealing with ADF Bindings. * Note: Updated for JDeveloper 11 * * @author Duncan Mills * @author Steve Muench * */ 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)JSFUtil.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)JSFUtil.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)JSFUtil.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)JSFUtil.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() ); } } } /** * When a bounded task flow manages a transaction (marked as requires-transaction,. * requires-new-transaction, or requires-existing-transaction), then the * task flow must issue any commits or rollbacks that are needed. This is * essentially to keep the state of the transaction that the task flow understands * in synch with the state of the transaction in the ADFbc layer. * * Use this method to issue a commit in the middle of a task flow while staying * in the task flow. */ public static void saveAndContinue() { Map sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); BindingContext context = (BindingContext)sessionMap.get(BindingContext.CONTEXT_ID); String currentFrameName = context.getCurrentDataControlFrame(); DataControlFrame dcFrame = context.findDataControlFrame(currentFrameName); dcFrame.commit(); dcFrame.beginTransaction(null); } /** * 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 af:setActionListener 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); } public static OperationBinding getOperationBindingForMethod(String pageDefMethod) { OperationBinding opBinding; opBinding = getBindingContainer().getOperationBinding(pageDefMethod); return opBinding; } /* public static Task getWorkFlowTaskForRemoteClient(String bpmWorkListContextId, String bpmWorkListTaskId) { try { IWorkflowServiceClient wfServiceClient = WorkflowServiceClientFactory.getWorkflowServiceClient(WorkflowServiceClientFactory.REMOTE_CLIENT); ITaskQueryService taskQueryService = wfServiceClient.getTaskQueryService(); IWorkflowContext wfContext = null; wfContext = taskQueryService.getWorkflowContext(bpmWorkListContextId); Task humanTask = taskQueryService.getTaskDetailsById(wfContext, bpmWorkListTaskId); return humanTask; } catch (WorkflowException we) { // TODO: Add catch code we.printStackTrace(); return null; } } public static TaskDefinition getWorkFlowTaskDefinitionForRemoteClient(String bpmWorkListContextId, String bpmWorkListTaskId) { try { IWorkflowServiceClient wfServiceClient = WorkflowServiceClientFactory.getWorkflowServiceClient(WorkflowServiceClientFactory.REMOTE_CLIENT); ITaskQueryService taskQueryService = wfServiceClient.getTaskQueryService(); ITaskMetadataService taskMetadataService = wfServiceClient.getTaskMetadataService(); ; IWorkflowContext wfContext = null; wfContext = taskQueryService.getWorkflowContext(bpmWorkListContextId); Task humanTask = taskQueryService.getTaskDetailsById(wfContext, bpmWorkListTaskId); TaskDefinition humanTaskDef = taskMetadataService.getTaskDefinition(wfContext, humanTask); return humanTaskDef; } catch (WorkflowException we) { // TODO: Add catch code we.printStackTrace(); return null; } } */ public static void openURLInWindow(String url) { FacesContext facesContext = FacesContext.getCurrentInstance(); System.out.println("########## Url :-"+url); url = url.replaceAll("\\\\", "\\\\\\\\"); String javaScriptText= null; if(url.contains("http")) { javaScriptText = "window.open('"+url+"', 'popupWindow', 'dependent=yes, menubar=no, toolbar=no');"; } else { JSFUtil.showFacesErrorMessage("Cannot open URL :"+url); } ExtendedRenderKitService service = Service.getRenderKitService(facesContext, ExtendedRenderKitService.class); service.addScript(facesContext, javaScriptText); } public static void executeClientJavascript(String script) { FacesContext facesContext = FacesContext.getCurrentInstance(); ExtendedRenderKitService service = Service.getRenderKitService(facesContext, ExtendedRenderKitService.class); service.addScript(facesContext, script); } public static void invokePopup(String popupId) { invokePopup(popupId, null, null); } /** * Hides or shows the popup component depending on the value of the * boolean parameter. * @param popUpComponent rich component popup object * @param showPopup true = show , false = hide */ public static void invokePopup(RichPopup popUpComponent, boolean showPopup){ String popupId = popUpComponent.getClientId(FacesContext.getCurrentInstance()); if (showPopup) invokePopup(popupId); else hidePopup(popupId); } /** * Shows the specified popup and uses the specified hints to align the popup. * @param popupId is the clientId of the popup to be shown - clientId is derived from backing bean for the af:popup using getClientId method * @param align is a hint for the popup display. Check AdfRichPopup js javadoc for valid values. Supported value includes: "AdfRichPopup.ALIGN_START_AFTER", "AdfRichPopup.ALIGN_BEFORE_START" and "AdfRichPopup.ALIGN_END_BEFORE" * @param alignId is the clientId of the component the popup should align to - clientId is derived from backing bean for the component using getClientId method * align and alignId need to be specified together - specifying null for either of them will have no effect. */ public static void invokePopup(String popupId, String align, String alignId) { if (popupId != null) { ExtendedRenderKitService service = Service.getRenderKitService(FacesContext.getCurrentInstance(), ExtendedRenderKitService.class); StringBuffer showPopup = new StringBuffer(); showPopup.append("var hints = new Object();"); //Add hints only if specified - see javadoc for AdfRichPopup js for details on valid values and behavior if (align != null && alignId != null) { showPopup.append("hints[AdfRichPopup.HINT_ALIGN] = " + align + ";"); showPopup.append("hints[AdfRichPopup.HINT_ALIGN_ID] ='" + alignId + "';"); } showPopup.append("var popupObj=AdfPage.PAGE.findComponent('" + popupId + "'); if (popupObj) popupObj.show(hints);"); service.addScript(FacesContext.getCurrentInstance(), showPopup.toString()); } } /** * Hides the specified popup. * @param popupId is the clientId of the popup to be hidden * clientId is derived from backing bean for the af:popup using getClientId method */ public static void hidePopup(String popupId) { if (popupId != null) { ExtendedRenderKitService service = Service.getRenderKitService(FacesContext.getCurrentInstance(), ExtendedRenderKitService.class); String hidePopup = "var popupObj=AdfPage.PAGE.findComponent('" + popupId + "'); if (popupObj) popupObj.hide();"; service.addScript(FacesContext.getCurrentInstance(), hidePopup); } } public static String join(List extends CharSequence> s, String delimiter) { int capacity = 0; int delimLength = delimiter.length(); Iterator extends CharSequence> iter = s.iterator(); if (iter.hasNext()) { capacity += iter.next().length() + delimLength; } StringBuilder buffer = new StringBuilder(capacity); iter = s.iterator(); if (iter.hasNext()) { buffer.append(iter.next()); while (iter.hasNext()) { buffer.append(delimiter); buffer.append(iter.next()); } } return buffer.toString(); } public static void raiseContextualEvent(String eventBindingOpExpr,ActionEvent actionEvent,Map
payload) { if(eventBindingOpExpr == null || actionEvent == null ) { JSFUtil.showFacesErrorMessage("Event Binding Operation Expression is NULL. Action Event is NULL"); return; } else { UIComponent pubUiComp = actionEvent.getComponent(); Map
attributes = pubUiComp.getAttributes(); if(payload != null) { Set set=payload.entrySet(); Iterator it=set.iterator(); String key; Object value; while(it.hasNext()) { Map.Entry m =(Map.Entry)it.next(); key=(String)m.getKey(); value = m.getValue(); attributes.put(key, value); } } JUEventBinding eventBinding = (JUEventBinding)getBindingContainer().get(eventBindingOpExpr); if(eventBinding == null) { JSFUtil.showFacesErrorMessage("Event Binding is Null"); return; } else { ActionListener actionListener = (ActionListener)eventBinding.getListener(); actionListener.processAction(actionEvent); } } } public static RowIterator getSelectedNodeRowIterator(RichTree tree) { if (tree != null && tree.getSelectedRowKeys() != null) { for (Object opaqueFacesKey : tree.getSelectedRowKeys()) { tree.setRowKey(opaqueFacesKey); return ((JUCtrlHierNodeBinding)tree.getRowData()).getRowIterator(); } } return null; } public static boolean isSelectedNodeInRowIteratorFirst(RichTree tree) { RowIterator ri = getSelectedNodeRowIterator(tree); if (ri != null) { Key selectedNodeRowKey = getSelectedNodeRowKey(tree); if (selectedNodeRowKey != null) { return selectedNodeRowKey.equals(ri.first().getKey()); } } return false; } public static boolean isSelectedNodeInRowIteratorLast(RichTree tree) { RowIterator ri = getSelectedNodeRowIterator(tree); if (ri != null) { Key selectedNodeRowKey = getSelectedNodeRowKey(tree); if (selectedNodeRowKey != null) { return selectedNodeRowKey.equals(ri.last().getKey()); } } return false; } public static Key getSelectedNodeRowKey(RichTree tree) { if (tree != null && tree.getSelectedRowKeys() != null) { for (Object opaqueFacesKey : tree.getSelectedRowKeys()) { tree.setRowKey(opaqueFacesKey); return ((JUCtrlHierNodeBinding)tree.getRowData()).getRowKey(); } } return null; } public static String getSelectedNodeViewDefFullName(RichTree tree) { if (tree != null && tree.getSelectedRowKeys() != null) { for (Object opaqueFacesKey : tree.getSelectedRowKeys()) { tree.setRowKey(opaqueFacesKey); return ((JUCtrlHierNodeBinding)tree.getRowData()).getViewObject().getDefFullName(); } } return null; } public static void makeCurrentInTree(RichTree tree,String treeSeleEL, RowKeySet rowKeySet){ //To make a row current, we need to create a SelectionEvent which //expects the following arguments: component, unselected_keys, //selected_keys. In our example, we don't have unselected keys and //therefore create an empty RowSet for this SelectionEvent selectionEvent = new SelectionEvent( tree, new RowKeySetImpl(), rowKeySet); //Calling the helper method introduced for this chapter. The //"LocationsView1" reference is the tree binding definition //our example tree has in the ADF PagDef file. invokeEL(treeSeleEL,new Class[]{SelectionEvent.class},new Object[]{selectionEvent}); } /** * author ms * @param object * @return */ public static String nullStringToSpace(Object object) { String spcStr = ""; if (object == null) { return spcStr; } else { return object.toString(); } } /** * author ms * @param queryComponent */ public static void resetQueryPanel(RichQuery queryComponent){ QueryModel queryModel = queryComponent.getModel(); QueryDescriptor queryDescriptor = queryComponent.getValue(); queryModel.reset(queryDescriptor); queryComponent.refresh(FacesContext.getCurrentInstance()); } /** * @param selectionEvent */ public static void makeCurrentRowInTable(SelectionEvent selectionEvent){ RichTable table = (RichTable) selectionEvent.getSource(); //CollectionModel tableModel = ModelUtils.toCollectionModel(table.getValue()); //JUCtrlHierBinding adfTableBinding = (JUCtrlHierBinding) tableModel.getWrappedData(); JUCtrlHierBinding adfTableBinding = null; adfTableBinding = (JUCtrlHierBinding) ((CollectionModel)table.getValue()).getWrappedData(); DCIteratorBinding tableIteratorBinding = adfTableBinding.getDCIteratorBinding(); Object selectedRowData = table.getSelectedRowData(); JUCtrlHierNodeBinding nodeBinding = (JUCtrlHierNodeBinding) selectedRowData; Key rwKey = nodeBinding.getRowKey(); tableIteratorBinding.setCurrentRowWithKey(rwKey.toStringFormat(true)); } public static void createTableNewRow(String iterator){ DCIteratorBinding dciter = ADFUtils.findIterator(iterator); Row lastRow = dciter.getNavigatableRowIterator().last(); Row newRow = dciter.getNavigatableRowIterator().createRow(); newRow.setNewRowState(Row.STATUS_INITIALIZED); int lastRowIndex = dciter.getNavigatableRowIterator().getRangeIndexOf(lastRow); dciter.getNavigatableRowIterator().insertRowAtRangeIndex(lastRowIndex+1, newRow); dciter.setCurrentRowWithKey(newRow.getKey().toStringFormat(true)); } }
JSFUtils
package view.utils; import java.util.Iterator; import java.util.List; 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.application.ViewHandler; 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.view.rich.component.rich.data.RichTreeTable; import oracle.adf.view.rich.datatransfer.DataFlavor; import oracle.adf.view.rich.datatransfer.Transferable; import oracle.adf.view.rich.event.DropEvent; import oracle.jbo.uicli.binding.JUCtrlHierBinding; import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding; import org.apache.myfaces.trinidad.context.RequestContext; import org.apache.myfaces.trinidad.model.CollectionModel; import org.apache.myfaces.trinidad.model.RowKeySet; /** * General useful static utilies for working with JSF. * @author Duncan Mills * @author Steve Muench */ public class JSFUtil { 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); } /** * Store page flow scope attribute * @param name * @param value */ public static void storeOnPageFlow(String name, Object value) { RequestContext.getCurrentInstance().getPageFlowScope().put(name, value); } /** * 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
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(); } /** * Create value binding for EL expression * @param expression * @return Object */ public static Object getExpressionObjectReference(String expression) { FacesContext fc = FacesContext.getCurrentInstance(); ELContext elctx = fc.getELContext(); ExpressionFactory elFactory = fc.getApplication().getExpressionFactory(); return elFactory.createValueExpression(elctx, expression, Object.class).getValue(elctx); } /** * Invokes an expression * @param expr * @param returnType * @param argTypes * @param args * @return */ public static Object invokeMethodExpression(String expr, Class returnType, Class[] argTypes,Object[] args){ FacesContext fc = FacesContext.getCurrentInstance(); ELContext elctx = fc.getELContext(); ExpressionFactory elFactory = fc.getApplication().getExpressionFactory(); MethodExpression methodExpr = elFactory.createMethodExpression(elctx,expr,returnType,argTypes); return methodExpr.invoke(elctx,args); } /** * Invoke an expression * @param expr * @param returnType * @param argType * @param argument * @return */ public static Object invokeMethodExpression(String expr, Class returnType,Class argType, Object argument){ return invokeMethodExpression(expr, returnType,new Class[]{argType}, new Object[]{argument}); } public static void showFacesInformationMessage(String msg) { FacesContext ctx = getFacesContext(); msg = ""+msg+""; FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, ""); ctx.addMessage(null, fm); } public static void showFacesErrorMessage(Exception e) { StackTraceElement[] elements = e.getStackTrace(); String errorStack = ""; for(StackTraceElement ele : elements) { errorStack = errorStack.concat(ele.toString()+"\n"); } JSFUtil.showFacesErrorMessage(errorStack); } public static void showFacesErrorMessage(String msg) { FacesContext ctx = getFacesContext(); FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, ""); ctx.addMessage(null, fm); } public static void refreshCurrentPage() { FacesContext context = getFacesContext(); String currentView = context.getViewRoot().getViewId(); ViewHandler vh = context.getApplication().getViewHandler(); UIViewRoot x = vh.createView(context, currentView); x.setViewId(currentView); context.setViewRoot(x); } /** * Get attribute value from page flow scope * @param name * @return Object */ public static Object getFromPageFlow(String name) { return RequestContext.getCurrentInstance().getPageFlowScope().get(name); } public static RowKeySet getDraggedRowKeySetFromTreeTable(DropEvent dropEvent, String discriminant ){ JUCtrlHierNodeBinding draggedRowNode=null; //Get the Dragged Row Transferable transferable= dropEvent.getTransferable(); DataFlavor
rowKeySetFlavor= DataFlavor.getDataFlavor(RowKeySet.class,discriminant); RowKeySet rowKeySet=transferable.getData(rowKeySetFlavor); return rowKeySet; } public static JUCtrlHierNodeBinding getTreeNodeByKey(RichTreeTable treeTable,List key){ JUCtrlHierNodeBinding treeNode=null; CollectionModel cm=(CollectionModel)treeTable.getValue(); JUCtrlHierBinding treeBinding=(JUCtrlHierBinding)cm.getWrappedData(); treeNode=treeBinding.findNodeByKeyPath(key); return treeNode; } public static JUCtrlHierNodeBinding getDraggedRowNodeFromTreeTable(DropEvent dropEvent, String discriminant ){ JUCtrlHierNodeBinding draggedRowNode=null; //Get the Dragged Row Transferable transferable= dropEvent.getTransferable(); DataFlavor
rowKeySetFlavor= DataFlavor.getDataFlavor(RowKeySet.class,discriminant); RowKeySet rowKeySet=transferable.getData(rowKeySetFlavor); if(rowKeySet !=null){ List firstRowKey=(List)rowKeySet.iterator().next(); CollectionModel treeTableCollectionModel=transferable.getData(CollectionModel.class); JUCtrlHierBinding binding=(JUCtrlHierBinding)treeTableCollectionModel.getWrappedData(); System.out.println(binding.getIteratorBinding().getDisplayName()); draggedRowNode=binding.findNodeByKeyPath(firstRowKey); } return draggedRowNode; } }
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment