View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.text.translate;
18  
19  import java.io.IOException;
20  import java.io.StringWriter;
21  import java.io.UncheckedIOException;
22  import java.io.Writer;
23  import java.util.Locale;
24  import java.util.Objects;
25  
26  import org.apache.commons.lang3.ArrayUtils;
27  
28  /**
29   * An API for translating text.
30   * Its core use is to escape and unescape text. Because escaping and unescaping
31   * is completely contextual, the API does not present two separate signatures.
32   *
33   * @since 3.0
34   * @deprecated As of <a href="https://commons.apache.org/proper/commons-lang/changes-report.html#a3.6">3.6</a>, use Apache Commons Text
35   * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/translate/CharSequenceTranslator.html">
36   * CharSequenceTranslator</a>.
37   */
38  @Deprecated
39  public abstract class CharSequenceTranslator {
40  
41      static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
42  
43      /**
44       * Returns an upper case hexadecimal {@link String} for the given
45       * character.
46       *
47       * @param codePoint The code point to convert.
48       * @return An upper case hexadecimal {@link String}.
49       */
50      public static String hex(final int codePoint) {
51          return Integer.toHexString(codePoint).toUpperCase(Locale.ENGLISH);
52      }
53  
54      /**
55       * Constructs a new instance.
56       */
57      public CharSequenceTranslator() {
58          // empty
59      }
60  
61      /**
62       * Helper for non-Writer usage.
63       *
64       * @param input CharSequence to be translated.
65       * @return String output of translation.
66       */
67      public final String translate(final CharSequence input) {
68          if (input == null) {
69              return null;
70          }
71          try {
72              final StringWriter writer = new StringWriter(input.length() * 2);
73              translate(input, writer);
74              return writer.toString();
75          } catch (final IOException ioe) {
76              // this should never ever happen while writing to a StringWriter
77              throw new UncheckedIOException(ioe);
78          }
79      }
80  
81      /**
82       * Translate a set of code points, represented by an int index into a CharSequence,
83       * into another set of code points. The number of code points consumed must be returned,
84       * and the only IOExceptions thrown must be from interacting with the Writer so that
85       * the top level API may reliably ignore StringWriter IOExceptions.
86       *
87       * @param input CharSequence that is being translated.
88       * @param index int representing the current point of translation.
89       * @param out Writer to translate the text to.
90       * @return int count of code points consumed.
91       * @throws IOException if and only if the Writer produces an IOException.
92       */
93      public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
94  
95      /**
96       * Translate an input onto a Writer. This is intentionally final as its algorithm is
97       * tightly coupled with the abstract method of this class.
98       *
99       * @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 }