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    package org.apache.commons.lang3.text.translate;
018    
019    import java.io.IOException;
020    import java.io.StringWriter;
021    import java.io.Writer;
022    import java.util.Locale;
023    
024    /**
025     * An API for translating text. 
026     * Its core use is to escape and unescape text. Because escaping and unescaping 
027     * is completely contextual, the API does not present two separate signatures.
028     * 
029     * @since 3.0
030     * @version $Id: CharSequenceTranslator.java 1139924 2011-06-26 19:32:14Z mbenson $
031     */
032    public abstract class CharSequenceTranslator {
033    
034        /**
035         * Translate a set of codepoints, represented by an int index into a CharSequence, 
036         * into another set of codepoints. The number of codepoints consumed must be returned, 
037         * and the only IOExceptions thrown must be from interacting with the Writer so that 
038         * the top level API may reliable ignore StringWriter IOExceptions. 
039         *
040         * @param input CharSequence that is being translated
041         * @param index int representing the current point of translation
042         * @param out Writer to translate the text to
043         * @return int count of codepoints consumed
044         * @throws IOException if and only if the Writer produces an IOException
045         */
046        public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
047    
048        /**
049         * Helper for non-Writer usage. 
050         * @param input CharSequence to be translated
051         * @return String output of translation
052         */
053        public final String translate(CharSequence input) {
054            if (input == null) {
055                return null;
056            }
057            try {
058                StringWriter writer = new StringWriter(input.length() * 2);
059                translate(input, writer);
060                return writer.toString();
061            } catch (IOException ioe) {
062                // this should never ever happen while writing to a StringWriter
063                throw new RuntimeException(ioe);
064            }
065        }
066    
067        /**
068         * Translate an input onto a Writer. This is intentionally final as its algorithm is 
069         * tightly coupled with the abstract method of this class. 
070         *
071         * @param input CharSequence that is being translated
072         * @param out Writer to translate the text to
073         * @throws IOException if and only if the Writer produces an IOException
074         */
075        public final void translate(CharSequence input, Writer out) throws IOException {
076            if (out == null) {
077                throw new IllegalArgumentException("The Writer must not be null");
078            }
079            if (input == null) {
080                return;
081            }
082            int sz = Character.codePointCount(input, 0, input.length());
083            for (int i = 0; i < sz; i++) {
084    
085                // consumed is the number of codepoints consumed
086                int consumed = translate(input, i, out);
087    
088                if (consumed == 0) {
089                    out.write(Character.toChars(Character.codePointAt(input, i)));
090                } else {
091                    // contract with translators is that they have to understand codepoints 
092                    // and they just took care of a surrogate pair
093                    for (int j = 0; j < consumed; j++) {
094                        if (i < sz - 2) {
095                            i += Character.charCount(Character.codePointAt(input, i));
096                        } else {
097                            // If the String ends with a high surrogate, just add the 1 and don't worry about such things
098                            i++;
099                        }
100                    }
101                    // for loop will increment 1 anyway, so remove 1 to account for that
102                    i--;
103                }
104            }
105        }
106    
107        /**
108         * Helper method to create a merger of this translator with another set of 
109         * translators. Useful in customizing the standard functionality.
110         *
111         * @param translators CharSequenceTranslator array of translators to merge with this one
112         * @return CharSequenceTranslator merging this translator with the others
113         */
114        public final CharSequenceTranslator with(CharSequenceTranslator... translators) {
115            CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
116            newArray[0] = this;
117            System.arraycopy(translators, 0, newArray, 1, translators.length);
118            return new AggregateTranslator(newArray);
119        }
120    
121        /**
122         * <p>Returns an upper case hexadecimal <code>String</code> for the given
123         * character.</p>
124         *
125         * @param codepoint The codepoint to convert.
126         * @return An upper case hexadecimal <code>String</code>
127         */
128        public static String hex(int codepoint) {
129            return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
130        }
131    
132    }