001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3.text.translate;
018
019import java.io.IOException;
020import java.io.Writer;
021import java.util.Arrays;
022import java.util.Collections;
023import java.util.EnumSet;
024
025/**
026 * Translate XML numeric entities of the form &#[xX]?\d+;? to
027 * the specific code point.
028 *
029 * Note that the semicolon is optional.
030 *
031 * @since 3.0
032 * @deprecated As of 3.6, use Apache Commons Text
033 * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/translate/NumericEntityUnescaper.html">
034 * NumericEntityUnescaper</a> instead
035 */
036@Deprecated
037public class NumericEntityUnescaper extends CharSequenceTranslator {
038
039    /** Enumerates NumericEntityUnescaper options for unescaping. */
040    public enum OPTION {
041
042        /**
043         * Require a semicolon.
044         */
045        semiColonRequired,
046
047        /**
048         * Do not require a semicolon.
049         */
050        semiColonOptional,
051
052        /**
053         * Throw an exception if a semicolon is missing.
054         */
055        errorIfNoSemiColon
056    }
057
058    // TODO?: Create an OptionsSet class to hide some of the conditional logic below
059    private final EnumSet<OPTION> options;
060
061    /**
062     * Create a UnicodeUnescaper.
063     *
064     * The constructor takes a list of options, only one type of which is currently
065     * available (whether to allow, error or ignore the semicolon on the end of a
066     * numeric entity to being missing).
067     *
068     * For example, to support numeric entities without a ';':
069     *    new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional)
070     * and to throw an IllegalArgumentException when they're missing:
071     *    new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon)
072     *
073     * Note that the default behavior is to ignore them.
074     *
075     * @param options to apply to this unescaper
076     */
077    public NumericEntityUnescaper(final OPTION... options) {
078        if (options.length > 0) {
079            this.options = EnumSet.copyOf(Arrays.asList(options));
080        } else {
081            this.options = EnumSet.copyOf(Collections.singletonList(OPTION.semiColonRequired));
082        }
083    }
084
085    /**
086     * Whether the passed in option is currently set.
087     *
088     * @param option to check state of
089     * @return whether the option is set
090     */
091    public boolean isSet(final OPTION option) {
092        return options != null && options.contains(option);
093    }
094
095    /**
096     * {@inheritDoc}
097     */
098    @Override
099    public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
100        final int seqEnd = input.length();
101        // Uses -2 to ensure there is something after the &#
102        if (input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
103            int start = index + 2;
104            boolean isHex = false;
105
106            final char firstChar = input.charAt(start);
107            if (firstChar == 'x' || firstChar == 'X') {
108                start++;
109                isHex = true;
110
111                // Check there's more than just an x after the &#
112                if (start == seqEnd) {
113                    return 0;
114                }
115            }
116
117            int end = start;
118            // Note that this supports character codes without a ; on the end
119            while (end < seqEnd && ( input.charAt(end) >= '0' && input.charAt(end) <= '9' ||
120                                    input.charAt(end) >= 'a' && input.charAt(end) <= 'f' ||
121                                    input.charAt(end) >= 'A' && input.charAt(end) <= 'F' ) ) {
122                end++;
123            }
124
125            final boolean semiNext = end != seqEnd && input.charAt(end) == ';';
126
127            if (!semiNext) {
128                if (isSet(OPTION.semiColonRequired)) {
129                    return 0;
130                }
131                if (isSet(OPTION.errorIfNoSemiColon)) {
132                    throw new IllegalArgumentException("Semi-colon required at end of numeric entity");
133                }
134            }
135
136            final int entityValue;
137            try {
138                if (isHex) {
139                    entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
140                } else {
141                    entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
142                }
143            } catch (final NumberFormatException nfe) {
144                return 0;
145            }
146
147            if (entityValue > 0xFFFF) {
148                final char[] chars = Character.toChars(entityValue);
149                out.write(chars[0]);
150                out.write(chars[1]);
151            } else {
152                out.write(entityValue);
153            }
154
155            return 2 + end - start + (isHex ? 1 : 0) + (semiNext ? 1 : 0);
156        }
157        return 0;
158    }
159}