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 */
017package org.apache.commons.lang3.text.translate;
018
019import java.io.IOException;
020import java.io.StringWriter;
021import java.io.Writer;
022import 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 * @deprecated as of 3.6, use commons-text
031 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/translate/CharSequenceTranslator.html">
032 * CharSequenceTranslator</a> instead
033 */
034@Deprecated
035public abstract class CharSequenceTranslator {
036
037    static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
038
039    /**
040     * Translate a set of codepoints, represented by an int index into a CharSequence,
041     * into another set of codepoints. The number of codepoints consumed must be returned,
042     * and the only IOExceptions thrown must be from interacting with the Writer so that
043     * the top level API may reliably ignore StringWriter IOExceptions.
044     *
045     * @param input CharSequence that is being translated
046     * @param index int representing the current point of translation
047     * @param out Writer to translate the text to
048     * @return int count of codepoints consumed
049     * @throws IOException if and only if the Writer produces an IOException
050     */
051    public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
052
053    /**
054     * Helper for non-Writer usage.
055     * @param input CharSequence to be translated
056     * @return String output of translation
057     */
058    public final String translate(final CharSequence input) {
059        if (input == null) {
060            return null;
061        }
062        try {
063            final StringWriter writer = new StringWriter(input.length() * 2);
064            translate(input, writer);
065            return writer.toString();
066        } catch (final IOException ioe) {
067            // this should never ever happen while writing to a StringWriter
068            throw new RuntimeException(ioe);
069        }
070    }
071
072    /**
073     * Translate an input onto a Writer. This is intentionally final as its algorithm is
074     * tightly coupled with the abstract method of this class.
075     *
076     * @param input CharSequence that is being translated
077     * @param out Writer to translate the text to
078     * @throws IOException if and only if the Writer produces an IOException
079     */
080    public final void translate(final CharSequence input, final Writer out) throws IOException {
081        if (out == null) {
082            throw new IllegalArgumentException("The Writer must not be null");
083        }
084        if (input == null) {
085            return;
086        }
087        int pos = 0;
088        final int len = input.length();
089        while (pos < len) {
090            final int consumed = translate(input, pos, out);
091            if (consumed == 0) {
092                // inlined implementation of Character.toChars(Character.codePointAt(input, pos))
093                // avoids allocating temp char arrays and duplicate checks
094                final char c1 = input.charAt(pos);
095                out.write(c1);
096                pos++;
097                if (Character.isHighSurrogate(c1) && pos < len) {
098                    final char c2 = input.charAt(pos);
099                    if (Character.isLowSurrogate(c2)) {
100                      out.write(c2);
101                      pos++;
102                    }
103                }
104                continue;
105            }
106            // contract with translators is that they have to understand codepoints
107            // and they just took care of a surrogate pair
108            for (int pt = 0; pt < consumed; pt++) {
109                pos += Character.charCount(Character.codePointAt(input, pos));
110            }
111        }
112    }
113
114    /**
115     * Helper method to create a merger of this translator with another set of
116     * translators. Useful in customizing the standard functionality.
117     *
118     * @param translators CharSequenceTranslator array of translators to merge with this one
119     * @return CharSequenceTranslator merging this translator with the others
120     */
121    public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
122        final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
123        newArray[0] = this;
124        System.arraycopy(translators, 0, newArray, 1, translators.length);
125        return new AggregateTranslator(newArray);
126    }
127
128    /**
129     * <p>Returns an upper case hexadecimal <code>String</code> for the given
130     * character.</p>
131     *
132     * @param codepoint The codepoint to convert.
133     * @return An upper case hexadecimal <code>String</code>
134     */
135    public static String hex(final int codepoint) {
136        return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
137    }
138
139}