commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From skitch...@apache.org
Subject cvs commit: jakarta-commons/digester/src/examples/xmlrules/addressbook AddressBook.java Main.java Person.java build.xml example.xml readme.txt xmlrules.xml
Date Sat, 17 Apr 2004 10:54:06 GMT
skitching    2004/04/17 03:54:06

  Added:       digester/src/examples/xmlrules/addressbook AddressBook.java
                        Main.java Person.java build.xml example.xml
                        readme.txt xmlrules.xml
  Log:
  basic example demonstrating use of the xmlrules module.
  
  Revision  Changes    Path
  1.1                  jakarta-commons/digester/src/examples/xmlrules/addressbook/AddressBook.java
  
  Index: AddressBook.java
  ===================================================================
  /*
   * Copyright 2001-2004 The Apache Software Foundation.
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   * 
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */ 
  
  import java.util.LinkedList;
  import java.util.Iterator;
  
  /**
   * See Main.java.
   */
  public class AddressBook {
      LinkedList people = new LinkedList();
      
      public void addPerson(Person p) {
          people.addLast(p);
      }
      
      public void print() {
          System.out.println("Address book has " + people.size() + " entries");
  
          for(Iterator i = people.iterator(); i.hasNext(); ) {
              Person p = (Person) i.next();
              p.print();
          }
      }
  }
  
  
  
  1.1                  jakarta-commons/digester/src/examples/xmlrules/addressbook/Main.java
  
  Index: Main.java
  ===================================================================
  /*
   * Copyright 2001-2004 The Apache Software Foundation.
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   * 
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */ 
  
  import org.apache.commons.digester.Digester;
  import org.apache.commons.digester.xmlrules.DigesterLoader;
  import org.xml.sax.InputSource;
  import java.net.URL;
  
  /**
   * A simple program to demonstrate the basic functionality of the
   * Commons Digester module with the xmlrules extension.
   * <p>
   * This code will parse the provided "example.xml" file to build a tree
   * of java objects, then cause those objects to print out their values
   * to demonstrate that the input file has been processed correctly.
   * <p>
   * Unlike the "addressbook" example in the "api" section, this implementation
   * has no parsing rules hard-wired into the code in this class. Instead, the
   * parsing rules are loaded from an external file at runtime. This allows
   * the parsing rules to be modified without compiling the code, and 
   * potentially makes it somewhat easier to review the parsing rules.
   * <p>
   * Note, however, that there is tyically quite a tight coupling between
   * the parsing rules and the <i>purpose</i> of the application which means
   * that it may not be all that common for parsing rules to be altered
   * without the application code also being altered, so only in some cases
   * will this prove of benefit. As with all software, it must be determined
   * whether this feature provides a true benefit in the context of the 
   * application it is being applied to.
   * <p>
   * Usage: java Main xmlrules.xml example.xml
   */
  public class Main {
      
      /**
       * Main method : entry point for running this example program.
       * <p>
       * Usage: java Example example.xml
       */
      public static void main(String[] args) throws Exception {
          if (args.length != 2) {
              usage();
              System.exit(-1);
          }
          
          String rulesfileName = args[0];
          String datafileName = args[1];
          
          // Create a Digester instance which has been initialised with
          // rules loaded from the specified file.
          URL rulesURL = ClassLoader.getSystemResource(rulesfileName);
          if (rulesURL == null) {
              System.out.println("Unable to find rules file.");
              System.exit(-1);
          }
          Digester d = DigesterLoader.createDigester(rulesURL);
          
          // Prime the digester stack with an object for rules to
          // operate on. Note that it is quite common for "this"
          // to be the object pushed.
          AddressBook book = new AddressBook();
          d.push(book);
          
          // Process the input file.
          try {
              java.io.File srcfile = new java.io.File(datafileName);
              d.parse(srcfile);
          }
          catch(java.io.IOException ioe) {
              System.out.println("Error reading input file:" + ioe.getMessage());
              System.exit(-1);
          }
          catch(org.xml.sax.SAXException se) {
              System.out.println("Error parsing input file:" + se.getMessage());
              System.exit(-1);
          }
          
          
          // Print out all the contents of the address book, as loaded from
          // the input file.
          book.print();
      }
      
      private static void usage() {
          System.out.println("Usage: java Main xmlrules.xml example.xml");
      }
  }
  
  
  1.1                  jakarta-commons/digester/src/examples/xmlrules/addressbook/Person.java
  
  Index: Person.java
  ===================================================================
  /*
   * Copyright 2001-2004 The Apache Software Foundation.
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   * 
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */ 
  
  import java.util.HashMap;
  import java.util.Iterator;
  
  /**
   * See Main.java.
   */
  public class Person {
    private int id;
    private String category;
    private String name;
    private HashMap emails = new HashMap();
    
    /** 
     * A unique id for this person. Note that the Digester automatically
     * converts the id to an integer.
     */
    public void setId(int id) {
        this.id = id;
    }
    
    public void setCategory(String category) {
        this.category = category;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    /** we assume only one email of each type... */
    public void addEmail(String type, String address) {
        emails.put(type, address);
    }
  
    public void print() {
        System.out.println("Person #" + id);
        System.out.println("  category=" + category);
        System.out.println("  name=" + name);
        
        for(Iterator i = emails.keySet().iterator(); i.hasNext(); ) {
            String type = (String) i.next();
            String address = (String) emails.get(type);
            
            System.out.println("  email (type " + type + ") : " + address);
        }
    }
  }
  
  
  
  1.1                  jakarta-commons/digester/src/examples/xmlrules/addressbook/build.xml
  
  Index: build.xml
  ===================================================================
  <project name="Example-AddressBook" default="compile" basedir=".">
  
  
  <!-- ========== Initialize Properties ===================================== -->
  
  
    <property file="build.properties"/>                <!-- Component local   -->
    <property file="../build.properties"/>             <!-- examples/api local-->
    <property file="../../../../build.properties"/>    <!-- Digester local     -->
    <property file="../../../../../build.properties"/> <!-- Commons local     -->
    <property file="${user.home}/build.properties"/>   <!-- User local        -->
  
  
  <!-- ========== External Dependencies ===================================== -->
  
  
    <!-- The directories corresponding to your necessary dependencies -->
    <property name="jaxp.home"               value="/usr/local/jaxp1.1"/>
    <property name="commons.home"            value="../../../../.."/>
    <property name="beanutils.home"          value="${commons.home}/beanutils"/>
    <property name="collections.home"        value="${commons.home}/collections"/>
    <property name="logging.home"            value="${commons.home}/logging"/>
    <property name="digester.home"            value="${commons.home}/digester"/>
  
  
  <!-- ========== Derived Values ============================================ -->
  
  
    <!-- The locations of necessary jar files -->
    <property name="jaxp.jaxp.jar"           value="${jaxp.home}/jaxp.jar"/>
    <property name="jaxp.parser.jar"         value="${jaxp.home}/crimson.jar"/>
    <property name="commons-beanutils.jar"   value="${beanutils.home}/dist/commons-beanutils.jar"/>
    <property name="commons-collections.jar" value="${collections.home}/dist/commons-collections.jar"/>
    <property name="commons-logging.jar"     value="${logging.home}/dist/commons-logging.jar"/>
    <property name="commons-digester.jar"     value="${digester.home}/dist/commons-digester.jar"/>
  
  
  <!-- ========== Component Declarations ==================================== -->
  
    <!-- The name of this component -->
    <property name="component.name"          value="addressbook"/>
  
  
  <!-- ========== Compiler Defaults ========================================= -->
  
    <!-- Should Java compilations set the 'debug' compiler option? -->
    <property name="compile.debug"           value="true"/>
  
    <!-- Should Java compilations set the 'deprecation' compiler option? -->
    <property name="compile.deprecation"     value="false"/>
  
    <!-- Should Java compilations set the 'optimize' compiler option? -->
    <property name="compile.optimize"        value="true"/>
  
    <!-- Construct compile classpath -->
    <path id="compile.classpath">
      <pathelement location="."/>
      <pathelement location="${jaxp.jaxp.jar}"/>
      <pathelement location="${jaxp.parser.jar}"/>
      <pathelement location="${commons-beanutils.jar}"/>
      <pathelement location="${commons-collections.jar}"/>
      <pathelement location="${commons-logging.jar}"/>
      <pathelement location="${commons-digester.jar}"/>
    </path>
  
  
  <!-- ========== Executable Targets ======================================== -->
  
  
    <target name="compile">
      <javac  srcdir="."
             destdir="."
               debug="${compile.debug}"
         deprecation="${compile.deprecation}"
            optimize="${compile.optimize}">
        <classpath refid="compile.classpath"/>
      </javac>
    </target>
  
  
    <target name="clean">
      <delete>
        <fileset dir="." includes="*.class"/>
      </delete>
      <delete dir="docs"/>
    </target>
  
    <target name="all" depends="clean,compile"/>
  
    <target name="javadoc" depends="compile">
      <mkdir      dir="docs"/>
      <javadoc destdir="docs"
                   author="true"
                  private="true"
                  version="true">
        <classpath  refid="compile.classpath"/>
        <fileset dir="." includes="*.java"/>
      </javadoc>
    </target>
  
    <target name="run" depends="compile">
      <java classname="Main" fork="yes">
        <arg value="xmlrules.xml"/>
        <arg value="example.xml"/>
        <classpath refid="compile.classpath"/>
        <classpath>
          <pathelement location="."/>
        </classpath>
      </java>
    </target>
  </project>
  
  
  
  1.1                  jakarta-commons/digester/src/examples/xmlrules/addressbook/example.xml
  
  Index: example.xml
  ===================================================================
  
  <address-book>
    <person id="1" category="acquaintance">
      <name>Gonzo</name>
      <email type="business">gonzo@muppets.com</email>
    </person>
  
    <person id="2" category="rolemodel">
      <name>Kermit</name>
      <email type="business">kermit@muppets.com</email>
      <email type="home">kermie@acme.com</email>
    </person>
  
  </address-book>
  
  
  1.1                  jakarta-commons/digester/src/examples/xmlrules/addressbook/readme.txt
  
  Index: readme.txt
  ===================================================================
  == overview
  
  The files in this directory are intended as an example of how to use
  the Apache Digester's basic functionality via its xmlrules interface.
  
  Topics covered:
  * how to create a digester instance initialised with
    rules specified in an external file.
  * how to parse a file
  * how to use the "object create" rule to create java objects
  * how to use the "set properties" rule (basic usage) to map xml attributes
    to java bean properties.
  * how to use the "set next" rule to build trees of java objects.
  * how to use the "call method rule" (basic usage)
  * how to use the "call parameter rule" to process the text contained
    in a tag's body
  * how to use the "call parameter rule" to process the contents of an 
    xml attribute.
  
  == compiling and running
  
  First rename the build.properties.sample file in the parent directory
  to build.properties and edit it to suit your environment. Then in this
  directory:
  
  * to compile:
    ant compile
  
  * to run:
    ant run
  
  Alternatively, you can set up your CLASSPATH appropriately, and
  run the example directly. See the build.properties and build.xml
  files for details.
  
  
  
  1.1                  jakarta-commons/digester/src/examples/xmlrules/addressbook/xmlrules.xml
  
  Index: xmlrules.xml
  ===================================================================
  <?xml version="1.0"?>
  
  <!--
   Copyright 2004 The Apache Software Foundation.
    
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
    
        http://www.apache.org/licenses/LICENSE-2.0
    
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
  -->
  
  <!DOCTYPE digester-rules 
    PUBLIC "-//Jakarta Apache //DTD digester-rules XML V1.0//EN" 
      "http://jakarta.apache.org/commons/digester/dtds/digester-rules.dtd">
  
  <digester-rules>
    <pattern value="address-book">
      <pattern value="person">
        <object-create-rule classname="Person"/>
        <set-properties-rule/>
        <set-next-rule methodname="addPerson"/>
        
        <pattern value="name">
          <call-method-rule methodname="setName" paramcount="0"/>
        </pattern>
        
        <pattern value="email">
          <call-method-rule methodname="addEmail" paramcount="2"/>  
          <call-param-rule paramnumber='0' attrname='type'/>
          <call-param-rule paramnumber='1'/>
        </pattern>
      </pattern>
    </pattern>
  </digester-rules>
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message