Source code
Description: source: package: org.apache.commons.text.translate, class: NumericEntityUnescaper, enum: OPTION

    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.Collections;
    023import java.util.EnumSet;
    024
    025import org.apache.commons.lang3.ArrayUtils;
    026
    027/**
    028 * Translates XML numeric entities of the form &amp;#[xX]?\d+;? to
    029 * the specific code point.
    030 *
    031 * Note that the semicolon is optional.
    032 *
    033 * @since 1.0
    034 */
    035public class NumericEntityUnescaper extends CharSequenceTranslator {
    036
    037    /** Enumerates NumericEntityUnescaper options for unescaping. */
    038    public enum OPTION {
    039
    040        /**
    041         * Requires a semicolon.
    042         */
    043        semiColonRequired,
    044
    045        /**
    046         * Does not require a semicolon.
    047         */
    048        semiColonOptional,
    049
    050        /**
    051         * Throws an exception if a semicolon is missing.
    052         */
    053        errorIfNoSemiColon
    054    }
    055
    056    /** Default options. */
    057    private static final EnumSet<OPTION> DEFAULT_OPTIONS = EnumSet
    058        .copyOf(Collections.singletonList(OPTION.semiColonRequired));
    059
    060    /** EnumSet of OPTIONS, given from the constructor, read-only. */
    061    private final EnumSet<OPTION> options;
    062
    063    /**
    064     * Creates a UnicodeUnescaper.
    065     *
    066     * The constructor takes a list of options, only one type of which is currently
    067     * available (whether to allow, error or ignore the semicolon on the end of a
    068     * numeric entity to being missing).
    069     *
    070     * For example, to support numeric entities without a ';':
    071     *    new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional)
    072     * and to throw an IllegalArgumentException when they're missing:
    073     *    new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon)
    074     *
    075     * Note that the default behavior is to ignore them.
    076     *
    077     * @param options to apply to this unescaper
    078     */
    079    public NumericEntityUnescaper(final OPTION... options) {
    080        this.options = ArrayUtils.isEmpty(options) ? DEFAULT_OPTIONS : EnumSet.copyOf(Arrays.asList(options));
    081    }
    082
    083    /**
    084     * Tests whether the passed in option is currently set.
    085     *
    086     * @param option to check state of
    087     * @return whether the option is set
    088     */
    089    public boolean isSet(final OPTION option) {
    090        return options.contains(option);
    091    }
    092
    093    /**
    094     * {@inheritDoc}
    095     */
    096    @Override
    097    public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
    098        final int seqEnd = input.length();
    099        // 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}