001package org.apache.commons.digester3.examples.plugins.pipeline; 002 003/* 004 * Licensed to the Apache Software Foundation (ASF) under one or more 005 * contributor license agreements. See the NOTICE file distributed with 006 * this work for additional information regarding copyright ownership. 007 * The ASF licenses this file to You under the Apache License, Version 2.0 008 * (the "License"); you may not use this file except in compliance with 009 * the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019 020import org.apache.commons.digester3.Digester; 021 022/** 023 * An implementation of the Transform interface which replaces all occurrences 024 * of a specified string with a different string. 025 * <p> 026 * Because this class wishes to configure instances via nested "from" and 027 * "to" tags, it needs to define an addRules method to add rules to the 028 * Digester dynamically. Note that there are different ways of defining the 029 * rules though; for example they can be defined in a separate 030 * SubstituteTransformRuleInfo class. 031 */ 032public class SubstituteTransform 033 implements Transform 034{ 035 036 private String from; 037 038 private String to; 039 040 public void setFrom( String from ) 041 { 042 this.from = from; 043 } 044 045 public void setTo( String to ) 046 { 047 this.to = to; 048 } 049 050 public String transform( String s ) 051 { 052 StringBuilder buf = new StringBuilder( s ); 053 while ( true ) 054 { 055 int idx = buf.indexOf( from ); 056 if ( idx == -1 ) 057 { 058 break; 059 } 060 061 buf.replace( idx, idx + from.length(), to ); 062 } 063 return buf.toString(); 064 } 065 066 public static void addRules( Digester d, String patternPrefix ) 067 { 068 d.addCallMethod( patternPrefix + "/from", "setFrom", 0 ); 069 d.addCallMethod( patternPrefix + "/to", "setTo", 0 ); 070 } 071 072}