2013年7月4日星期四

[ADF技术-011] 如何在backingbean中执行javascript



    /**
     * 通过后台执行前台的JS代码
     * @param script
     */
    public static void script(String script) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        try {
                ExtendedRenderKitService service =
                    Service.getRenderKitService(facesContext, ExtendedRenderKitService.class);
                service.addScript(facesContext, script);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

以上代码可以在backingbean中执行js

不过一定要注意一点:调用以上方法的按钮一定要设置partialSubmit="true"

2013年5月29日星期三

[Go Lang-006] Go基础-全局变量与局部变量


package main

import (
"fmt"
)

var a="a"
func main() {
fmt.Println("func main",a)
j()
g()
k()
}

func g(){
fmt.Println("func g",a)
}

func j(){
//局部作用域
//a:="j"
//全部作用域
a="j"
fmt.Println("func j",a)
}

func k(){
fmt.Println("func k",a)
}

以上程序有个注意的地方
当func j()中的局部变量的注释打开,a:="j"(红色部分)时
打印

func main a
func j j
func g a
func k a


当func j()中的全部变量的注释打开,a="j"(蓝色部分)时

func main a
func j j
func g j
func k j


就是a="j"a:="j"的区别,差了一个分号,就差别那么大?看下下面的解释大家就懂了..

其实
a="j"的意思就是把全局变量a重新赋值成"j"

a:="j"的意思就是重新定义一个新的局部变量a并赋值成"j"


[ADF技术-010] VO的ID字段自动获取Sequence

获取Sequence有两种不同的方法

1.Groovy表达式获取

  该方法是view的iterator中创建一行的时候就通过groovy表达式获取Seq中的值并赋值到id字段中,该方法有个缺点:如果事务回滚了或者创建的行没保存,就会造成Seq跳值

  1.1.选中需要获取Seq的EO中的字段

 1.2.Default Value中选择Expression(表达式)
     并填入(new oracle.jbo.server.SequenceImpl(SEQ名称,adf.object.getDBTransaction())).getSequenceNumber()


2.提交事务时候之前获取

  该方法是通过在提交事务之前手工获取对应的seq值并赋值到id字段中,是第一个方法很好的补充

  2.1.生成EO对应的java类,并勾上Data Manipulation Methods

  2.2.找到java类中的doDML方法,并重写
     
代码如下
     /**
      * Custom DML update/insert/delete logic here.
      * @param operation the operation type
      * @param e the transaction event
      */
     protected void doDML(int operation, TransactionEvent e) {
         if (operation == DML_INSERT) {
             if(this.getCompanyId()==null){
                 this.setCompanyId((new oracle.jbo.server.SequenceImpl(SEQ名称, this.getDBTransaction())).getSequenceNumber().intValue());
             }
         }
         super.doDML(operation, e);
     }

2013年5月20日星期一

[Go Lang-005] Go基础-Array,Slice,Map

Array
   Array(数组)是固定长度,相同类型的集合,因为是固定长度,因此大小不能改变.
     
     1.1.创建Array
     有两种初始化方式
          1.1.1.固定长度
               var a [3]int
          
          1.1.2.自动统计长度
               var a [...]int{1,2,3}
               中括号用...代替长度值,就会自动元素个数并赋值长度

Slice
   Slice(切片)是非固定长度,相同类型的集合,如果有新元素加入,Slice会增加长度,并且Slice总是指向一个底层的Array,是一个指向Array的指针

     2.1.创建一个长度为10,空的Slice
          slice:=make([]int,10)
     
     2.2.创建一个非空的slice
          slice:=[]int{1,2,3}
          注意:这里很容易搞错,上面是slice,下面是array
          slice:=[...]int{1,2,3}

          差别就是在于中括号中的数字,有数字就是array,没有就是slice
     
     2.3.创建一个Array,并且初始化Slice
          var a [...]int{1,2,3}
          slice:=[1:3]
     
     各种例子
a:=[...]int{1,2,3,4,5}
//从数组a中取出大于2,小于等于4的数字
s1:=a[2:4]

//从数组a中取出大于1,小于等于5的数字
s2:=a[1:5]

//用a中所有元素创建slice,这是a[0:len(a)]的简化写法
s3:=a[:]

//从序号0到3创建,这是a[0:4]简化写法,得到1,2,3,4
s4:=a[:4]

//从s2创建slice,注意s5的指针扔向指向a
s5:=s2[:]

       2.4.追加slice元素
s0:=[]int{1,2}
//向s0中追加元素3
s1:=append(s0,3)
//向s0中追加多个元素
s2:=append(s0,3,4,5)
//向S0中追加一个slice
s3:=append(s0,s2...)

       2.5.复制slice元素
        a:=[...]int{1,2,3,4,5}

var s1=make([]int,6)
//copy(target,src),src:源数组,target目标数组,返回函数是复制了多少个元素
s2:=copy(s1,a[0:])
println("s2",s2);

Map

     Map可以理解为是一个有索引的数组,一般定义形式为map[from type(key type)]to type(value type)
     monthDays:= map[ string] int {
        "Jan" :31,"Feb" :30,"Mar" :31,
        "Apr" :30,"May" :30,"Jun" :30,//<<<<<最后这个逗号是必须的!
     }
     3.1.读取
     println( "May:" ,monthDays["May" ]);

     3.2.增加元素
     monthDays[ "Dec"]=29

     3.3.删除元素
     delete(monthDays,"May")

     3.4.检查元素是否存在
     var value int //<<<接收value
     var isExist bool//<<<返回true/false标识是否存在
     value,isExist =monthDays["Jan"]

     另外一种方式
     value,isExist:=monthDays["Jan"]



参考文献
1.http://www.cnblogs.com/yjf512/archive/2012/06/14/2549929.html

[Go Lang-004] Go基础-赋值

Go赋值有两种方法
1.先定义类型再赋值

package main

import (
)

func main(){

//定义一个变量a类型为int
var a int
//将变量a赋值为1,如果不初始化默认为0
a=1
//打印变量a
println("a:",a);

}

注意:定义变量的时候切记和java是有区别的哦..亲...
java:int a;
go:var a int

多个变量同时赋值
//初始化,这种方式成为group
var(
a int
b string
)
注意:使用group方式赋值的时候注意
var和括号一定要在同一行
如:
var(

不能写成不在同一行
如:
var
(
会报错

//赋值
a=1
b="2"



2.直接赋值

package main

import (
)

func main(){
//将变量a赋值为1,不需要定义类型,类型由赋值推演出来
a:=1
//打印变量a
println("a:",a);
}

多个变量同时赋值
a,b:=1,2



2013年5月18日星期六

[Android-001] Android Studio启动不了

算是尝鲜吧...
早上跑完步回来刚好下完...
安装完之后发现打不开..

在网上找了下资料
可以开查看错误信息的

1.先用记事本打开android-studio\bin\studio.bat文件,在72行后加上PAUSE

2.用cmd运行android-studio\bin\studio.bat

发现错误信息是没配置jdk的环境变量
但运行java -version是没问题的- -

3.好吧.只能检查一下环境变量..真没配置....(比较无奈..)

4.配置上之后把studio.bat文件中的pause去掉就可以正常打开Android Studio

注意:
本帖只限于解决我本机的问题.
如果看到错误提示其他信息请到Google查询解决方案.

2013年5月17日星期五

[ADF技术-009] ModelADFUtils.java-ADF工具类

持续更新ing...........

package model;
import Const;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import oracle.adf.share.ADFContext;

import oracle.jbo.Row;
import oracle.jbo.server.AttributeListImpl;

public class ModelADFUtils {
    public ADFUtils() {
        super();
    }
 
    /**
     * 获取SessionScope存储的变量值
     * @param key
     * @return
     */
    public static Object getSessionScope(String key) {
        return ADFContext.getCurrent().getSessionScope().get(key);
    }
 
    /**
     * 获取SessionScope存储的变量值
     * @param key
     * @return
     */
    public static Object getPageFlowScope(String key) {
        return ADFContext.getCurrent().getPageFlowScope().get(key);
    }
 
    /**
     * 获取当前的语言
     * @return
     */
    public static String getLocale(){
        Object o = getSessionScope(Const.LOCALE_FLAG);
        if (Beans.isNotEmpty(o)) {
            String LangVar = EtravelConst.localeMap.get(o.toString());
            if (Beans.isNotEmpty(LangVar)) {
                return LangVar;
            }
        }
        return Const.LAN_CN;
    }
 

    /**
     * 复制一个实体的属性到另外一个实体
     * @param obj
     * @param targetObject
     */

    public static void copy(Object obj,Object targetObject){
        AttributeListImpl attribute=null;
        Row row=null;
        if(targetObject instanceof AttributeListImpl){
            attribute = (AttributeListImpl)targetObject;
        }else if(targetObject instanceof Row){
            row = (Row)targetObject;
        }else{
            return;
        }
     
        if (obj!=null) {
            BeanMap bm = new BeanMap(obj);
            Set<Entry<String, Object>> entrySet = bm.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                VEntry vEntry = (VEntry)entry;
                String key = Beans.firtCharToUpper(vEntry.getKey());
                //不拷贝情况-begin
                if (Beans.isEmpty(vEntry.getType())) {
                    continue;
                }
                if (vEntry.getType().isArray()) { //不拷贝数组
                    continue;
                }
                if (Collection.class.isAssignableFrom(vEntry.getType())) { //不拷贝集合
                    continue;
                }
                if (Map.class.isAssignableFrom(vEntry.getType())) { //不拷贝映射
                    continue;
                }
                if (Beans.isEmpty(key) || Beans.isEmpty(vEntry.getValue())) {
                    continue;
                }
                //不拷贝情况-end
             
                if (Beans.isNotEmpty(row)) {
                    row.setAttribute(key, vEntry.getValue());
                } else if (Beans.isNotEmpty(attribute)) {
                    attribute.setAttribute(key, vEntry.getValue());
                }
            }
        }
    }
}


[ADF技术-008] ADFUtils.java-ADF工具类


package view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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.model.SelectItem;

import oracle.adf.controller.ControllerContext;
import oracle.adf.controller.TaskFlowId;
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.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.component.rich.input.RichInputText;
import oracle.adf.view.rich.component.rich.layout.RichPanelTabbed;
import oracle.adf.view.rich.component.rich.layout.RichShowDetailItem;
import oracle.adf.view.rich.context.AdfFacesContext;

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;

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
 * @author Ric Smith
 *
 * $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}");
        FacesContext fc = FacesContext.getCurrentInstance();
        BindingContainer bindings =
            (BindingContainer)fc.getApplication().evaluateExpressionGet(fc,
                                                                        "#{bindings}",
                                                                        BindingContainer.class);
        return 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<SelectItem> selectItemsForIterator(String iteratorName,
                                                          String valueAttrName,
                                                          String displayAttrName) {
        return selectItemsForIterator(findIterator(iteratorName),
                                      valueAttrName, displayAttrName);
    }

    /**
     * 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 displayAttrNames array of attribute names from iterator rows to display
     * @return ADF Faces SelectItem for an iterator binding
     */
    public static List<SelectItem> selectItemsForIterator(String iteratorName,
                                                          String valueAttrName,
                                                          String[] displayAttrNames)  {
        return selectItemsForIterator(findIterator(iteratorName),
                                      valueAttrName, displayAttrNames);
    }

    /**
     * Get a List of attributes as a Map (of name, value) for an iterator.
     * @param iter iterator binding
     * @param attrNames array of attribute names for attributes to be retrieved
     * @return List of attribute values
     */
    public static List<Map<String, Object>> attributesListForIterator(DCIteratorBinding iter,
                                                                      String[] attrNames) {
        List<Map<String, Object>> attributeList =
            new ArrayList<Map<String, Object>>();
        for (Row r : iter.getAllRowsInRange()) {
            Map<String, Object> alist = new HashMap<String, Object>();
            for (String aName : attrNames) {
                alist.put(aName, r.getAttribute(aName));
            }
            attributeList.add(alist);
        }
        return attributeList;
    }

    /**
     * Get a List of attributes as a Map (of name, value) for an iterator.
     * @param iteratorName ADF iterator binding name
     * @param attrNames array of attribute names for attributes to be retrieved
     * @return List of attribute values for an iterator
     */
    public static List<Map<String, Object>> attributeListForIterator(String iteratorName,
                                                                     String[] attrNames) {
        return attributesListForIterator(findIterator(iteratorName),
                                         attrNames);
    }

    /**
     * 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<SelectItem> 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<Key> 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<Key> keyListForIterator(DCIteratorBinding iter) {
        List<Key> attributeList = new ArrayList<Key>();
        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<Key> 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<Key> keyAttrListForIterator(DCIteratorBinding iter,
                                                   String keyAttrName) {
        List<Key> attributeList = new ArrayList<Key>();
        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 IteratorNotFound("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<SelectItem> selectItemsForIterator(DCIteratorBinding iter,
                                                          String valueAttrName,
                                                          String displayAttrName,
                                                          String descriptionAttrName) {
        List<SelectItem> selectItems = new ArrayList<SelectItem>();
        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<SelectItem> selectItemsForIterator(DCIteratorBinding iter,
                                                          String valueAttrName,
                                                          String displayAttrName) {
        List<SelectItem> selectItems = new ArrayList<SelectItem>();
        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 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 displayAttrNames array of attribute names from iterator rows to display
     * @return ADF Faces SelectItem for an iterator binding
     */
    public static List<SelectItem> selectItemsForIterator(DCIteratorBinding iter,
                                                          String valueAttrName,
                                                          String[] displayAttrNames) {
        List<SelectItem> selectItems = new ArrayList<SelectItem>();
        for (Row r : iter.getAllRowsInRange()) {
            StringBuilder buf = new StringBuilder();
            for (int idx = 0; idx < displayAttrNames.length; idx++) {
                buf.append((String)r.getAttribute(displayAttrNames[idx]));
                if (idx < (displayAttrNames.length - 1)) {
                    buf.append("-");
                }
            }
            selectItems.add(new SelectItem(r.getAttribute(valueAttrName),
                                           buf.toString()));
        }
        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<SelectItem> 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<SelectItem> 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<SelectItem> selectItemsByKeyForIterator(DCIteratorBinding iter,
                                                               String displayAttrName,
                                                               String descriptionAttrName) {
        List<SelectItem> selectItems = new ArrayList<SelectItem>();
        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<SelectItem> selectItemsByKeyForIterator(DCIteratorBinding iter,
                                                               String displayAttrName) {
        List<SelectItem> selectItems = new ArrayList<SelectItem>();
        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());
            }
        }
    }

    /**
     * Get the page flow scope
     * @return
     */
    public static Map getPageFlowScope() {
        return AdfFacesContext.getCurrentInstance().getPageFlowScope();
    }

    /**
     * Open a new browser tab/window starting a new bounded task flow.
     *
     * @param taskFlowId - id of bounded task flow to show in new window
     * @param taskFlowParams - params for the task flow (if any)
     * @param windowName - name of browser tab/window (window.name)
     * @param openInWindow - true will open a browser window (if settings of the browser
     *     allow this), false will open a new browser tab.
     */
    public static void launchTaskFlowInNewWindow(TaskFlowId taskFlowId,
                                                 Map taskFlowParams,
                                                 String windowName,
                                                 boolean openInWindow) {
        launchTaskFlowInNewWindow(taskFlowId, taskFlowParams, windowName,
                                  openInWindow, 1000, 750);

    }


    /**
     * Open a new browser tab/window starting a new bounded task flow.
     *
     * @param taskFlowId - id of bounded task flow to show in new window
     * @param taskFlowParams - params for the task flow (if any)
     * @param windowName - name of browser tab/window (window.name)
     * @param openInWindow - true will open a browser window (if settings of the browser
     *     allow this), false will open a new browser tab.
     * @param width
     * @param height
     */

    public static void launchTaskFlowInNewWindow(TaskFlowId taskFlowId,
                                                 Map taskFlowParams,
                                                 String windowName,
                                                 boolean openInWindow,
                                                 int width, int height) {

        String url =
            ControllerContext.getInstance().getTaskFlowURL(false, taskFlowId,
                                                           taskFlowParams);

        if (url == null) {
            throw new Error("Unable to launch window for task flow id " +
                            taskFlowId);
        }

        FacesContext context = FacesContext.getCurrentInstance();
        ExtendedRenderKitService extendedRenderKitService =
            Service.getService(context.getRenderKit(),
                               ExtendedRenderKitService.class);

        // Build javascript to open a new browser tab/window
        StringBuilder script = new StringBuilder();

        // Unable to get a named firefox tab to gain focus.  To workaround
        // issue we close the tab first, then open it.
        if (!openInWindow && windowName != null) {

            script.append("var hWinx = window.open(\"");
            script.append("about:blank"); // the URL
            script.append("\",\"");
            script.append(windowName);
            script.append("\"");
            script.append(");");
            script.append("\n");
            script.append("hWinx.close();\n");
        }

        // Set a variable with the window properties
        script.append("var winProps = \"status=yes,toolbar=no,copyhistory=no,width=" +
                      width + ",height=" + height + "\";");
        // If we aren't going to open in a new window, then clear the window properties
        if (!openInWindow) {
            script.append("winProps = '';");
        }
        // Set isOpenerValid to true if window.opener (a parent window) is defined and open
        script.append("var isOpenerValid = (typeof(window.opener) != 'undefined' && window.opener != undefined && !window.opener.closed);");
        // Set useProps to true if openInWindow is true or isOpenerValid is true
        script.append("var useProps = (" + openInWindow +
                      " || isOpenerValid);");
        // Set win to the current window, unless we need to use the parent, then set to window.opener (the parent window)
        script.append("var win = window; if (typeof(isChildWindow) != 'undefined' && isChildWindow != undefined && isChildWindow == true && isOpenerValid) {win = window.opener;}");
        // Set hWin to the window returned by calling open on win
        script.append("var hWin = win.open(\"");
        script.append(url); // the URL
        script.append("\",\"");
        script.append(windowName);
        script.append("\"");
        script.append(", winProps");
        script.append(");");
        // Set focus to the window opened.
        script.append("hWin.focus();");

        extendedRenderKitService.addScript(context, script.toString());
    }

    public static void executeClientSideScript(String script) {
        FacesContext context = FacesContext.getCurrentInstance();
        ExtendedRenderKitService extendedRenderKitService =
            Service.getService(context.getRenderKit(),
                               ExtendedRenderKitService.class);

        extendedRenderKitService.addScript(context, script);
    }


    /**
     * Get the id of the RichShowDetailItem which is currently disclosed within the
     * RichPanelTabbed or null if no children disclosed.
     *
     * @param panelTabbed
     * @return
     */
    public static String getDisclosedDetailItemId(RichPanelTabbed panelTabbed) {
        RichShowDetailItem item = getDisclosedDetailItem(panelTabbed);
        if (item != null) {
            return item.getId();
        }
        return null;
    }

    /**
     * Get the RichShowDetailItem which is currently disclosed within the
     * RichPanelTabbed or null if no children disclosed.
     *
     * @param panelTabbed
     * @return
     */
    public static RichShowDetailItem getDisclosedDetailItem(RichPanelTabbed panelTabbed) {
        if (panelTabbed != null) {
            Iterator iter = panelTabbed.getChildren().iterator();
            // Loop through all the child components
            while (iter.hasNext()) {
                UIComponent component = (UIComponent)iter.next();
                // Make sure we only check components that are detailItems
                if (component instanceof RichShowDetailItem) {
                    RichShowDetailItem detailItem =
                        (RichShowDetailItem)component;
                    if (detailItem.isDisclosed()) {
                        return detailItem;
                    }
                }
            }
        }
        return null;
    }

    /**
     * Helper method to check if a UI component value
     * is null or empty.
     * @param component UIComponent
     * @return true / false
     */
    public static boolean isEmpty(UIComponent component) {
        boolean isEmpty = false;
        if (component == null) {
            isEmpty = true;
        } else {
            // for a text field, check the value as a String
            if (component instanceof RichInputText) {
                RichInputText textField = (RichInputText)component;
                if (textField.getValue() == null ||
                    ((String)textField.getValue()).length() <= 0) {
                    isEmpty = true;
                }
            }

        }
        return isEmpty;
    }

    /**
     * Get the list containging the selected rows for the given table <br/>
     * Make sure the ADF table definition does not have the selection listener
     * and the make current set.
     * @param table
     * @return
     */
    public static List<Row> getSelectedRows(RichTable table) {
        List<Row> rows = new ArrayList<Row>();

        // get the selected row keys (iterator)
        Iterator keyIter = table.getSelectedRowKeys().iterator();
        // remember selected row keys
        Object oldKey = table.getRowKey();
        // loop for each selection
        while (keyIter.hasNext()) {
            
        }
        // restore originally selected rows
        table.setRowKey(oldKey);
        return rows;
    }

    public static void printRow(Row row) {
        System.out.println("\nSTART " + row.getKey() +
                           " *********************");
        for (int i = 0; i < row.getAttributeCount(); i++) {
            System.out.println("row[" + row.getAttributeNames()[i] + "]:[" +
                               row.getAttribute(i) + "]");

        }
        System.out.println("END   " + row.getKey() +
                           "*********************\n");
    }


    /**
     * Get a List of attributes as a Map (of name, value) for an iterator.
     * @param iter iterator binding
     * @param keyAttrName attribut name for the key of the map
     * @param valueAttrName attribut name for the value
     * @return Map of attribute values
     */
    public static Map<Object, Object> attributesMapForIterator(DCIteratorBinding iter,
                                                               String keyAttrName,
                                                               String valueAttrName) {
        Map<Object, Object> amap = new HashMap<Object, Object>();
        for (Row r : iter.getAllRowsInRange()) {
            amap.put(r.getAttribute(keyAttrName),
                     r.getAttribute(valueAttrName));
        }
        return amap;
    }

    /**
     * Get a List of attributes as a Map (of name, value) for an iterator.
     * @param iteratorName ADF iterator binding name
     * @param keyAttrName attribut name for the key of the map
     * @param valueAttrName attribut name for the value
     * @return Map of attribute values
     */
    public static Map<Object, Object> attributeMapForIterator(String iteratorName,
                                                              String keyAttrName,
                                                              String valueAttrName) {
        return attributesMapForIterator(findIterator(iteratorName),
                                        keyAttrName, valueAttrName);
    }

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

    public static Object invokeMethodExpression(String expr, Class returnType,
                                                Class argType,
                                                Object argument) {
        return invokeMethodExpression(expr, returnType,
                                      new Class[] { argType },
                                      new Object[] { argument });
    }
    /**
    * 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);
    }

}

参考文献
1.http://jdeveloper-adf.googlecode.com/svn/trunk/TGPrototype2/ViewController/src/com/tgslc/defaultManagement/utils/ADFUtils.java

[ADF技术-007] JSFUtils.java-ADF工具类


package view;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.model.SelectItem;

import javax.servlet.http.HttpServletResponse;

import oracle.adf.model.binding.DCIteratorBinding;

import oracle.binding.BindingContainer;

import oracle.jbo.Row;
import oracle.jbo.ViewObject;


/**
 * Utils for webpages.
 *
 */
public class JSFUtils {

    private static final String NO_RESOURCE_FOUND = "Missing resource: ";

    private static Map<String, SelectItem> selectItems =
        new HashMap<String, SelectItem>();

    /**
     * Method for taking a reference to a JSF binding expression and returning
     * the matching object (or creating it).
     * @param expression
     * @return Managed object
     */
    public static Object resolveExpression(String expression) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        Application app = ctx.getApplication();
        ValueBinding bind = app.createValueBinding(expression);
        return bind.getValue(ctx);
    }

    /**
     * Convenience method for resolving a reference to a managed bean by name
     * rather than by expression.
     * @param beanName
     * @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
     * @param newValue
     */
    public static void setExpressionValue(String expression, Object newValue) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        Application app = ctx.getApplication();
        ValueBinding bind = app.createValueBinding(expression);
        Class bindClass = bind.getType(ctx);
        if (bindClass.isPrimitive() || bindClass.isInstance(newValue)) {
            bind.setValue(ctx, newValue);
        }
    }

    public static void setManagedBeanValue(String beanName, Object newValue) {
        StringBuffer buff = new StringBuffer("#{");
        buff.append(beanName);
        buff.append("}");
        setExpressionValue(buff.toString(), newValue);
    }


    public static void storeOnSession(String key, Object object) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        Map sessionState = ctx.getExternalContext().getSessionMap();
        sessionState.put(key, object);
    }

    public static Object getFromSession(String key) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        Map sessionState = ctx.getExternalContext().getSessionMap();
        return sessionState.get(key);
    }

    public static Object getSession() {
        return FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    }

    public static Object getFromRequest(String key) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        Map reqMap = ctx.getExternalContext().getRequestMap();
        return reqMap.get(key);
    }


    public static String getStringFromBundle(String key) {
        ResourceBundle bundle = getBundle();
        return getStringSafely(bundle, key, null);
    }


    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;
    }

    public static void addFacesErrorMessage(String msg) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        FacesMessage fm =
            new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, "");
        ctx.addMessage(getRootViewComponentId(), fm);
    }

    public static void addFacesInfoMessage(String msg) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        FacesMessage fm =
            new FacesMessage(FacesMessage.SEVERITY_INFO, msg, "");
        ctx.addMessage(getRootViewComponentId(), fm);
    }

    public static void addFacesErrorMessage(String attrName, String msg) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        FacesMessage fm =
            new FacesMessage(FacesMessage.SEVERITY_ERROR, attrName, msg);
        ctx.addMessage(getRootViewComponentId(), fm);
    }

    public static String getRootViewId() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        return ctx.getViewRoot().getViewId();
    }

    public static String getRootViewComponentId() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        return ctx.getViewRoot().getId();
    }

    private static ResourceBundle getBundle() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        UIViewRoot uiRoot = ctx.getViewRoot();
        Locale locale = uiRoot.getLocale();
        ClassLoader ldr = Thread.currentThread().getContextClassLoader();
        return ResourceBundle.getBundle(ctx.getApplication().getMessageBundle(),
                                        locale, ldr);
    }

    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;
    }

    public static SelectItem getSelectItem(String value) {
        SelectItem item = selectItems.get(value);
        if (item == null) {
            item = createNewSelectItem(value, value);
            selectItems.put(value, item);
        }
        return item;
    }

    public static SelectItem createNewSelectItem(String label, String value) {
        return new SelectItem(value, label);
    }

    public static HttpServletResponse getResponse() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        HttpServletResponse response =
            (HttpServletResponse)ctx.getExternalContext().getResponse();
        return response;

    }

    public static BindingContainer getBindingContainer() {
        return (BindingContainer)JSFUtils.resolveExpression("#{bindings}");
    }

    public static boolean hasRecords(String iteratorName) {
        Row[] rows = getAllRows(iteratorName);
        if ((rows == null) || (rows.length == 0)) {
            return false;
        }
        return true;
    }


    public static void setIteratorPosition(String iteratorName,
                                           String whereClause) throws Exception {
        ViewObject viewObject = getViewObject(iteratorName);
        if (viewObject.getWhereClause() != null) {
            viewObject.setWhereClauseParams(null);
            viewObject.executeQuery();

        }
        viewObject.setWhereClause(whereClause);
        //        viewObject.defineNamedWhereClauseParam(param, null, null);
        //        viewObject.setNamedWhereClauseParam(param, value);
        viewObject.executeQuery();
    }


    public static ViewObject getViewObject(String iteratorName) {
        ViewObject viewObject = null;
        BindingContainer bindings = JSFUtils.getBindingContainer();
        if (bindings != null) {
            DCIteratorBinding iter =
                (DCIteratorBinding)bindings.get(iteratorName);
            viewObject = iter.getViewObject();
        }
        return viewObject;
    }

    public static Row[] getAllRows(String iteratorName) {
        ViewObject vObject = getViewObject(iteratorName);
        vObject.executeQuery();
        Row[] rows = vObject.getAllRowsInRange();
        return rows;
    }

    public static ViewObject executeViewObject(String iteratorName) {
        ViewObject vObject = getViewObject(iteratorName);
        vObject.executeQuery();
        System.out.println("....Total rows..." + vObject.getRowCount());
        return vObject;
    }


    public static Row getCurrentRow(String iteratorName) {
        BindingContainer bindings = getBindingContainer();
        Row currentRow = null;
        if (bindings != null) {

            DCIteratorBinding iter =
                (DCIteratorBinding)bindings.get(iteratorName);
            ViewObject vObject = iter.getViewObject();
            currentRow = vObject.getCurrentRow();
        }
        return currentRow;
    }

    public static void executeIterator(String iteratorName) {
        BindingContainer bindings = getBindingContainer();
        if (bindings != null) {
            DCIteratorBinding iter =
                (DCIteratorBinding)bindings.get(iteratorName);
            ViewObject vObject = iter.getViewObject();
            vObject.executeQuery();
        }
    }

    public static Object getCurrentRowAttribute(String iteratorName,
                                                String attributeName) {
        Row row = getCurrentRow(iteratorName);
        return row.getAttribute(attributeName);
    }

    public static Object getFromRequestParameterMap(String key) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        return ctx.getExternalContext().getRequestParameterMap().get(key);

    }

    public static FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    public static void postMessageToFacesContext(FacesMessage.Severity severity,
                                                 String summary,
                                                 String detail) {
        postMessage(null, severity, summary, detail);
    }

    public static void postMessage(String componentId,
                                   FacesMessage.Severity severity,
                                   String summary, String detail) {
        getFacesContext().addMessage(componentId,
                                     new FacesMessage(severity, summary,
                                                      detail));
    }

}

参考文献
1.http://jdeveloper-adf.googlecode.com/svn/trunk/TGPrototype2/ViewController/src/com/tgslc/defaultManagement/utils/JSFUtils.java


[ADF技术-006] TaskFlowUtils.java-ADF工具类


package view;

import java.util.Collection;

import java.util.HashMap;

import java.util.Map;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;

import oracle.adf.controller.ControllerContext;
import oracle.adf.controller.TaskFlowContext;
import oracle.adf.controller.TaskFlowId;
import oracle.adf.controller.ViewPortContext;
import oracle.adf.controller.metadata.MetadataService;
import oracle.adf.controller.metadata.model.DataControlScopeType;
import oracle.adf.controller.metadata.model.NamedParameter;
import oracle.adf.controller.metadata.model.TaskFlowDefinition;
import oracle.adf.controller.metadata.model.TaskFlowInputParameter;
import oracle.adf.controller.metadata.model.TransactionType;
import oracle.adf.model.BindingContext;
import oracle.adf.model.DataControlFrame;
import oracle.adf.model.binding.DCDataControl;
import oracle.adf.view.rich.context.AdfFacesContext;

/**
 * ADF task flow utilities for use with JDev/ADF 11g+.
 * 
 * Available under the Creative Commons Attribution 3.0 Unported License.
 * See: http://one-size-doesnt-fit-all.blogspot.com/p/terms-conditions.html
 * 
 * Absolutely no warranty implied, *use*at*your*own*risk*.  This code has been mostly used
 * for checking task flow features and hasn't been used in a production environment.
 * 
 * Author: Chris Muir @ Oracle.com
 * Date: 19th April 2012
 */
public class TaskFlowUtils {

    public String getTaskFlowName() {
        MetadataService metadataService = MetadataService.getInstance();
        TaskFlowDefinition taskFlowDefinition = metadataService.getTaskFlowDefinition(getCurrentTaskFlowId());
        String taskFlowName = null;
        if (taskFlowDefinition != null) {
            TaskFlowId taskFlowId = taskFlowDefinition.getTaskFlowId();

            if (taskFlowId != null)
                taskFlowName = taskFlowDefinition.getTaskFlowId().getFullyQualifiedName();
            else
                taskFlowName = "Null";
        } else
            taskFlowName = "Null";


        return taskFlowName;
    }

    public String getTaskFlowControlScopeName() {
        MetadataService metadataService = MetadataService.getInstance();
        String controlScopeTypeString;
        TaskFlowDefinition taskFlowDefinition = metadataService.getTaskFlowDefinition(getCurrentTaskFlowId());
        if (taskFlowDefinition != null) {
            String taskFlowName = taskFlowDefinition.getTaskFlowId().getFullyQualifiedName();
            DataControlScopeType controlScopeType = taskFlowDefinition.getDataControlScopeType();

            if (controlScopeType == null || controlScopeType == DataControlScopeType.SHARED)
                controlScopeTypeString = "Shared Data Control Scope";
            else if (controlScopeType == DataControlScopeType.ISOLATED)
                controlScopeTypeString = "Isolated Data Control Scope";
            else
                controlScopeTypeString = "UNKNOWN Data Control Scope";
        } else
            controlScopeTypeString = "Null";

        return controlScopeTypeString;
    }

    public String getTaskFlowControlTransactionTypeName() {
        MetadataService metadataService = MetadataService.getInstance();
        String transactionTypeString;
        TaskFlowDefinition taskFlowDefinition = metadataService.getTaskFlowDefinition(getCurrentTaskFlowId());
        if (taskFlowDefinition != null) {
            String taskFlowName = taskFlowDefinition.getTaskFlowId().getFullyQualifiedName();

            TransactionType transactionType = taskFlowDefinition.getTransactionType();

            if (transactionType == null)
                transactionTypeString = "-No Controller Transaction-";
            else if (transactionType == TransactionType.NEW_TRANSACTION)
                transactionTypeString = "Always Begin New Transaction";
            else if (transactionType == TransactionType.REQUIRES_TRANSACTION)
                transactionTypeString = "Use Existing Transaction if Possible";
            else if (transactionType == TransactionType.REQUIRES_EXISTING_TRANSACTION)
                transactionTypeString = "Always Use Existing Transaction";
            else
                transactionTypeString = "UNKNOWN Transaction Type";
        } else
            transactionTypeString = "Null";

        return transactionTypeString;
    }

    public HashMap<String, String> formatTaskFlowParameters(Map btfParameters) {
        HashMap<String, String> taskFlowParameterValues = new HashMap<String, String>();

        FacesContext facesContext = FacesContext.getCurrentInstance();
        Application application = facesContext.getApplication();
        AdfFacesContext adfFacesContext = AdfFacesContext.getCurrentInstance();
        Map<String, Object> pageFlowScope = adfFacesContext.getPageFlowScope();

        for (Object parameter : btfParameters.values()) {
            NamedParameter namedParameter = (NamedParameter)parameter;
            String parameterName = namedParameter.getName();
            String parameterExpression = namedParameter.getValueExpression();
            Object parameterValue;
            String stringValue;

            if (parameterExpression == null) {
                parameterValue = pageFlowScope.get(parameterName);
            } else {
                parameterValue = application.evaluateExpressionGet(facesContext, parameterExpression, Object.class);
            }

            if (parameterValue != null) {
                try {
                    stringValue = parameterValue.toString();
                } catch (Exception e) {
                    stringValue = "<complex>";
                }
            } else {
                stringValue = "<null>";
            }

            taskFlowParameterValues.put(parameterName, stringValue);
        }
        return taskFlowParameterValues;
    }

    public TaskFlowId getCurrentTaskFlowId() {
        ControllerContext controllerContext = ControllerContext.getInstance();
        ViewPortContext currentViewPort = controllerContext.getCurrentViewPort();
        TaskFlowContext taskFlowContext = currentViewPort.getTaskFlowContext();
        TaskFlowId taskFlowId = taskFlowContext.getTaskFlowId();

        return taskFlowId;
    }

    public TaskFlowDefinition getTaskFlowDefinition(TaskFlowId taskFlowId) {
        MetadataService metadataService = MetadataService.getInstance();
        TaskFlowDefinition taskFlowDefinition = metadataService.getTaskFlowDefinition(taskFlowId);

        return taskFlowDefinition;
    }

    public Map<String, TaskFlowInputParameter> getCurrentTaskFlowInputParameters() {
        return getInputParameters(getCurrentTaskFlowId());
    }

    public Map<String, TaskFlowInputParameter> getInputParameters(TaskFlowId taskFlowId) {
        TaskFlowDefinition taskFlowDefinition = getTaskFlowDefinition(taskFlowId);
        Map<String, TaskFlowInputParameter> taskFlowInputParameters = taskFlowDefinition.getInputParameters();

        return taskFlowInputParameters;
    }

    public Map<String, NamedParameter> getCurrentTaskFlowReturnParameters() {
        return getReturnParameters(getCurrentTaskFlowId());
    }

    public Map<String, NamedParameter> getReturnParameters(TaskFlowId taskFlowId) {
        TaskFlowDefinition taskFlowDefinition = getTaskFlowDefinition(taskFlowId);
        Map<String, NamedParameter> namedParameters = taskFlowDefinition.getReturnValues();

        return namedParameters;
    }


    public String getDataControlFrameName() {
        BindingContext bindingContext = oracle.adf.controller.binding.BindingUtils.getBindingContext();
        String dataControlFrameName = bindingContext.getCurrentDataControlFrame();

        return dataControlFrameName;
    }

    public DataControlFrame getDataControlFrame() {
        BindingContext bindingContext = oracle.adf.controller.binding.BindingUtils.getBindingContext();
        String dataControlFrameName = bindingContext.getCurrentDataControlFrame();
        DataControlFrame dataControlFrame = bindingContext.findDataControlFrame(dataControlFrameName);

        return dataControlFrame;
    }

    public void commitTaskFlow() {
        getDataControlFrame().commit();
    }

    public void rollbackTaskFlow() {
        getDataControlFrame().rollback();
    }

    public boolean isTaskFlowTransactionDirty() {
        return getDataControlFrame().isTransactionDirty();
    }

    public String getOpenTransactionName() {
        return getDataControlFrame().getOpenTransactionName();
    }

    public String getDataControlNames() {
        BindingContext bindingContext = oracle.adf.controller.binding.BindingUtils.getBindingContext();
        String dataControlFrameName = bindingContext.getCurrentDataControlFrame();
        DataControlFrame dataControlFrame = bindingContext.findDataControlFrame(dataControlFrameName);
        Collection<DCDataControl> dataControls = dataControlFrame.datacontrols();
        String names = "";
        for (DCDataControl dc : dataControls) {
            names = names + "," + dc.getName() + dc.hashCode();
        }

        return names;
    }
}


参考文献
1.https://java.net/downloads/adfemg/TaskFlowUtils.java

[ADF技术-005] Table中Row在最后插入

应用场景:很难具体分析- -.....


1.创建类ViewObjectImplExt继承ViewObjectImpl


2.重写insertRow方法

    public void insertRow(Row row) {
         //super.insertRow(row);
         //row.removeAndRetain();
         last();
         next();
         getDefaultRowSet().insertRow(row);
    }

3.让CompanyEOViewImpl继承ViewObjectImplExt

这样就大功告成了...
效果如下:

[ADF技术-004] Table中增加统计字段

应用场景:统计一个机构下面有多少个员工,统计一个部门员工工资总共多少等

效果如下:

本例子中用到的表结构如下
基础表:Users,Company
关联表:CompanyUsers

1.找到CompanyEOView增加一个新的属性

2.填个名字

3.出来了一个新的属性,类型Integer,如果是有小数点的数字(如:金额)最好类型改成BigDecimal


4.检查CompanyUsersCompany 是否存在关联关系(是否存在ViewLink),如存在,点Accessors右边的铅笔



5.把Source Accessor-In View Object的勾勾上,这个勾的意义就是在Master表中生成访问Detail表的方法(注意:图中的对话框不一定是Source是Master表,Destination是Detail表,所以选择的时候看清楚

6.找到Company表的rowImpl类,确认其中是否存在刚才生成的关联关系



7.选择UserCount,default value 选择表达式(Expression)
value中输入CompanyUsersEOView.count("CompanyId")

CompanyUsersEOView:rowImpl中的关联字段的名字
Count:groovy提供的函数,还有sum,avg,min,max,一共五个函数
CompanyId:CompanyUsersEOView中的字段,需要统计的字段  

refresh expression value 默认为true就可以了

这样就大功告成了!
该字段也不会同步到数据库,并且实时刷新!

效果如下:


参考文献: