KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SubstituteTransform


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 import org.apache.commons.digester.Digester;
18
19 /**
20  * An implementation of the Transform interface which replaces all occurrences
21  * of a specified string with a different string.
22  * <p>
23  * Because this class wishes to configure instances via nested "from" and
24  * "to" tags, it needs to define an addRules method to add rules to the
25  * Digester dynamically. Note that there are different ways of defining the
26  * rules though; for example they can be defined in a separate
27  * SubstituteTransformRuleInfo class.
28  */

29  
30 public class SubstituteTransform implements Transform {
31     private String JavaDoc from;
32     private String JavaDoc to;
33     
34     public void setFrom(String JavaDoc from) {
35         this.from = from;
36     }
37     
38     public void setTo(String JavaDoc to) {
39         this.to = to;
40     }
41     
42     public String JavaDoc transform(String JavaDoc s) {
43         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(s);
44         while (true) {
45             int idx = buf.indexOf(from);
46             if (idx == -1)
47                 break;
48             
49             StringBuffer JavaDoc buf2 = buf.replace(idx, idx+from.length(), to);
50         }
51         return buf.toString();
52     }
53     
54     public static void addRules(Digester d, String JavaDoc patternPrefix) {
55         d.addCallMethod(patternPrefix+"/from", "setFrom", 0);
56         d.addCallMethod(patternPrefix+"/to", "setTo", 0);
57     }
58 }
59
Popular Tags