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