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 */
017 package org.apache.commons.lang3.text.translate;
018
019 import java.io.IOException;
020 import java.io.Writer;
021 import java.util.Arrays;
022 import java.util.EnumSet;
023
024 /**
025 * Translates escaped unicode values of the form \\u+\d\d\d\d back to
026 * unicode. It supports multiple 'u' characters and will work with or
027 * without the +.
028 *
029 * @since 3.0
030 * @version $Id: UnicodeUnescaper.java 1145851 2011-07-13 03:31:14Z bayard $
031 */
032 public class UnicodeUnescaper extends CharSequenceTranslator {
033
034 /**
035 * {@inheritDoc}
036 */
037 @Override
038 public int translate(CharSequence input, int index, Writer out) throws IOException {
039 if(input.charAt(index) == '\\') {
040 if( (index + 1 < input.length()) && input.charAt(index + 1) == 'u') {
041 // consume optional additional 'u' chars
042 int i=2;
043 while( (index + i < input.length()) && input.charAt(index + i) == 'u') {
044 i++;
045 }
046
047 if( (index + i < input.length()) && (input.charAt(index + i) == '+') ) {
048 i++;
049 }
050
051 if( (index + i + 4 <= input.length()) ) {
052 // Get 4 hex digits
053 CharSequence unicode = input.subSequence(index + i, index + i + 4);
054
055 try {
056 int value = Integer.parseInt(unicode.toString(), 16);
057 out.write((char) value);
058 } catch (NumberFormatException nfe) {
059 throw new IllegalArgumentException("Unable to parse unicode value: " + unicode, nfe);
060 }
061 return i + 4;
062 } else {
063 throw new IllegalArgumentException("Less than 4 hex digits in unicode value: '" +
064 input.subSequence(index, input.length()) +
065 "' due to end of CharSequence");
066 }
067 }
068 }
069 return 0;
070 }
071 }