1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.commons.text.translate; 18 19 import java.io.IOException; 20 import java.io.Writer; 21 22 /** 23 * Abstract translator for processing whole input in single pass. 24 * Handles initial index checking and counting of returned code points. 25 */ 26 abstract class SinglePassTranslator extends CharSequenceTranslator { 27 28 /** 29 * A utility method to be used in the {@link #translate(CharSequence, int, Writer)} method. 30 * 31 * @return The name of this or the extending class. 32 */ 33 private String getClassName() { 34 final Class<? extends SinglePassTranslator> clazz = this.getClass(); 35 return clazz.isAnonymousClass() ? clazz.getName() : clazz.getSimpleName(); 36 } 37 38 /** 39 * {@inheritDoc} 40 * @throws IllegalArgumentException if {@code index != 0} 41 */ 42 @Override 43 public int translate(final CharSequence input, final int index, final Writer writer) throws IOException { 44 if (index != 0) { 45 throw new IllegalArgumentException(getClassName() + ".translate(final CharSequence input, final int " 46 + "index, final Writer out) cannot handle a non-zero index."); 47 } 48 49 translateWhole(input, writer); 50 51 return Character.codePointCount(input, index, input.length()); 52 } 53 54 /** 55 * Translates whole set of code points passed in input. 56 * 57 * @param input CharSequence that is being translated 58 * @param writer Writer to translate the text to 59 * @throws IOException if and only if the Writer produces an IOException 60 */ 61 abstract void translateWhole(CharSequence input, Writer writer) throws IOException; 62 }