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    *      http://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.text.translate;
18  
19  import java.io.IOException;
20  import java.io.StringWriter;
21  import java.io.Writer;
22  import java.util.Locale;
23  
24  /**
25   * An API for translating text. 
26   * Its core use is to escape and unescape text. Because escaping and unescaping 
27   * is completely contextual, the API does not present two separate signatures.
28   *
29   * @since 1.0
30   */
31  public abstract class CharSequenceTranslator {
32  
33      static final char[] HEX_DIGITS = new char[] {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
34  
35      /**
36       * Translate a set of codepoints, represented by an int index into a CharSequence, 
37       * into another set of codepoints. The number of codepoints consumed must be returned, 
38       * and the only IOExceptions thrown must be from interacting with the Writer so that 
39       * the top level API may reliably ignore StringWriter IOExceptions. 
40       *
41       * @param input CharSequence that is being translated
42       * @param index int representing the current point of translation
43       * @param out Writer to translate the text to
44       * @return int count of codepoints consumed
45       * @throws IOException if and only if the Writer produces an IOException
46       */
47      public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
48  
49      /**
50       * Helper for non-Writer usage. 
51       * @param input CharSequence to be translated
52       * @return String output of translation
53       */
54      public final String translate(final CharSequence input) {
55          if (input == null) {
56              return null;
57          }
58          try {
59              final StringWriter writer = new StringWriter(input.length() * 2);
60              translate(input, writer);
61              return writer.toString();
62          } catch (final IOException ioe) {
63              // this should never ever happen while writing to a StringWriter
64              throw new RuntimeException(ioe);
65          }
66      }
67  
68      /**
69       * Translate an input onto a Writer. This is intentionally final as its algorithm is 
70       * tightly coupled with the abstract method of this class. 
71       *
72       * @param input CharSequence that is being translated
73       * @param out Writer to translate the text to
74       * @throws IOException if and only if the Writer produces an IOException
75       */
76      public final void translate(final CharSequence input, final Writer out) throws IOException {
77          if (out == null) {
78              throw new IllegalArgumentException("The Writer must not be null");
79          }
80          if (input == null) {
81              return;
82          }
83          int pos = 0;
84          final int len = input.length();
85          while (pos < len) {
86              final int consumed = translate(input, pos, out);
87              if (consumed == 0) {
88                  // inlined implementation of Character.toChars(Character.codePointAt(input, pos))
89                  // avoids allocating temp char arrays and duplicate checks
90                  final char c1 = input.charAt(pos);
91                  out.write(c1);
92                  pos++;
93                  if (Character.isHighSurrogate(c1) && pos < len) {
94                      final char c2 = input.charAt(pos);
95                      if (Character.isLowSurrogate(c2)) {
96                        out.write(c2);
97                        pos++;
98                      }
99                  }
100                 continue;
101             }
102             // contract with translators is that they have to understand codepoints
103             // and they just took care of a surrogate pair
104             for (int pt = 0; pt < consumed; pt++) {
105                 pos += Character.charCount(Character.codePointAt(input, pos));
106             }
107         }
108     }
109 
110     /**
111      * Helper method to create a merger of this translator with another set of 
112      * translators. Useful in customizing the standard functionality.
113      *
114      * @param translators CharSequenceTranslator array of translators to merge with this one
115      * @return CharSequenceTranslator merging this translator with the others
116      */
117     public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
118         final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
119         newArray[0] = this;
120         System.arraycopy(translators, 0, newArray, 1, translators.length);
121         return new AggregateTranslator(newArray);
122     }
123 
124     /**
125      * <p>Returns an upper case hexadecimal <code>String</code> for the given
126      * character.</p>
127      *
128      * @param codepoint The codepoint to convert.
129      * @return An upper case hexadecimal <code>String</code>
130      */
131     public static String hex(final int codepoint) {
132         return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
133     }
134 
135 }