    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 *      https://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>
    029 * This class is immutable and thread-safe.
    030 * </p>
    031 */
    032public class RefinedSoundex implements StringEncoder {
    033
    034    /**
    035     * Mapping:
    036     * <pre>
    037     * 0: A E I O U Y H W
    038     * 1: B P
    039     * 2: F V
    040     * 3: C K S
    041     * 4: G J
    042     * 5: Q X Z
    043     * 6: D T
    044     * 7: L
    045     * 8: M N
    046     * 9: R
    047     * </pre>
    048     *
    049     * @since 1.4
    050     */
    051    //                                                      ABCDEFGHIJKLMNOPQRSTUVWXYZ
    052    public static final String US_ENGLISH_MAPPING_STRING = "01360240043788015936020505";
    053
    054   /**
    055     * RefinedSoundex is *refined* for a number of reasons one being that the
    056     * mappings have been altered. This implementation contains default
    057     * mappings for US English.
    058     */
    059    private static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray();
    060
    061    /**
    062     * This static variable contains an instance of the RefinedSoundex using
    063     * the US_ENGLISH mapping.
    064     */
    065    public static final RefinedSoundex US_ENGLISH = new RefinedSoundex();
    066
    067    /**
    068     * Every letter of the alphabet is "mapped" to a numerical value. This char
    069     * array holds the values to which each letter is mapped. This
    070     * implementation contains a default map for US_ENGLISH.
    071     */
    072    private final char[] soundexMapping;
    073
    074     /**
    075     * Creates an instance of the RefinedSoundex object using the default US
    076     * English mapping.
    077     */
    078    public RefinedSoundex() {
    079        this.soundexMapping = US_ENGLISH_MAPPING;
    080    }
    081
    082    /**
    083     * Creates a refined Soundex instance using a custom mapping. This
    084     * constructor can be used to customize the mapping, and/or possibly
    085     * provide an internationalized mapping for a non-Western character set.
    086     *
    087     * @param mapping
    088     *                  Mapping array to use when finding the corresponding code for
    089     *                  a given character.
    090     */
    091    public RefinedSoundex(final char[] mapping) {
    092        this.soundexMapping = mapping.clone();
    093    }
    094
    095    /**
    096     * Creates a refined Soundex instance using a custom mapping. This constructor can be used to customize the mapping,
    097     * and/or possibly provide an internationalized mapping for a non-Western character set.
    098     *
    099     * @param mapping
    100     *            Mapping string to use when finding the corresponding code for a given character.
    101     * @since 1.4
    102     */
    103    public RefinedSoundex(final String mapping) {
    104        this.soundexMapping = mapping.toCharArray();
    105    }
    106
    107    /**
    108     * Returns the number of characters in the two encoded Strings that are the
    109     * same. This return value ranges from 0 to the length of the shortest
    110     * encoded String: 0 indicates little or no similarity, and 4 out of 4 (for
    111     * example) indicates strong similarity or identical values. For refined
    112     * Soundex, the return value can be greater than 4.
    113     *
    114     * @param s1
    115     *                  A String that will be encoded and compared.
    116     * @param s2
    117     *                  A String that will be encoded and compared.
    118     * @return The number of characters in the two encoded Strings that are the
    119     *             same from 0 to the length of the shortest encoded String.
    120     *
    121     * @see SoundexUtils#difference(StringEncoder,String,String)
    122     * @see <a href="https://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_de-dz_8co5.asp">
    123     *          MS T-SQL DIFFERENCE</a>
    124     *
    125     * @throws EncoderException
    126     *                  if an error occurs encoding one of the strings.
    127     * @since 1.3
    128     */
    129    public int difference(final String s1, final String s2) throws EncoderException {
    130        return SoundexUtils.difference(this, s1, s2);
    131    }
    132
    133    /**
    134     * Encodes an Object using the refined Soundex algorithm. This method is
    135     * provided in order to satisfy the requirements of the Encoder interface,
    136     * and will throw an EncoderException if the supplied object is not of type
    137     * {@link String}.
    138     *
    139     * @param obj
    140     *                  Object to encode.
    141     * @return An object (or type {@link String}) containing the refined.
    142     *             Soundex code which corresponds to the String supplied.
    143     * @throws EncoderException
    144     *                  if the parameter supplied is not of type {@link String}.
    145     */
    146    @Override
    147    public Object encode(final Object obj) throws EncoderException {
    148        if (!(obj instanceof String)) {
    149            throw new EncoderException("Parameter supplied to RefinedSoundex encode is not of type java.lang.String");
    150        }
    151        return soundex((String) obj);
    152    }
    153
    154    /**
    155     * Encodes a String using the refined Soundex algorithm.
    156     *
    157     * @param str
    158     *                  A String object to encode.
    159     * @return A Soundex code corresponding to the String supplied.
    160     */
    161    @Override
    162    public String encode(final String str) {
    163        return soundex(str);
    164    }
    165
    166    /**
    167     * Returns the mapping code for a given character. The mapping codes are
    168     * maintained in an internal char array named soundexMapping, and the
    169     * default values of these mappings are US English.
    170     *
    171     * @param c
    172     *                  char to get mapping for.
    173     * @return A character (really a numeral) to return for the given char.
    174     */
    175    char getMappingCode(final char c) {
    176        if (!Character.isLetter(c)) {
    177            return 0;
    178        }
    179        final int index = Character.toUpperCase(c) - 'A';
    180        if (index < 0 || index >= this.soundexMapping.length) {
    181            return 0;
    182        }
    183        return this.soundexMapping[index];
    184    }
    185
    186    /**
    187     * Retrieves the Refined Soundex code for a given String object.
    188     *
    189     * @param str
    190     *                  String to encode using the Refined Soundex algorithm.
    191     * @return A Soundex code for the String supplied.
    192     */
    193    public String soundex(String str) {
    194        if (str == null) {
    195            return null;
    196        }
    197        str = SoundexUtils.clean(str);
    198        if (str.isEmpty()) {
    199            return str;
    200        }
    201
    202        final StringBuilder sBuf = new StringBuilder();
    203        sBuf.append(str.charAt(0));
    204
    205        char last, current;
    206        last = '*';
    207
    208        for (int i = 0; i < str.length(); i++) {
    209
    210            current = getMappingCode(str.charAt(i));
    211            if (current == last) {
    212                continue;
    213            }
    214            if (current != 0) {
    215                sBuf.append(current);
    216            }
    217
    218            last = current;
    219
    220        }
    221
    222        return sBuf.toString();
    223    }
    224}