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