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