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 022 /** 023 * Translate escaped octal Strings back to their octal values. 024 * 025 * For example, "\45" should go back to being the specific value (a %). 026 * 027 * Note that this currently only supports the viable range of octal for Java; namely 028 * 1 to 377. This is both because parsing Java is the main use case and Integer.parseInt 029 * throws an exception when values are larger than octal 377. 030 * 031 * @since 3.0 032 * @version $Id: OctalUnescaper.java 967237 2010-07-23 20:08:57Z mbenson $ 033 */ 034 public class OctalUnescaper extends CharSequenceTranslator { 035 036 private static int OCTAL_MAX = 377; 037 038 /** 039 * {@inheritDoc} 040 */ 041 @Override 042 public int translate(CharSequence input, int index, Writer out) throws IOException { 043 if(input.charAt(index) == '\\' && index < (input.length() - 1) && Character.isDigit(input.charAt(index + 1)) ) { 044 int start = index + 1; 045 046 int end = index + 2; 047 while ( end < input.length() && Character.isDigit(input.charAt(end)) ) { 048 end++; 049 if ( Integer.parseInt(input.subSequence(start, end).toString(), 10) > OCTAL_MAX) { 050 end--; // rollback 051 break; 052 } 053 } 054 055 out.write( Integer.parseInt(input.subSequence(start, end).toString(), 8) ); 056 return 1 + end - start; 057 } 058 return 0; 059 } 060 }