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.Writer;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.EnumSet;
24
25 import org.apache.commons.lang3.ArrayUtils;
26
27 /**
28 * Translates XML numeric entities of the form &#[xX]?\d+;? to
29 * the specific code point.
30 *
31 * Note that the semicolon is optional.
32 *
33 * @since 1.0
34 */
35 public class NumericEntityUnescaper extends CharSequenceTranslator {
36
37 /** Enumerates NumericEntityUnescaper options for unescaping. */
38 public enum OPTION {
39
40 /**
41 * Requires a semicolon.
42 */
43 semiColonRequired,
44
45 /**
46 * Does not require a semicolon.
47 */
48 semiColonOptional,
49
50 /**
51 * Throws an exception if a semicolon is missing.
52 */
53 errorIfNoSemiColon
54 }
55
56 /** Default options. */
57 private static final EnumSet<OPTION> DEFAULT_OPTIONS = EnumSet
58 .copyOf(Collections.singletonList(OPTION.semiColonRequired));
59
60 /** EnumSet of OPTIONS, given from the constructor, read-only. */
61 private final EnumSet<OPTION> options;
62
63 /**
64 * Creates a UnicodeUnescaper.
65 *
66 * The constructor takes a list of options, only one type of which is currently available (whether to allow, error or ignore the semicolon on the end of a
67 * numeric entity to being missing).
68 * <p>
69 * For example, to support numeric entities without a ';':
70 * </p>
71 *
72 * <pre>
73 * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional)
74 * </pre>
75 * <p>
76 * and to throw an IllegalArgumentException when they're missing:
77 * </p>
78 *
79 * <pre>
80 * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon)
81 * </pre>
82 * <p>
83 * Note that the default behavior is to ignore them.
84 * </p>
85 *
86 * @param options to apply to this unescaper
87 */
88 public NumericEntityUnescaper(final OPTION... options) {
89 this.options = ArrayUtils.isEmpty(options) ? DEFAULT_OPTIONS : EnumSet.copyOf(Arrays.asList(options));
90 }
91
92 /**
93 * Tests whether the passed in option is currently set.
94 *
95 * @param option to check state of.
96 * @return whether the option is set.
97 */
98 public boolean isSet(final OPTION option) {
99 return options.contains(option);
100 }
101
102 /**
103 * {@inheritDoc}
104 */
105 @Override
106 public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
107 final int seqEnd = input.length();
108 // Uses -2 to ensure there is something after the &#
109 if (input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
110 int start = index + 2;
111 boolean isHex = false;
112
113 final char firstChar = input.charAt(start);
114 if (firstChar == 'x' || firstChar == 'X') {
115 start++;
116 isHex = true;
117
118 // Check there's more than just an x after the &#
119 if (start == seqEnd) {
120 return 0;
121 }
122 }
123
124 int end = start;
125 // Note that this supports character codes without a ; on the end
126 while (end < seqEnd && (input.charAt(end) >= '0' && input.charAt(end) <= '9'
127 || input.charAt(end) >= 'a' && input.charAt(end) <= 'f'
128 || input.charAt(end) >= 'A' && input.charAt(end) <= 'F')) {
129 end++;
130 }
131
132 final boolean semiNext = end != seqEnd && input.charAt(end) == ';';
133
134 if (!semiNext) {
135 if (isSet(OPTION.semiColonRequired)) {
136 return 0;
137 }
138 if (isSet(OPTION.errorIfNoSemiColon)) {
139 throw new IllegalArgumentException("Semi-colon required at end of numeric entity");
140 }
141 }
142
143 final int entityValue;
144 try {
145 if (isHex) {
146 entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
147 } else {
148 entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
149 }
150 } catch (final NumberFormatException nfe) {
151 return 0;
152 }
153
154 if (entityValue > 0xFFFF) {
155 final char[] chrs = Character.toChars(entityValue);
156 writer.write(chrs[0]);
157 writer.write(chrs[1]);
158 } else {
159 writer.write(entityValue);
160 }
161
162 return 2 + end - start + (isHex ? 1 : 0) + (semiNext ? 1 : 0);
163 }
164 return 0;
165 }
166 }