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 *      https://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 the specific code point.
027 *
028 * Note that the semicolon is optional.
029 *
030 * @since 3.0
031 * @deprecated As of <a href="https://commons.apache.org/proper/commons-lang/changes-report.html#a3.6">3.6</a>, use Apache Commons Text
032 *             <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/translate/NumericEntityUnescaper.html">
033 *             NumericEntityUnescaper</a>.
034 */
035@Deprecated
036public class NumericEntityUnescaper extends CharSequenceTranslator {
037
038    /**
039     * Enumerates NumericEntityUnescaper options for unescaping.
040     *
041     * @deprecated As of 3.18.0, use Apache Commons Text <a href=
042     *             "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/translate/NumericEntityUnescaper.OPTION.html">
043     *             NumericEntityUnescaper.OPTION</a>.
044     */
045    @Deprecated
046    public enum OPTION {
047
048        /**
049         * Require a semicolon.
050         */
051        semiColonRequired,
052
053        /**
054         * Do not require a semicolon.
055         */
056        semiColonOptional,
057
058        /**
059         * Throw an exception if a semicolon is missing.
060         */
061        errorIfNoSemiColon
062    }
063
064    // TODO?: Create an OptionsSet class to hide some of the conditional logic below
065    private final EnumSet<OPTION> options;
066
067    /**
068     * Create a UnicodeUnescaper.
069     *
070     * The constructor takes a list of options, only one type of which is currently
071     * available (whether to allow, error or ignore the semicolon on the end of a
072     * numeric entity to being missing).
073     *
074     * For example, to support numeric entities without a ';':
075     *    new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional)
076     * and to throw an IllegalArgumentException when they're missing:
077     *    new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon)
078     *
079     * Note that the default behavior is to ignore them.
080     *
081     * @param options to apply to this unescaper
082     */
083    public NumericEntityUnescaper(final OPTION... options) {
084        if (options.length > 0) {
085            this.options = EnumSet.copyOf(Arrays.asList(options));
086        } else {
087            this.options = EnumSet.copyOf(Collections.singletonList(OPTION.semiColonRequired));
088        }
089    }
090
091    /**
092     * Tests whether the passed in option is currently set.
093     *
094     * @param option to check state of
095     * @return whether the option is set
096     */
097    public boolean isSet(final OPTION option) {
098        return options != null && options.contains(option);
099    }
100
101    /**
102     * {@inheritDoc}
103     */
104    @Override
105    public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
106        final int seqEnd = input.length();
107        // Uses -2 to ensure there is something after the &#
108        if (input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
109            int start = index + 2;
110            boolean isHex = false;
111
112            final char firstChar = input.charAt(start);
113            if (firstChar == 'x' || firstChar == 'X') {
114                start++;
115                isHex = true;
116
117                // Check there's more than just an x after the &#
118                if (start == seqEnd) {
119                    return 0;
120                }
121            }
122
123            int end = start;
124            // Note that this supports character codes without a ; on the end
125            while (end < seqEnd && (input.charAt(end) >= '0' && input.charAt(end) <= '9' ||
126                                    input.charAt(end) >= 'a' && input.charAt(end) <= 'f' ||
127                                    input.charAt(end) >= 'A' && input.charAt(end) <= 'F')) {
128                end++;
129            }
130
131            final boolean semiNext = end != seqEnd && input.charAt(end) == ';';
132
133            if (!semiNext) {
134                if (isSet(OPTION.semiColonRequired)) {
135                    return 0;
136                }
137                if (isSet(OPTION.errorIfNoSemiColon)) {
138                    throw new IllegalArgumentException("Semi-colon required at end of numeric entity");
139                }
140            }
141
142            final int entityValue;
143            try {
144                if (isHex) {
145                    entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
146                } else {
147                    entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
148                }
149            } catch (final NumberFormatException nfe) {
150                return 0;
151            }
152
153            if (entityValue > 0xFFFF) {
154                final char[] chars = Character.toChars(entityValue);
155                out.write(chars[0]);
156                out.write(chars[1]);
157            } else {
158                out.write(entityValue);
159            }
160
161            return 2 + end - start + (isHex ? 1 : 0) + (semiNext ? 1 : 0);
162        }
163        return 0;
164    }
165}