封装API-方法

    XWorker是用Java编写的,XWorker中的模型库非常多的来自于其它Java开源类库,封装各种API通过模型可以更加快捷和方便的使用它们。

1.方法的封装步骤

    方法的封装主要是指封装Java的静态方法,不过非静态的方法的封装也是类似的。

1.1.建立动作模型

    方法一般被封装为动作和行为,动作和行为的差别也就是Java中的静态方法和方法的差别。建立动作模型主要方法是原有的静态方法有几个参数,那么就定义几个相关的属性,并且最好为参数定义getXXX方法来获取参数的值。

1.2.编写实现

    动作需要有一个run方法,run方法可以用Java或Groovy等语言来实现,如要考虑性能一般建议使用Java来实现。

2.示例

    下面的示例是Apache的FileUtils的copyURLToFile方法的封装。

2.1.模型代码

<?xml version="1.0" encoding="utf-8"?>

<thing name="CopyURLToFile" descriptors="xworker.lang.MetaDescriptor3/@thing" extends="xworker.lang.actions.SelfAction"
     group="io.file,_actions.utils.file">
    <description><![CDATA[文档放这里]]></description>
    <actions>
        <JavaAction name="run" outerClassName="xworker.io.file.FileActions" methodName="copyURLToFile"></JavaAction>
        <GetObject name="getSource" _xmeta_id_="getSize" descriptors="xworker.lang.actions.ActionUtil/@GetData"
             attributeName="source"></GetObject>
        <GetObject name="getDestination" _xmeta_id_="getDestDir" descriptors="xworker.lang.actions.ActionUtil/@GetData"
             attributeName="destination"></GetObject>
        <GetInt name="getConnectionTimeout" descriptors="xworker.lang.actions.ActionUtil/@GetInt"
             attributeName="connectionTimeout" defaultValue="0"></GetInt>
        <GetInt name="getReadTimeout" descriptors="xworker.lang.actions.ActionUtil/@GetInt"
             attributeName="readTimeout" defaultValue="0"></GetInt>
    </actions>
    <attribute name="name"></attribute>
    <attribute name="label"></attribute>
    <attribute name="source" _xmeta_id_="file" size="50"></attribute>
    <attribute name="destination" _xmeta_id_="output" inputtype="file" size="50"></attribute>
    <attribute name="connectionTimeout"></attribute>
    <attribute name="readTimeout"></attribute>
    <attribute name="description" inputtype="html"></attribute>
</thing>

2.2.属性

    可以看到在上面的模型代码中定义了sourcedestinationconnetionTimeoutreadTimeout四个属性,这四个属性分别对应于Apache的FileUtils的copyURLToFile的四个参数。

    另外模型也定义了getSourcegetDestinationgetConnectionTimeoutgetReadTimeout四个方法,这四个方法可以让使用者灵活的传参数,如可以通过属性指定常量、变量或ognl表达式等等,使用者也可以通过重写以上方法实现自定义的参数获取机制。

2.3.实现

    在上面的模型示例中run方法是用Java实现的,代码如下。

	public static void copyURLToFile(ActionContext actionContext) throws IOException{
		Thing self = actionContext.getObject("self");
		File destination = getFile(self, "getDestination", actionContext);
		URL source = (URL) self.doAction("getSource", actionContext);
		int connectionTimeout = (Integer) self.doAction("getConnectionTimeout", actionContext);
		int readTimeout = (Integer) self.doAction("getReadTimeout", actionContext);
		
		FileUtils.copyURLToFile(source, destination, connectionTimeout, readTimeout);
	}

3.演示说明

    下面1分50秒左右的GIF视频演示了上面的模型CopyURLToFile的两种用法,一是直接在动作模型的参数属性里输入常量,另一种是通过变量传递参数,通过变量传递参数时动作的参数属性的值是以var:开头的。

 

 

 

Copyright ©  2007-2014 XWorker.org  版权所有

沪ICP备08000575号