You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by sk...@apache.org on 2004/02/29 06:06:58 UTC

cvs commit: jakarta-commons/digester/src/examples/plugins/pipeline CaseTransform.java CompoundTransform.java Pipeline.java SubstituteTransform.java Transform.java build.xml compound.xml input.txt substitute.xml uppercase.xml

skitching    2004/02/28 21:06:58

  Added:       digester/src/examples/plugins/pipeline CaseTransform.java
                        CompoundTransform.java Pipeline.java
                        SubstituteTransform.java Transform.java build.xml
                        compound.xml input.txt substitute.xml uppercase.xml
  Log:
  Plugins example
  
  Revision  Changes    Path
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/CaseTransform.java
  
  Index: CaseTransform.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.
   */ 
  
  /**
   * An implementation of the Transform interface which converts all
   * input text to either upper or lower case.
   * <p>
   * Note that because it doesn't use any nested tags for configuration,
   * just xml attributes which map 1:1 onto bean property-setter methods,
   * there is no need to define any custom addRules method to use this
   * as a Digester plugin class.
   */
  
  public class CaseTransform implements Transform {
      private boolean toLower = true;
      
      public void setCase(String caseType) {
          if (caseType.equalsIgnoreCase("upper"))
              toLower = false;
          else 
              toLower = true;
      }
      
      public String transform(String s) {
          if (toLower)
              return s.toLowerCase();
          else
              return s.toUpperCase();
      }
  }
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/CompoundTransform.java
  
  Index: CompoundTransform.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;
  
  import org.apache.commons.digester.Digester;
  import org.apache.commons.digester.plugins.PluginCreateRule;
  
  /**
   * An implementation of the Transform interface which is configured with
   * a sequence of "subtransforms", and applies them one by one to the input
   * data.
   * <p>
   * This demonstrates that a plugged-in class can itself define plugin-points 
   * for user-defined classes if it wishes.
   */
  
  public class CompoundTransform implements Transform {
      private LinkedList transforms = new LinkedList();
      
      public void addTransform(Transform transform) {
          transforms.add(transform);
      }
      
      public String transform(String s) {
          for(Iterator i = transforms.iterator(); i.hasNext(); ) {
              Transform t = (Transform) i.next();
              s = t.transform(s);
          }
          return s;
      }
      
      public static void addRules(Digester d, String pattern) {
          PluginCreateRule pcr = new PluginCreateRule(Transform.class);
          d.addRule(pattern+"/subtransform", pcr);
          d.addSetNext(pattern+"/subtransform", "addTransform");
      }
  }
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/Pipeline.java
  
  Index: Pipeline.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.plugins.PluginRules;
  import org.apache.commons.digester.plugins.PluginCreateRule;
  import java.io.*;
  
  /**
   * This is the "main" class for this example.
   * <p>
   * It can be run via <code>java Pipeline config-file-name</code>.
   * <p>
   * The specified config file is parsed using the Apache Commons Digester.
   * This config file specifies an input file to be read, a number of
   * user-defined transform classes to be instantiated and configured from
   * the config file, and an output file.
   * <p>
   * The contents of the input file is then passed to the transform objects,
   * and the output written to the output file. 
   * <p>
   * Why not try writing your own transform classes, and plugging them in.
   * Note that they can configure themselves from the main config file in
   * any manner the Digester supports, without changing a line of this
   * application.
   */
   
  public class Pipeline {
      
      private String source;
      private String dest;
      private Transform transformer;
  
      public static void main(String[] args) {
          if (args.length != 1) {
              System.err.println("usage: pipeline config-file");
              System.exit(-1);
          }
          String configFile = args[0];
          
          Digester digester = new Digester();
          PluginRules rc = new PluginRules();
          digester.setRules(rc);
          
          digester.addObjectCreate("pipeline", Pipeline.class);
          
          digester.addCallMethod("pipeline/source", "setSource", 1);
          digester.addCallParam("pipeline/source", 0, "file");
          
          PluginCreateRule pcr = new PluginCreateRule(Transform.class);
          digester.addRule("pipeline/transform", pcr);
          digester.addSetNext("pipeline/transform", "setTransform");
          
          digester.addCallMethod("pipeline/destination", "setDest", 1);
          digester.addCallParam("pipeline/destination", 0, "file");
          
          Pipeline pipeline = null;
          try {
              pipeline = (Pipeline) digester.parse(configFile);
          }
          catch(Exception e) {
              System.err.println("oops exception occurred during parse.");
              e.printStackTrace();
              System.exit(-1);
          }
          
          try {
              pipeline.execute();
          }
          catch (Exception e) {
              System.err.println("oops exception occurred during pipeline execution.");
              e.printStackTrace();
              System.exit(-1);
          }
      }
      
      public void setSource(String source) {
          this.source = source;
      }
      
      public void setDest(String dest) {
          this.dest = dest;
      }
      
      public void setTransform(Transform transformer) {
          this.transformer = transformer;
      }
      
      private void execute() throws IOException {
          FileReader inRaw = new FileReader(source);
          FileWriter out = new FileWriter(dest);
  
          BufferedReader in = new BufferedReader(inRaw);
          
          while(true) {
              String inStr = in.readLine();
              if (inStr==null) 
                  break;
              
              String outStr = transformer.transform(inStr);
              out.write(outStr);
              out.write('\n');
          }
          
          
          inRaw.close();
          out.close();
          
          System.out.println(
              "Contents of file " + source + " have been transformed, and"
              + " written to file " + dest + ".");
      }
  }
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/SubstituteTransform.java
  
  Index: SubstituteTransform.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;
  
  /**
   * An implementation of the Transform interface which replaces all occurrences
   * of a specified string with a different string.
   * <p>
   * Because this class wishes to configure instances via nested "from" and
   * "to" tags, it needs to define an addRules method to add rules to the
   * Digester dynamically. Note that there are different ways of defining the
   * rules though; for example they can be defined in a separate
   * SubstituteTransformRuleInfo class.
   */
   
  public class SubstituteTransform implements Transform {
      private String from;
      private String to;
      
      public void setFrom(String from) {
          this.from = from;
      }
      
      public void setTo(String to) {
          this.to = to;
      }
      
      public String transform(String s) {
          StringBuffer buf = new StringBuffer(s);
          while (true) {
              int idx = buf.indexOf(from);
              if (idx == -1)
                  break;
              
              StringBuffer buf2 = buf.replace(idx, idx+from.length(), to);
          }
          return buf.toString();
      }
      
      public static void addRules(Digester d, String pattern) {
          d.addCallMethod(pattern+"/from", "setFrom", 0);
          d.addCallMethod(pattern+"/to", "setTo", 0);
      }
  }
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/Transform.java
  
  Index: Transform.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.
   */ 
  
  /**
   * An interface that any user class must implement if it wishes to be
   * plugged in at the "transform" tag of a pipeline configuration file.
   */
  
  public interface Transform {
      String transform(String s);
  }
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/build.xml
  
  Index: build.xml
  ===================================================================
  <project name="Example-Pipeline" 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="pipeline"/>
  
  
  <!-- ========== 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-uppercase" depends="compile">
      <java classname="Pipeline" fork="yes">
        <arg value="uppercase.xml"/>
        <classpath refid="compile.classpath"/>
        <classpath>
          <pathelement location="."/>
        </classpath>
      </java>
    </target>
    
    <target name="run-substitute" depends="compile">
      <java classname="Pipeline" fork="yes">
        <arg value="substitute.xml"/>
        <classpath refid="compile.classpath"/>
        <classpath>
          <pathelement location="."/>
        </classpath>
      </java>
    </target>
    
    <target name="run-compound" depends="compile">
      <java classname="Pipeline" fork="yes">
        <arg value="compound.xml"/>
        <classpath refid="compile.classpath"/>
        <classpath>
          <pathelement location="."/>
        </classpath>
      </java>
    </target>
  </project>
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/compound.xml
  
  Index: compound.xml
  ===================================================================
  <!--
    - Example compound pipeline
    -->
    
  <pipeline>
    <source file="input.txt"/>
    <transform plugin-class="CompoundTransform">
      <subtransform plugin-class="CaseTransform" case="lower"/>
      <subtransform plugin-class="SubstituteTransform">
        <from>changeme</from>
        <to>transformed</to>
      </subtransform>
    </transform>
    <destination file="output.txt"/>
  </pipeline>
    
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/input.txt
  
  Index: input.txt
  ===================================================================
  This is a test input file
  for the pipeline demo.
  
  It has multiple lines of text, which
  are transformed one-by-one using
  plugin classes.
  
  HERE IS SOME ALL-UPPERCASE TEXT and here some lowercase text
  which demonstrates the Case Transform plugin.
  
  Here are some lines to demonstrate the substitution plugin:
  changeme 1
  and changeme2
  and changeme again.
  
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/substitute.xml
  
  Index: substitute.xml
  ===================================================================
  <!--
    - Example pipeline which uses the SubstituteTransform plugin class
    -->
    
  <pipeline>
    <source file="input.txt"/>
    <transform plugin-class="SubstituteTransform">
      <from>changeme</from>
      <to>changed</to>
    </transform>
    <destination file="output.txt"/>
  </pipeline>
    
  
  
  
  1.1                  jakarta-commons/digester/src/examples/plugins/pipeline/uppercase.xml
  
  Index: uppercase.xml
  ===================================================================
  <!--
    - Example pipeline which uses the CaseTransform plugin class
    -->
    
  <pipeline>
    <source file="input.txt"/>
    <transform plugin-class="CaseTransform" case="upper"/>
    <destination file="output.txt"/>
  </pipeline>
    
  
  
  

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