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