001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.codec.language;
019
020import org.apache.commons.codec.EncoderException;
021import org.apache.commons.codec.StringEncoder;
022
023/**
024 * Encodes a string into a Refined Soundex value. A refined soundex code is
025 * optimized for spell checking words. Soundex method originally developed by
026 * <CITE>Margaret Odell</CITE> and <CITE>Robert Russell</CITE>.
027 *
028 * <p>This class is immutable and thread-safe.</p>
029 *
030 */
031public class RefinedSoundex implements StringEncoder {
032
033    /**
034     * Mapping:
035     * <pre>
036     * 0: A E I O U Y H W
037     * 1: B P
038     * 2: F V
039     * 3: C K S
040     * 4: G J
041     * 5: Q X Z
042     * 6: D T
043     * 7: L
044     * 8: M N
045     * 9: R
046     * </pre>
047     * @since 1.4
048     */
049    //                                                      ABCDEFGHIJKLMNOPQRSTUVWXYZ
050    public static final String US_ENGLISH_MAPPING_STRING = "01360240043788015936020505";
051
052   /**
053     * RefinedSoundex is *refined* for a number of reasons one being that the
054     * mappings have been altered. This implementation contains default
055     * mappings for US English.
056     */
057    private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray();
058
059    /**
060     * Every letter of the alphabet is "mapped" to a numerical value. This char
061     * array holds the values to which each letter is mapped. This
062     * implementation contains a default map for US_ENGLISH
063     */
064    private final char[] soundexMapping;
065
066    /**
067     * This static variable contains an instance of the RefinedSoundex using
068     * the US_ENGLISH mapping.
069     */
070    public static final RefinedSoundex US_ENGLISH = new RefinedSoundex();
071
072     /**
073     * Creates an instance of the RefinedSoundex object using the default US
074     * English mapping.
075     */
076    public RefinedSoundex() {
077        this.soundexMapping = US_ENGLISH_MAPPING;
078    }
079
080    /**
081     * Creates a refined soundex instance using a custom mapping. This
082     * constructor can be used to customize the mapping, and/or possibly
083     * provide an internationalized mapping for a non-Western character set.
084     *
085     * @param mapping
086     *                  Mapping array to use when finding the corresponding code for
087     *                  a given character
088     */
089    public RefinedSoundex(final char[] mapping) {
090        this.soundexMapping = new char[mapping.length];
091        System.arraycopy(mapping, 0, this.soundexMapping, 0, mapping.length);
092    }
093
094    /**
095     * Creates a refined Soundex instance using a custom mapping. This constructor can be used to customize the mapping,
096     * and/or possibly provide an internationalized mapping for a non-Western character set.
097     *
098     * @param mapping
099     *            Mapping string to use when finding the corresponding code for a given character
100     * @since 1.4
101     */
102    public RefinedSoundex(final String mapping) {
103        this.soundexMapping = mapping.toCharArray();
104    }
105
106    /**
107     * Returns the number of characters in the two encoded Strings that are the
108     * same. This return value ranges from 0 to the length of the shortest
109     * encoded String: 0 indicates little or no similarity, and 4 out of 4 (for
110     * example) indicates strong similarity or identical values. For refined
111     * Soundex, the return value can be greater than 4.
112     *
113     * @param s1
114     *                  A String that will be encoded and compared.
115     * @param s2
116     *                  A String that will be encoded and compared.
117     * @return The number of characters in the two encoded Strings that are the
118     *             same from 0 to to the length of the shortest encoded String.
119     *
120     * @see SoundexUtils#difference(StringEncoder,String,String)
121     * @see <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp">
122     *          MS T-SQL DIFFERENCE</a>
123     *
124     * @throws EncoderException
125     *                  if an error occurs encoding one of the strings
126     * @since 1.3
127     */
128    public int difference(final String s1, final String s2) throws EncoderException {
129        return SoundexUtils.difference(this, s1, s2);
130    }
131
132    /**
133     * Encodes an Object using the refined soundex algorithm. This method is
134     * provided in order to satisfy the requirements of the Encoder interface,
135     * and will throw an EncoderException if the supplied object is not of type
136     * java.lang.String.
137     *
138     * @param obj
139     *                  Object to encode
140     * @return An object (or type java.lang.String) containing the refined
141     *             soundex code which corresponds to the String supplied.
142     * @throws EncoderException
143     *                  if the parameter supplied is not of type java.lang.String
144     */
145    @Override
146    public Object encode(final Object obj) throws EncoderException {
147        if (!(obj instanceof String)) {
148            throw new EncoderException("Parameter supplied to RefinedSoundex encode is not of type java.lang.String");
149        }
150        return soundex((String) obj);
151    }
152
153    /**
154     * Encodes a String using the refined soundex algorithm.
155     *
156     * @param str
157     *                  A String object to encode
158     * @return A Soundex code corresponding to the String supplied
159     */
160    @Override
161    public String encode(final String str) {
162        return soundex(str);
163    }
164
165    /**
166     * Returns the mapping code for a given character. The mapping codes are
167     * maintained in an internal char array named soundexMapping, and the
168     * default values of these mappings are US English.
169     *
170     * @param c
171     *                  char to get mapping for
172     * @return A character (really a numeral) to return for the given char
173     */
174    char getMappingCode(final char c) {
175        if (!Character.isLetter(c)) {
176            return 0;
177        }
178        return this.soundexMapping[Character.toUpperCase(c) - 'A'];
179    }
180
181    /**
182     * Retrieves the Refined Soundex code for a given String object.
183     *
184     * @param str
185     *                  String to encode using the Refined Soundex algorithm
186     * @return A soundex code for the String supplied
187     */
188    public String soundex(String str) {
189        if (str == null) {
190            return null;
191        }
192        str = SoundexUtils.clean(str);
193        if (str.length() == 0) {
194            return str;
195        }
196
197        final StringBuilder sBuf = new StringBuilder();
198        sBuf.append(str.charAt(0));
199
200        char last, current;
201        last = '*';
202
203        for (int i = 0; i < str.length(); i++) {
204
205            current = getMappingCode(str.charAt(i));
206            if (current == last) {
207                continue;
208            } else if (current != 0) {
209                sBuf.append(current);
210            }
211
212            last = current;
213
214        }
215
216        return sBuf.toString();
217    }
218}