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