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