利用Jakarta Commons Digester匹配xml配置文件信息与其对应的xml规则文件形成Java Object

类别:Java 点击:0 评论:0 推荐:

利用Jakarta Commons Digester匹配xml配置文件信息与其对应的xml规则文件形成Java Object

说明:在这里以一个简单的例子来说明如何使用Digester。

第一步:下载Digester
在http://jakarta.apache.org/commons/index.html页面找到Digester Project,并下载commons-digester-1.6.zip(我使用的)

第二步:所需主要lib
commons-digester.jar : 这个就是Digester主要的lib
   (digester中解析xml利用的是Sax方法,有可能需要crimson.jar,在我的JBuilder环境就不需要,因为jdk已经带了解析xml文件的lib)
commons-beanutils.jar : 主要公用包(请查看http://www.apache.org)
commons-logging.jar : 其log包,由于commons-digester.jar该包中使用

 

第三步:书写xml配置文件(config.xml)、xml规则文件(rules.xml)与Java Object(Example.java)
1.config.xml
<?xml version="1.0" encoding="UTF-8"?>
<db-base-config>
  <control>
    <queue-connection-factory>java:/ConnectionFactory</queue-connection-factory>
    <sender-queue>
      <param name="Internet">queue/Email</param>
      <param name="CDMA">queue/SmsCdma</param>
    </sender-queue>
  </control>
  <db-foreign-exchange-sql>
    <publication_id>1</publication_id>
    <receiver-list>
      <param>Telephone</param>
      <param>Email</param>
    </receiver-list>
  </db-foreign-exchange-sql>
</db-base-config>

2. rules.xml
<?xml version="1.0" encoding="UTF-8"?>
<digester-rules>
  <pattern value="db-base-config/control">
    <call-method-rule pattern="queue-connection-factory" methodname="setQueueConnectionFactory" paramcount="0"/>
    <pattern value="sender-queue/param">
      <call-method-rule methodname="addSenderQueue" paramcount="2"/>
      <call-param-rule paramnumber='0' attrname='name'/>
      <call-param-rule paramnumber='1'/>
    </pattern>
  </pattern>
  <pattern value="db-base-config/db-foreign-exchange-sql">
    <call-method-rule pattern="publication_id" methodname="setExchangePublicationID" paramcount="0"/>
    <pattern value="receiver-list/param">
      <call-method-rule methodname="addReceiverList" paramcount="0"/>
    </pattern>
  </pattern>
</digester-rules>

 

3. Example.java
import java.net.*;
import java.util.*;

import org.apache.commons.digester.*;
import org.apache.commons.digester.xmlrules.*;

public class Example {

  /*
   以下两个String变量,严实在xml配置文件,在不同节点下查找
  */
  private String queueConnectionFactory = null;
  private String exchangePublicationID = null;

/*
   以下两个主要演示xml配置文件,是怎样形成Collection的
*/
  private HashMap senderQueueMap = new HashMap();
  private LinkedList receiverList = new LinkedList();

  public Example() {
    try {

      /*
       请把两个xml放在该Example的class文件,使该类能找到xml文件
      */
      URL inputURL = getClass().getResource("config.xml");
      URL rulesURL = getClass().getResource("rules.xml");

      Digester digester = DigesterLoader.createDigester(rulesURL);
      digester.push(this);
      digester.parse(inputURL.openStream());

    }
    catch (Exception e) {
      System.out.print(
          "Can not get configurations, system initialization failed." +
          e.toString());
      System.exit(1);
    }
    System.out.print("Get configurations is successful ");
  }

  public static void main(String[] args) {
    Example paramconfig = new Example();
    System.out.print(paramconfig.getSenderQueueMap());
    System.out.println(paramconfig.getExchangePublicationID());
    System.out.print(paramconfig.getReceiverList());
  }

  public String getQueueConnectionFactory() {
    return queueConnectionFactory;
  }

  public HashMap getSenderQueueMap() {
    return senderQueueMap;
  }

  public String getExchangePublicationID() {
    return exchangePublicationID;
  }

  /*增加Map元素*/
  public void addSenderQueue(String name, String value) {
    senderQueueMap.put(name.toLowerCase(), value);
  }

  public LinkedList getReceiverList() {
    return receiverList;
  }

  public void setQueueConnectionFactory(String queueConnectionFactory) {
    this.queueConnectionFactory = queueConnectionFactory;
  }

  /*增加LinkedList元素*/
  public void addReceiverList(String value) {
    receiverList.addLast(value);
  }

  public void setSenderQueueMap(HashMap senderQueueMap) {
    this.senderQueueMap = senderQueueMap;
  }

  public void setExchangePublicationID(String exchangePublicationID) {
    this.exchangePublicationID = exchangePublicationID;
  }

  public void setReceiverList(LinkedList receiverList) {
    this.receiverList = receiverList;
  }
}


说明:请注意rules.xml的中pattern属性以及methodname属性

第四步:运行(在Jbuilder下调试通过)

第五步:(高级)形成DataSource的例子

以配置Oracle为例子,所增lib(class12.jar:oracle jdbc driver)
1.config.xml
<?xml version="1.0" encoding="UTF-8"?>
<db-base-config>
 <database>
   <user>user</user>
   <password>pwd</password>
 </database>
 <db-provider class="oracle.jdbc.pool.OracleDataSource">
    <user>user</user>
    <password>pwd</password>
    <driver-type>thin</driver-type>
    <server-name>192.168.0.59</server-name>
    <network-protocol>tcp</network-protocol>
    <port-number>1521</port-number>
    <database-name>example</database-name>
  </db-provider>
</db-base-config>

2.rules.xml
<?xml version="1.0" encoding="UTF-8"?>
<digester-rules>
 <pattern value="db-base-config/database">
    <call-method-rule pattern="user" methodname="setDbUser" paramcount="0" />
    <call-method-rule pattern="password" methodname="setDbPass" paramcount="0" />
 </pattern>
 <pattern value="db-base-config/db-provider">
  <object-create-rule classname="oracle.jdbc.pool.OracleDataSource" attrname="class" />  
  <call-method-rule pattern="user" methodname="setUser" paramcount="0" />
  <call-method-rule pattern="password" methodname="setPassword" paramcount="0" />
  <call-method-rule pattern="driver-type" methodname="setDriverType" paramcount="0" />
  <call-method-rule pattern="server-name" methodname="setServerName" paramcount="0" />
  <call-method-rule pattern="network-protocol" methodname="setNetworkProtocol" paramcount="0" />
  <call-method-rule pattern="port-number" methodname="setPortNumber" paramcount="0" paramtypes="java.lang.Integer" />
  <call-method-rule pattern="database-name" methodname="setDatabaseName" paramcount="0" />
  <set-next-rule methodname="setDs" />
 </pattern>
</digester-rules>

3. Java Object

import javax.sql.DataSource;
import java.net.*;
import java.util.*;

import org.apache.commons.digester.*;
import org.apache.commons.digester.xmlrules.*;

public class Example {
 private static DataSource ds = null;

 private String dbUser = null;
 private String dbPass = null;

 public Example() {
    try {

      /*
       请把两个xml放在该Example的class文件,使该类能找到xml文件
      */
      URL inputURL = getClass().getResource("config.xml");
      URL rulesURL = getClass().getResource("rules.xml");

      Digester digester = DigesterLoader.createDigester(rulesURL);
      digester.push(this);
      digester.parse(inputURL.openStream());

    }
    catch (Exception e) {
      System.out.print(
          "Can not get configurations, system initialization failed." +
          e.toString());
      System.exit(1);
    }
    System.out.print("Get configurations is successful ");
  }

public static void main(String[] args) {
 Example paramconfig = new Example();
 DataSource dataSource = paramconfig.getDs().getConnection();
 //已经得到connection,就看你处理数据库的能力的,呵呵
 java.sql.Connection conn = dataSource.getConnection(paramconfig.getDbUser(),paramconfig.getDbPass());

 }

public DataSource getDs() {
        return ds;
    }
 public void setDs(DataSource ds) {
        this.ds = ds;
    }

 public String getDbPass() {
        return dbPass;
    }

    public String getDbUser() {
        return dbUser;
    }

 public void setDbPass(String dbPass) {
        this.dbPass = dbPass;
    }

    public void setDbUser(String dbUser) {
        this.dbUser = dbUser;
    }
}

总结:Digester功能越来越强大,在这里我只是抛砖引玉。
     Java Application Framework---Spring 的Dependency Injection是非常强大
     大家可以有空研究一下。

本文地址:http://com.8s8s.com/it/it13337.htm