001    package net.sourceforge.mp3dings.filter;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: StringReplacer.java 117 2007-11-09 11:09:50Z ringler $
006     *
007     * This program is free software; you can redistribute it and/or
008     * modify it under the terms of the GNU General Public License
009     * as published by the Free Software Foundation; either version 2
010     * of the License, or (at your option) any later version.
011     *
012     * This program is distributed in the hope that it will be useful,
013     * but WITHOUT ANY WARRANTY; without even the implied warranty of
014     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015     * GNU General Public License for more details.
016     *
017     * You should have received a copy of the GNU General Public License
018     * along with this program; if not, write to the Free Software
019     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
020     */
021    
022    import java.util.Arrays;
023    import java.util.Iterator;
024    import java.util.Vector;
025    import java.util.logging.Logger;
026    import java.util.prefs.Preferences;
027    import java.util.regex.Pattern;
028    import java.util.regex.PatternSyntaxException;
029    import net.sourceforge.mp3dings.utils.Bean;
030    
031    /**A filter that performs one or more string/regular expression substitution.
032     * @author Moritz Ringler
033     * @version $Revision: 117 $ ($Date: 2007-11-09 12:09:50 +0100 (Fr, 09 Nov 2007) $)
034     **/
035    public class StringReplacer extends AbstractStringFilter{
036        private static final Logger logger = Logger.getLogger(StringReplacer.class.getPackage().getName());
037            static final long serialVersionUID = 2680490202227545697L;
038            //private boolean include = true;
039            public static final String PROPERTY_RULES = "rules";
040            private boolean regExp = true;
041            private boolean wordMatch = false;
042            private boolean caseSensitive = false;
043    
044            /* must be a vector not a list !! */
045            private Vector rules = new Vector(1,1);
046    
047            /** Constructs a new empty case-sensitive ruleset.
048             */
049            public StringReplacer(){
050            }
051    
052            /** returns a StringReplacer or null **/
053            public static Bean load(Preferences pref, String key){
054                Bean b =  Bean.load(pref, key);
055                if(! (b instanceof StringReplacer) ){
056                    b = null;
057                }
058                return b;
059            }
060    
061            /* must be a vector not a list !! */
062            protected Vector getRuleList(){
063                return rules;
064            }
065    
066            public boolean isRegExp(){
067                return regExp;
068            }
069    
070            public void setRegExp(boolean b){
071                if(regExp != b){
072                    regExp = b;
073                    try{
074                        setFlags();
075                    } catch (PatternSyntaxException ex){
076                        logger.warning(ex.toString());
077                        regExp = !b;
078                        setFlags();
079                    }
080                    firePropertyChange("regExp",!regExp, regExp);
081                }
082            }
083    
084            public boolean isCaseSensitive(){
085                return caseSensitive;
086            }
087    
088            public void setCaseSensitive(boolean b){
089                if(caseSensitive != b){
090                    caseSensitive = b;
091                    setFlags();
092                    firePropertyChange("caseSensitive",!b, b);
093                }
094            }
095    
096            public boolean isWordMatch(){
097                return wordMatch;
098            }
099    
100            public void setWordMatch(boolean b){
101                if(wordMatch != b){
102                    wordMatch = b;
103                    setFlags();
104                    firePropertyChange("wordMatch",!b, b);
105                }
106            }
107    
108            /** Returns a String representation of this Object.
109             *  @return a String of rules
110             **/
111            public String toString(){
112                Object[] rule;
113                StringBuffer sb = new StringBuffer(getSize()*10+15);
114                sb.append(getName()).append("[");
115                Iterator rIterator = rules.iterator();
116                while (rIterator.hasNext()){
117                    rule = (Object[]) rIterator.next();
118                    sb.append(Arrays.asList(rule).toString()).append(",\n");
119                }
120                sb.append("[");
121                return sb.toString();
122            }
123    
124            /** Returns the string pattern of the specified pattern
125              * with embedded flags and quoting removed.
126              **/
127            private String extractPattern(Pattern p){
128                String str = p.pattern();
129                //remove embedded flags
130                str = str.replaceAll("^\\(\\?[-idmsux]+\\)","");
131                //remove MATCH_WORD flag
132                /* this does work in Java 1.6 but I now prefer the solution below
133                str = str.replaceAll("^\\\\b","");
134                str = str.replaceAll("\\\\b$","");
135                */
136                if(str.startsWith("\\b") && str.endsWith("\\b")){
137                    str = str.substring(2, str.length() - 2);
138                }
139                //remove string quoting
140                /* does not work in Java 6
141                str = str.replaceAll("^\\\\Q","");
142                str = str.replaceAll("\\\\E$","");
143                */
144                if(str.startsWith("\\Q") && str.endsWith("\\E")){
145                    str = str.substring(2, str.length() - 2);
146                }
147                return str;
148            }
149    
150            /** Adds a new rule to this ruleset.
151             * @param pattern a string or regular expression pattern matching the
152             *        parts of the input that you want replaced
153             * @param replacement the replacement string
154             **/
155            public void addRule(String pattern, String replacement){
156                insertRule(pattern, replacement, rules.size());
157            }
158    
159            /** Adds a new rule to this ruleset.
160             * @param pattern the matching pattern (string or regular expression)
161             * @param replacement the replacement string
162             * @param i the index of the rule in the ruleset. For two rules the
163             *        one with smaller index will have higher precedence.
164             **/
165            public void insertRule(String pattern, String replacement, int i){
166                rules.insertElementAt(new Object[]{compile(pattern), replacement},  i);
167                firePropertyChange(PROPERTY_RULES,null,rules);
168            }
169    
170            protected Pattern compile(String pattern){
171                String p = (regExp) ? pattern : "\\Q"+pattern+"\\E";
172                if(wordMatch){
173                    p = "\\b" + p + "\\b";
174                }
175                //MULTILINE mode
176                String embeddedFlags = "?m";
177                //unicode case-insensitive matching
178                if(!caseSensitive){
179                    embeddedFlags += "iu";
180                }
181                p = "("+embeddedFlags+")"+p;
182                return Pattern.compile(p);
183            }
184    
185            protected void replaceRule(String pattern, String replacement, int i){
186                Object[] rule = (Object[]) rules.get(i);
187                rule[0] = compile(pattern);
188                rule[1] = replacement;
189                firePropertyChange(PROPERTY_RULES,null,rules);
190            }
191    
192            public void setFlags(){
193                //this clumsy procedure is the price we pay for storing the
194                //rules in compiled form
195                String[][] rulestr = getRulesAsStrings();
196                final int n = rulestr.length;
197                for (int i=0; i<n; i++){
198                    replaceRule(rulestr[i][0],rulestr[i][1], i);
199                }
200            }
201    
202            /** Applies the given rule to the input string and returns the result.
203            **/
204            private String replace(String input, Object[] rule){
205                return ((Pattern) rule[0]).matcher(input).
206                        replaceAll((String) rule[1]);
207            }
208    
209            /** Applies all rules in this ruleset to the specified string and
210             *  returns the result.
211             *  @param val the String to process (remains unchanged)
212             *  @return a new String resulting from applying all replacement rules to the input.
213            **/
214            public String filterString(String val){
215                String str = val;
216                Iterator rIterator = rules.iterator();
217                while (rIterator.hasNext()){
218                    str = replace(str, (Object[]) rIterator.next());
219                }
220                return str;
221            }
222    
223            /** Returns the number of rules currently in this ruleset.
224             *  @return the number of rules in the ruleset
225             */
226            public int getSize(){
227                return rules.size();
228            }
229    
230            /** Returns the rule with index i as a string pair. Equivalent to
231             * but more efficient than {@link #getRulesAsStrings() getRulesAsStrings()[i]}.
232             *  @param i the index of the rule returned
233             *  @return the specified rule as a string array with length 2
234             */
235            public String[] getRule(int i){
236                Object[] o = (Object[]) rules.get(i);
237                return ruleToStrings(o, null);
238            }
239    
240            protected String[] ruleToStrings(Object[] rule, String[] result){
241                String[] val = result;
242                if (val == null){
243                    val = new String[2];
244                }
245                val[0] = extractPattern((Pattern) rule[0]);
246                val[1] = (String) rule[1];
247                return val;
248            }
249    
250            /** Returns the ruleset as an array of string pairs.
251             * The first element (index 0) in each pair is the matching pattern
252             * and the second element (index 1) is the replacement.
253             * @return an array of rules as string pairs
254             * @see #getRule(int)
255             **/
256            public String[][] getRulesAsStrings(){
257                String[][] val = new String[rules.size()][2];
258                Object[] rule;
259                for (int i=0; i<rules.size(); i++){
260                    rule = (Object[]) rules.get(i);
261                    val[i][0] = extractPattern((Pattern) rule[0]);
262                    val[i][1] = (String) rule[1];
263                }
264                return val;
265            }
266    
267            /** This method is public as an implementation side effect. It must
268                never be invoked by a client. **/
269            public void setRulesAsStrings(String[][] rs){
270                Object[][] r = new Object[rs.length][2];
271                for (int i=0; i<r.length; i++){
272                    r[i][0] = compile(rs[i][0]);
273                    r[i][1] = rs[i][1];
274                }
275                rules = new Vector(Arrays.asList(r));
276                firePropertyChange(PROPERTY_RULES,null,rules);
277            }
278    
279            /** Deletes the rule with index i from this ruleset.
280             * @param i the index of the rule to delete
281            **/
282            public String[] deleteRule(int i){
283                String[] val = getRule(i);
284                rules.remove(i);
285                firePropertyChange(PROPERTY_RULES,null,rules);
286                return val;
287            }
288    
289            public boolean equals(Object o){
290                if(this == o){
291                    return true;
292                }
293                boolean result = false;
294                if(o instanceof StringReplacer){
295                    StringReplacer other = (StringReplacer) o;
296                    result = (caseSensitive == other.caseSensitive);
297                    result = result && (regExp == other.regExp);
298                    result = result && (wordMatch == other.wordMatch);
299                    result = result && ((getName() == null)
300                                            ? (other.getName() == null)
301                                            : getName().equals(other.getName()));
302                    result = result && (rules.size() == other.rules.size());
303                    if(result){
304                        Iterator itThis = rules.iterator();
305                        Iterator itOther = other.rules.iterator();
306                        while(result && itThis.hasNext() && itOther.hasNext()){
307                            result = Arrays.equals(
308                                    (Object[]) itThis.next(),
309                                    (Object[]) itOther.next());
310                        }
311                    }
312                    return result;
313                }
314                return result;
315            }
316    
317            public int hashCode(){
318                int result = 19;
319                result = 43 * result + (caseSensitive? 0 : 1);
320                result = 43 * result + (regExp? 0 : 1);
321                result = 43 * result + (wordMatch? 0 : 1);
322                result = 43 * result +
323                        ((getName() == null)? 0 : getName().hashCode());
324                Iterator it = rules.iterator();
325                Object[] x;
326                while(it.hasNext()){
327                    x = (Object[]) it.next();
328                    if(x == null){
329                        result *= 43;
330                    } else {
331                        for (int i = 0; i<x.length; i++){
332                            result = 43 * result +
333                            ((x[i] == null)? 0 : x[i].hashCode());
334                        }
335                    }
336                }
337                return result;
338            }
339    }