View Javadoc

1   package org.apache.commons.digester3.examples.plugins.pipeline;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one or more
5    * contributor license agreements.  See the NOTICE file distributed with
6    * this work for additional information regarding copyright ownership.
7    * The ASF licenses this file to You under the Apache License, Version 2.0
8    * (the "License"); you may not use this file except in compliance with
9    * the License.  You may obtain a copy of the License at
10   * 
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   * 
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */ 
19  
20  import org.apache.commons.digester3.Digester;
21  
22  /**
23   * An implementation of the Transform interface which replaces all occurrences
24   * of a specified string with a different string.
25   * <p>
26   * Because this class wishes to configure instances via nested "from" and
27   * "to" tags, it needs to define an addRules method to add rules to the
28   * Digester dynamically. Note that there are different ways of defining the
29   * rules though; for example they can be defined in a separate
30   * SubstituteTransformRuleInfo class.
31   */
32  public class SubstituteTransform
33      implements Transform
34  {
35  
36      private String from;
37  
38      private String to;
39  
40      public void setFrom( String from )
41      {
42          this.from = from;
43      }
44  
45      public void setTo( String to )
46      {
47          this.to = to;
48      }
49  
50      public String transform( String s )
51      {
52          StringBuilder buf = new StringBuilder( s );
53          while ( true )
54          {
55              int idx = buf.indexOf( from );
56              if ( idx == -1 )
57              {
58                  break;
59              }
60  
61              buf.replace( idx, idx + from.length(), to );
62          }
63          return buf.toString();
64      }
65  
66      public static void addRules( Digester d, String patternPrefix )
67      {
68          d.addCallMethod( patternPrefix + "/from", "setFrom", 0 );
69          d.addCallMethod( patternPrefix + "/to", "setTo", 0 );
70      }
71  
72  }