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;
021
022/**
023 * Translates escaped Unicode values of the form \\u+\d\d\d\d back to
024 * Unicode. It supports multiple 'u' characters and will work with or
025 * without the +.
026 *
027 * @since 1.0
028 */
029public class UnicodeUnescaper extends CharSequenceTranslator {
030
031    /**
032     * Constructs a new instance.
033     */
034    public UnicodeUnescaper() {
035        // empty
036    }
037
038    /**
039     * {@inheritDoc}
040     */
041    @Override
042    public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
043        if (input.charAt(index) == '\\' && index + 1 < input.length() && input.charAt(index + 1) == 'u') {
044            // consume optional additional 'u' chars
045            int i = 2;
046            while (index + i < input.length() && input.charAt(index + i) == 'u') {
047                i++;
048            }
049
050            if (index + i < input.length() && input.charAt(index + i) == '+') {
051                i++;
052            }
053
054            if (index + i + 4 <= input.length()) {
055                // Get 4 hex digits
056                final CharSequence unicode = input.subSequence(index + i, index + i + 4);
057
058                try {
059                    final int value = Integer.parseInt(unicode.toString(), 16);
060                    writer.write((char) value);
061                } catch (final NumberFormatException nfe) {
062                    throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe);
063                }
064                return i + 4;
065            }
066            throw new IllegalArgumentException("Less than 4 hex digits in unicode value: '"
067                    + input.subSequence(index, input.length())
068                    + "' due to end of CharSequence");
069        }
070        return 0;
071    }
072}