    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     * Constructs a new instance.
    056     */
    057    public CharSequenceTranslator() {
    058        // empty
    059    }
    060
    061    /**
    062     * Helper for non-Writer usage.
    063     * @param input CharSequence to be translated
    064     * @return String output of translation
    065     */
    066    public final String translate(final CharSequence input) {
    067        if (input == null) {
    068            return null;
    069        }
    070        try {
    071            final StringWriter writer = new StringWriter(input.length() * 2);
    072            translate(input, writer);
    073            return writer.toString();
    074        } catch (final IOException ioe) {
    075            // this should never ever happen while writing to a StringWriter
    076            throw new UncheckedIOException(ioe);
    077        }
    078    }
    079
    080    /**
    081     * Translate a set of code points, represented by an int index into a CharSequence,
    082     * into another set of code points. The number of code points consumed must be returned,
    083     * and the only IOExceptions thrown must be from interacting with the Writer so that
    084     * the top level API may reliably ignore StringWriter IOExceptions.
    085     *
    086     * @param input CharSequence that is being translated
    087     * @param index int representing the current point of translation
    088     * @param out Writer to translate the text to
    089     * @return int count of code points consumed
    090     * @throws IOException if and only if the Writer produces an IOException
    091     */
    092    public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
    093
    094    /**
    095     * Translate an input onto a Writer. This is intentionally final as its algorithm is
    096     * tightly coupled with the abstract method of this class.
    097     *
    098     * @param input CharSequence that is being translated
    099     * @param writer Writer to translate the text to
    100     * @throws IOException if and only if the Writer produces an IOException
    101     */
    102    @SuppressWarnings("resource") // Caller closes writer
    103    public final void translate(final CharSequence input, final Writer writer) throws IOException {
    104        Objects.requireNonNull(writer, "writer");
    105        if (input == null) {
    106            return;
    107        }
    108        int pos = 0;
    109        final int len = input.length();
    110        while (pos < len) {
    111            final int consumed = translate(input, pos, writer);
    112            if (consumed == 0) {
    113                // inlined implementation of Character.toChars(Character.codePointAt(input, pos))
    114                // avoids allocating temp char arrays and duplicate checks
    115                final char c1 = input.charAt(pos);
    116                writer.write(c1);
    117                pos++;
    118                if (Character.isHighSurrogate(c1) && pos < len) {
    119                    final char c2 = input.charAt(pos);
    120                    if (Character.isLowSurrogate(c2)) {
    121                      writer.write(c2);
    122                      pos++;
    123                    }
    124                }
    125                continue;
    126            }
    127            // contract with translators is that they have to understand code points
    128            // and they just took care of a surrogate pair
    129            for (int pt = 0; pt < consumed; pt++) {
    130                pos += Character.charCount(Character.codePointAt(input, pos));
    131            }
    132        }
    133    }
    134
    135    /**
    136     * Helper method to create a merger of this translator with another set of
    137     * translators. Useful in customizing the standard functionality.
    138     *
    139     * @param translators CharSequenceTranslator array of translators to merge with this one
    140     * @return CharSequenceTranslator merging this translator with the others
    141     */
    142    public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
    143        final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
    144        newArray[0] = this;
    145        return new AggregateTranslator(ArrayUtils.arraycopy(translators, 0, newArray, 1, translators.length));
    146    }
    147
    148}