View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.codec.language;
19  
20  import java.util.Arrays;
21  import java.util.Locale;
22  
23  import org.apache.commons.codec.EncoderException;
24  import org.apache.commons.codec.StringEncoder;
25  
26  /**
27   * Encodes a string into a Cologne Phonetic value.
28   * <p>
29   * Implements the <a href="https://de.wikipedia.org/wiki/K%C3%B6lner_Phonetik">K&ouml;lner Phonetik</a> (Cologne
30   * Phonetic) algorithm issued by Hans Joachim Postel in 1969.
31   * </p>
32   * <p>
33   * The <i>K&ouml;lner Phonetik</i> is a phonetic algorithm which is optimized for the German language. It is related to
34   * the well-known soundex algorithm.
35   * </p>
36   *
37   * <h2>Algorithm</h2>
38   *
39   * <ul>
40   *
41   * <li>
42   * <h3>Step 1:</h3>
43   * After preprocessing (conversion to upper case, transcription of <a
44   * href="https://en.wikipedia.org/wiki/Germanic_umlaut">germanic umlauts</a>, removal of non alphabetical characters) the
45   * letters of the supplied text are replaced by their phonetic code according to the following table.
46   * <table border="1">
47   * <caption style="caption-side: bottom"><small><i>(Source: <a
48   * href="https://de.wikipedia.org/wiki/K%C3%B6lner_Phonetik#Buchstabencodes">Wikipedia (de): K&ouml;lner Phonetik --
49   * Buchstabencodes</a>)</i></small></caption> <tbody>
50   * <tr>
51   * <th>Letter</th>
52   * <th>Context</th>
53   * <th>Code</th>
54   * </tr>
55   * <tr>
56   * <td>A, E, I, J, O, U, Y</td>
57   * <td></td>
58   * <td>0</td>
59   * </tr>
60   * <tr>
61   *
62   * <td>H</td>
63   * <td></td>
64   * <td>-</td>
65   * </tr>
66   * <tr>
67   * <td>B</td>
68   * <td></td>
69   * <td rowspan="2">1</td>
70   * </tr>
71   * <tr>
72   * <td>P</td>
73   * <td>not before H</td>
74   *
75   * </tr>
76   * <tr>
77   * <td>D, T</td>
78   * <td>not before C, S, Z</td>
79   * <td>2</td>
80   * </tr>
81   * <tr>
82   * <td>F, V, W</td>
83   * <td></td>
84   * <td rowspan="2">3</td>
85   * </tr>
86   * <tr>
87   *
88   * <td>P</td>
89   * <td>before H</td>
90   * </tr>
91   * <tr>
92   * <td>G, K, Q</td>
93   * <td></td>
94   * <td rowspan="3">4</td>
95   * </tr>
96   * <tr>
97   * <td rowspan="2">C</td>
98   * <td>at onset before A, H, K, L, O, Q, R, U, X</td>
99   *
100  * </tr>
101  * <tr>
102  * <td>before A, H, K, O, Q, U, X except after S, Z</td>
103  * </tr>
104  * <tr>
105  * <td>X</td>
106  * <td>not after C, K, Q</td>
107  * <td>48</td>
108  * </tr>
109  * <tr>
110  * <td>L</td>
111  * <td></td>
112  *
113  * <td>5</td>
114  * </tr>
115  * <tr>
116  * <td>M, N</td>
117  * <td></td>
118  * <td>6</td>
119  * </tr>
120  * <tr>
121  * <td>R</td>
122  * <td></td>
123  * <td>7</td>
124  * </tr>
125  *
126  * <tr>
127  * <td>S, Z</td>
128  * <td></td>
129  * <td rowspan="6">8</td>
130  * </tr>
131  * <tr>
132  * <td rowspan="3">C</td>
133  * <td>after S, Z</td>
134  * </tr>
135  * <tr>
136  * <td>at onset except before A, H, K, L, O, Q, R, U, X</td>
137  * </tr>
138  *
139  * <tr>
140  * <td>not before A, H, K, O, Q, U, X</td>
141  * </tr>
142  * <tr>
143  * <td>D, T</td>
144  * <td>before C, S, Z</td>
145  * </tr>
146  * <tr>
147  * <td>X</td>
148  * <td>after C, K, Q</td>
149  * </tr>
150  * </tbody>
151  * </table>
152  *
153  * <h4>Example:</h4>
154  *
155  * {@code "M}&uuml;{@code ller-L}&uuml;<code>denscheidt"
156  * =&gt; "MULLERLUDENSCHEIDT" =&gt; "6005507500206880022"</code>
157  *
158  * </li>
159  *
160  * <li>
161  * <h3>Step 2:</h3>
162  * Collapse of all multiple consecutive code digits.
163  * <h4>Example:</h4>
164  * {@code "6005507500206880022" =&gt; "6050750206802"}</li>
165  *
166  * <li>
167  * <h3>Step 3:</h3>
168  * Removal of all codes "0" except at the beginning. This means that two or more identical consecutive digits can occur
169  * if they occur after removing the "0" digits.
170  *
171  * <h4>Example:</h4>
172  * {@code "6050750206802" =&gt; "65752682"}</li>
173  *
174  * </ul>
175  *
176  * <p>
177  * This class is thread-safe.
178  * </p>
179  *
180  * @see <a href="https://de.wikipedia.org/wiki/K%C3%B6lner_Phonetik">Wikipedia (de): K&ouml;lner Phonetik (in German)</a>
181  * @since 1.5
182  */
183 public class ColognePhonetic implements StringEncoder {
184 
185     /**
186      * This class is not thread-safe; the field {@link #length} is mutable.
187      * However, it is not shared between threads, as it is constructed on demand
188      * by the method {@link ColognePhonetic#colognePhonetic(String)}
189      */
190     abstract static class CologneBuffer {
191 
192         protected final char[] data;
193 
194         protected int length;
195 
196         public CologneBuffer(final char[] data) {
197             this.data = data;
198             this.length = data.length;
199         }
200 
201         public CologneBuffer(final int buffSize) {
202             this.data = new char[buffSize];
203             this.length = 0;
204         }
205 
206         protected abstract char[] copyData(int start, int length);
207 
208         public boolean isEmpty() {
209             return length() == 0;
210         }
211 
212         public int length() {
213             return length;
214         }
215 
216         @Override
217         public String toString() {
218             return new String(copyData(0, length));
219         }
220     }
221     private final class CologneInputBuffer extends CologneBuffer {
222 
223         public CologneInputBuffer(final char[] data) {
224             super(data);
225         }
226 
227         @Override
228         protected char[] copyData(final int start, final int length) {
229             final char[] newData = new char[length];
230             System.arraycopy(data, data.length - this.length + start, newData, 0, length);
231             return newData;
232         }
233 
234         public char getNextChar() {
235             return data[getNextPos()];
236         }
237 
238         protected int getNextPos() {
239             return data.length - length;
240         }
241 
242         public char removeNext() {
243             final char ch = getNextChar();
244             length--;
245             return ch;
246         }
247     }
248     private final class CologneOutputBuffer extends CologneBuffer {
249 
250         private char lastCode;
251 
252         public CologneOutputBuffer(final int buffSize) {
253             super(buffSize);
254             lastCode = '/'; // impossible value
255         }
256 
257         @Override
258         protected char[] copyData(final int start, final int length) {
259             return Arrays.copyOfRange(data, start, length);
260         }
261 
262         /**
263          * Stores the next code in the output buffer, keeping track of the previous code.
264          * '0' is only stored if it is the first entry.
265          * Ignored chars are never stored.
266          * If the code is the same as the last code (whether stored or not) it is not stored.
267          *
268          * @param code the code to store.
269          */
270         public void put(final char code) {
271             if (code != CHAR_IGNORE && lastCode != code && (code != '0' || length == 0)) {
272                 data[length] = code;
273                 length++;
274             }
275             lastCode = code;
276         }
277     }
278     // Predefined char arrays for better performance and less GC load
279     private static final char[] AEIJOUY = { 'A', 'E', 'I', 'J', 'O', 'U', 'Y' };
280     private static final char[] CSZ = { 'C', 'S', 'Z' };
281     private static final char[] FPVW = { 'F', 'P', 'V', 'W' };
282     private static final char[] GKQ = { 'G', 'K', 'Q' };
283     private static final char[] CKQ = { 'C', 'K', 'Q' };
284     private static final char[] AHKLOQRUX = { 'A', 'H', 'K', 'L', 'O', 'Q', 'R', 'U', 'X' };
285 
286     private static final char[] SZ = { 'S', 'Z' };
287 
288     private static final char[] AHKOQUX = { 'A', 'H', 'K', 'O', 'Q', 'U', 'X' };
289 
290     private static final char[] DTX = { 'D', 'T', 'X' };
291 
292     private static final char CHAR_IGNORE = '-';    // is this character to be ignored?
293 
294     /*
295      * Returns whether the array contains the key, or not.
296      */
297     private static boolean arrayContains(final char[] arr, final char key) {
298         for (final char element : arr) {
299             if (element == key) {
300                 return true;
301             }
302         }
303         return false;
304     }
305 
306     /**
307      * <p>
308      * Implements the <i>K&ouml;lner Phonetik</i> algorithm.
309      * </p>
310      * <p>
311      * In contrast to the initial description of the algorithm, this implementation does the encoding in one pass.
312      * </p>
313      *
314      * @param text The source text to encode
315      * @return the corresponding encoding according to the <i>K&ouml;lner Phonetik</i> algorithm
316      */
317     public String colognePhonetic(final String text) {
318         if (text == null) {
319             return null;
320         }
321 
322         final CologneInputBuffer input = new CologneInputBuffer(preprocess(text));
323         final CologneOutputBuffer output = new CologneOutputBuffer(input.length() * 2);
324 
325         char nextChar;
326 
327         char lastChar = CHAR_IGNORE;
328         char chr;
329 
330         while (!input.isEmpty()) {
331             chr = input.removeNext();
332 
333             if (!input.isEmpty()) {
334                 nextChar = input.getNextChar();
335             } else {
336                 nextChar = CHAR_IGNORE;
337             }
338 
339             if (chr < 'A' || chr > 'Z') {
340                     continue; // ignore unwanted characters
341             }
342 
343             if (arrayContains(AEIJOUY, chr)) {
344                 output.put('0');
345             } else if (chr == 'B' || chr == 'P' && nextChar != 'H') {
346                 output.put('1');
347             } else if ((chr == 'D' || chr == 'T') && !arrayContains(CSZ, nextChar)) {
348                 output.put('2');
349             } else if (arrayContains(FPVW, chr)) {
350                 output.put('3');
351             } else if (arrayContains(GKQ, chr)) {
352                 output.put('4');
353             } else if (chr == 'X' && !arrayContains(CKQ, lastChar)) {
354                 output.put('4');
355                 output.put('8');
356             } else if (chr == 'S' || chr == 'Z') {
357                 output.put('8');
358             } else if (chr == 'C') {
359                 if (output.isEmpty()) {
360                     if (arrayContains(AHKLOQRUX, nextChar)) {
361                         output.put('4');
362                     } else {
363                         output.put('8');
364                     }
365                 } else if (arrayContains(SZ, lastChar) || !arrayContains(AHKOQUX, nextChar)) {
366                     output.put('8');
367                 } else {
368                     output.put('4');
369                 }
370             } else if (arrayContains(DTX, chr)) {
371                 output.put('8');
372             } else {
373                 switch (chr) {
374                 case 'R':
375                     output.put('7');
376                     break;
377                 case 'L':
378                     output.put('5');
379                     break;
380                 case 'M':
381                 case 'N':
382                     output.put('6');
383                     break;
384                 case 'H':
385                     output.put(CHAR_IGNORE); // needed by put
386                     break;
387                 default:
388                     break;
389                 }
390             }
391 
392             lastChar = chr;
393         }
394         return output.toString();
395     }
396 
397     @Override
398     public Object encode(final Object object) throws EncoderException {
399         if (!(object instanceof String)) {
400             throw new EncoderException("This method's parameter was expected to be of the type " +
401                 String.class.getName() +
402                 ". But actually it was of the type " +
403                 object.getClass().getName() +
404                 ".");
405         }
406         return encode((String) object);
407     }
408 
409     @Override
410     public String encode(final String text) {
411         return colognePhonetic(text);
412     }
413 
414     /**
415      * Compares the first encoded string to the second encoded string.
416      *
417      * @param text1 source text to encode before testing for equality.
418      * @param text2 source text to encode before testing for equality.
419      * @return {@code true} if the encoding the first string equals the encoding of the second string, {@code false}
420      *         otherwise
421      */
422     public boolean isEncodeEqual(final String text1, final String text2) {
423         return colognePhonetic(text1).equals(colognePhonetic(text2));
424     }
425 
426     /**
427      * Converts the string to upper case and replaces Germanic umlaut characters
428      * The following characters are mapped:
429      * <ul>
430      * <li>capital A, umlaut mark</li>
431      * <li>capital U, umlaut mark</li>
432      * <li>capital O, umlaut mark</li>
433      * <li>small sharp s, German</li>
434      * </ul>
435      */
436     private char[] preprocess(final String text) {
437         // This converts German small sharp s (Eszett) to SS
438         final char[] chrs = text.toUpperCase(Locale.GERMAN).toCharArray();
439 
440         for (int index = 0; index < chrs.length; index++) {
441             switch (chrs[index]) {
442                 case '\u00C4': // capital A, umlaut mark
443                     chrs[index] = 'A';
444                     break;
445                 case '\u00DC': // capital U, umlaut mark
446                     chrs[index] = 'U';
447                     break;
448                 case '\u00D6': // capital O, umlaut mark
449                     chrs[index] = 'O';
450                     break;
451                 default:
452                     break;
453             }
454         }
455         return chrs;
456     }
457 }