SinglePassTranslator.java

  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. import java.io.IOException;
  19. import java.io.Writer;

  20. /**
  21.  * Abstract translator for processing whole input in single pass.
  22.  * Handles initial index checking and counting of returned code points.
  23.  */
  24. abstract class SinglePassTranslator extends CharSequenceTranslator {

  25.     /**
  26.      * A utility method to be used in the {@link #translate(CharSequence, int, Writer)} method.
  27.      *
  28.      * @return The name of this or the extending class.
  29.      */
  30.     private String getClassName() {
  31.         final Class<? extends SinglePassTranslator> clazz = this.getClass();
  32.         return clazz.isAnonymousClass() ?  clazz.getName() : clazz.getSimpleName();
  33.     }

  34.     /**
  35.      * {@inheritDoc}
  36.      * @throws IllegalArgumentException if {@code index != 0}
  37.      */
  38.     @Override
  39.     public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
  40.         if (index != 0) {
  41.             throw new IllegalArgumentException(getClassName() + ".translate(final CharSequence input, final int "
  42.                     + "index, final Writer out) cannot handle a non-zero index.");
  43.         }

  44.         translateWhole(input, writer);

  45.         return Character.codePointCount(input, index, input.length());
  46.     }

  47.     /**
  48.      * Translates whole set of code points passed in input.
  49.      *
  50.      * @param input CharSequence that is being translated
  51.      * @param writer Writer to translate the text to
  52.      * @throws IOException if and only if the Writer produces an IOException
  53.      */
  54.     abstract void translateWhole(CharSequence input, Writer writer) throws IOException;
  55. }