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.UncheckedIOException;
022import java.io.Writer;
023import java.util.Locale;
024import java.util.Objects;
025
026/**
027 * An API for translating text.
028 * Its core use is to escape and unescape text. Because escaping and unescaping
029 * is completely contextual, the API does not present two separate signatures.
030 *
031 * @since 3.0
032 * @deprecated As of 3.6, use Apache Commons Text
033 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/translate/CharSequenceTranslator.html">
034 * CharSequenceTranslator</a> instead
035 */
036@Deprecated
037public abstract class CharSequenceTranslator {
038
039    static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
040
041    /**
042     * Translate a set of code points, represented by an int index into a CharSequence,
043     * into another set of code points. The number of code points consumed must be returned,
044     * and the only IOExceptions thrown must be from interacting with the Writer so that
045     * the top level API may reliably ignore StringWriter IOExceptions.
046     *
047     * @param input CharSequence that is being translated
048     * @param index int representing the current point of translation
049     * @param out Writer to translate the text to
050     * @return int count of code points consumed
051     * @throws IOException if and only if the Writer produces an IOException
052     */
053    public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
054
055    /**
056     * Helper for non-Writer usage.
057     * @param input CharSequence to be translated
058     * @return String output of translation
059     */
060    public final String translate(final CharSequence input) {
061        if (input == null) {
062            return null;
063        }
064        try {
065            final StringWriter writer = new StringWriter(input.length() * 2);
066            translate(input, writer);
067            return writer.toString();
068        } catch (final IOException ioe) {
069            // this should never ever happen while writing to a StringWriter
070            throw new UncheckedIOException(ioe);
071        }
072    }
073
074    /**
075     * Translate an input onto a Writer. This is intentionally final as its algorithm is
076     * tightly coupled with the abstract method of this class.
077     *
078     * @param input CharSequence that is being translated
079     * @param writer Writer to translate the text to
080     * @throws IOException if and only if the Writer produces an IOException
081     */
082    public final void translate(final CharSequence input, final Writer writer) throws IOException {
083        Objects.requireNonNull(writer, "writer");
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, writer);
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                writer.write(c1);
096                pos++;
097                if (Character.isHighSurrogate(c1) && pos < len) {
098                    final char c2 = input.charAt(pos);
099                    if (Character.isLowSurrogate(c2)) {
100                      writer.write(c2);
101                      pos++;
102                    }
103                }
104                continue;
105            }
106            // contract with translators is that they have to understand code points
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     * Returns an upper case hexadecimal {@link String} for the given
130     * character.
131     *
132     * @param codePoint The code point to convert.
133     * @return An upper case hexadecimal {@link String}
134     */
135    public static String hex(final int codePoint) {
136        return Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH);
137    }
138
139}