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.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
67       * available (whether to allow, error or ignore the semicolon on the end of a
68       * numeric entity to being missing).
69       *
70       * For example, to support numeric entities without a ';':
71       *    new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional)
72       * and to throw an IllegalArgumentException when they're missing:
73       *    new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon)
74       *
75       * Note that the default behavior is to ignore them.
76       *
77       * @param options to apply to this unescaper
78       */
79      public NumericEntityUnescaper(final OPTION... options) {
80          this.options = ArrayUtils.isEmpty(options) ? DEFAULT_OPTIONS : EnumSet.copyOf(Arrays.asList(options));
81      }
82  
83      /**
84       * Tests whether the passed in option is currently set.
85       *
86       * @param option to check state of
87       * @return whether the option is set
88       */
89      public boolean isSet(final OPTION option) {
90          return options.contains(option);
91      }
92  
93      /**
94       * {@inheritDoc}
95       */
96      @Override
97      public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
98          final int seqEnd = input.length();
99          // Uses -2 to ensure there is something after the &#
100         if (input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
101             int start = index + 2;
102             boolean isHex = false;
103 
104             final char firstChar = input.charAt(start);
105             if (firstChar == 'x' || firstChar == 'X') {
106                 start++;
107                 isHex = true;
108 
109                 // Check there's more than just an x after the &#
110                 if (start == seqEnd) {
111                     return 0;
112                 }
113             }
114 
115             int end = start;
116             // Note that this supports character codes without a ; on the end
117             while (end < seqEnd && (input.charAt(end) >= '0' && input.charAt(end) <= '9'
118                                     || input.charAt(end) >= 'a' && input.charAt(end) <= 'f'
119                                     || input.charAt(end) >= 'A' && input.charAt(end) <= 'F')) {
120                 end++;
121             }
122 
123             final boolean semiNext = end != seqEnd && input.charAt(end) == ';';
124 
125             if (!semiNext) {
126                 if (isSet(OPTION.semiColonRequired)) {
127                     return 0;
128                 }
129                 if (isSet(OPTION.errorIfNoSemiColon)) {
130                     throw new IllegalArgumentException("Semi-colon required at end of numeric entity");
131                 }
132             }
133 
134             final int entityValue;
135             try {
136                 if (isHex) {
137                     entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
138                 } else {
139                     entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
140                 }
141             } catch (final NumberFormatException nfe) {
142                 return 0;
143             }
144 
145             if (entityValue > 0xFFFF) {
146                 final char[] chrs = Character.toChars(entityValue);
147                 writer.write(chrs[0]);
148                 writer.write(chrs[1]);
149             } else {
150                 writer.write(entityValue);
151             }
152 
153             return 2 + end - start + (isHex ? 1 : 0) + (semiNext ? 1 : 0);
154         }
155         return 0;
156     }
157 }