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