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.lang3.text.translate;
018
019import java.io.IOException;
020import java.io.StringWriter;
021import java.io.Writer;
022import java.util.Locale;
023
024/**
025 * An API for translating text. 
026 * Its core use is to escape and unescape text. Because escaping and unescaping 
027 * is completely contextual, the API does not present two separate signatures.
028 * 
029 * @since 3.0
030 * @version $Id: CharSequenceTranslator.java 1471063 2013-04-23 17:31:21Z sebb $
031 */
032public abstract class CharSequenceTranslator {
033
034    /**
035     * Translate a set of codepoints, represented by an int index into a CharSequence, 
036     * into another set of codepoints. The number of codepoints consumed must be returned, 
037     * and the only IOExceptions thrown must be from interacting with the Writer so that 
038     * the top level API may reliably ignore StringWriter IOExceptions. 
039     *
040     * @param input CharSequence that is being translated
041     * @param index int representing the current point of translation
042     * @param out Writer to translate the text to
043     * @return int count of codepoints consumed
044     * @throws IOException if and only if the Writer produces an IOException
045     */
046    public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
047
048    /**
049     * Helper for non-Writer usage. 
050     * @param input CharSequence to be translated
051     * @return String output of translation
052     */
053    public final String translate(final CharSequence input) {
054        if (input == null) {
055            return null;
056        }
057        try {
058            final StringWriter writer = new StringWriter(input.length() * 2);
059            translate(input, writer);
060            return writer.toString();
061        } catch (final IOException ioe) {
062            // this should never ever happen while writing to a StringWriter
063            throw new RuntimeException(ioe);
064        }
065    }
066
067    /**
068     * Translate an input onto a Writer. This is intentionally final as its algorithm is 
069     * tightly coupled with the abstract method of this class. 
070     *
071     * @param input CharSequence that is being translated
072     * @param out Writer to translate the text to
073     * @throws IOException if and only if the Writer produces an IOException
074     */
075    public final void translate(final CharSequence input, final Writer out) throws IOException {
076        if (out == null) {
077            throw new IllegalArgumentException("The Writer must not be null");
078        }
079        if (input == null) {
080            return;
081        }
082        int pos = 0;
083        final int len = input.length();
084        while (pos < len) {
085            final int consumed = translate(input, pos, out);
086            if (consumed == 0) {
087                final char[] c = Character.toChars(Character.codePointAt(input, pos));
088                out.write(c);
089                pos+= c.length;
090                continue;
091            }
092//          // contract with translators is that they have to understand codepoints 
093//          // and they just took care of a surrogate pair
094            for (int pt = 0; pt < consumed; pt++) {
095                pos += Character.charCount(Character.codePointAt(input, pt));
096            }
097        }
098    }
099
100    /**
101     * Helper method to create a merger of this translator with another set of 
102     * translators. Useful in customizing the standard functionality.
103     *
104     * @param translators CharSequenceTranslator array of translators to merge with this one
105     * @return CharSequenceTranslator merging this translator with the others
106     */
107    public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
108        final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
109        newArray[0] = this;
110        System.arraycopy(translators, 0, newArray, 1, translators.length);
111        return new AggregateTranslator(newArray);
112    }
113
114    /**
115     * <p>Returns an upper case hexadecimal <code>String</code> for the given
116     * character.</p>
117     *
118     * @param codepoint The codepoint to convert.
119     * @return An upper case hexadecimal <code>String</code>
120     */
121    public static String hex(final int codepoint) {
122        return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
123    }
124
125}