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