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.text;
018
019import java.util.Formattable;
020import java.util.Formatter;
021
022import static java.util.FormattableFlags.LEFT_JUSTIFY;
023
024/**
025 * <p>Provides utilities for working with the {@code Formattable} interface.</p>
026 * 
027 * <p>The {@link Formattable} interface provides basic control over formatting
028 * when using a {@code Formatter}. It is primarily concerned with numeric precision
029 * and padding, and is not designed to allow generalised alternate formats.</p>
030 *
031 * @since 1.0
032 *
033 */
034public class FormattableUtils {
035
036    /**
037     * A format that simply outputs the value as a string.
038     */
039    private static final String SIMPLEST_FORMAT = "%s";
040
041    /**
042     * <p>{@code FormattableUtils} instances should NOT be constructed in
043     * standard programming. Instead, the methods of the class should be invoked
044     * statically.</p>
045     * 
046     * <p>This constructor is public to permit tools that require a JavaBean
047     * instance to operate.</p>
048     */
049    public FormattableUtils() {
050        super();
051    }
052
053    //-----------------------------------------------------------------------
054    /**
055     * Get the default formatted representation of the specified
056     * {@code Formattable}.
057     * 
058     * @param formattable  the instance to convert to a string, not null
059     * @return the resulting string, not null
060     */
061    public static String toString(final Formattable formattable) {
062        return String.format(SIMPLEST_FORMAT, formattable);
063    }
064
065    /**
066     * Handles the common {@code Formattable} operations of truncate-pad-append,
067     * with no ellipsis on precision overflow, and padding width underflow with
068     * spaces.
069     * 
070     * @param seq  the string to handle, not null
071     * @param formatter  the destination formatter, not null
072     * @param flags  the flags for formatting, see {@code Formattable}
073     * @param width  the width of the output, see {@code Formattable}
074     * @param precision  the precision of the output, see {@code Formattable}
075     * @return the {@code formatter} instance, not null
076     */
077    public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
078            final int precision) {
079        return append(seq, formatter, flags, width, precision, ' ', null);
080    }
081
082    /**
083     * Handles the common {@link Formattable} operations of truncate-pad-append,
084     * with no ellipsis on precision overflow.
085     * 
086     * @param seq  the string to handle, not null
087     * @param formatter  the destination formatter, not null
088     * @param flags  the flags for formatting, see {@code Formattable}
089     * @param width  the width of the output, see {@code Formattable}
090     * @param precision  the precision of the output, see {@code Formattable}
091     * @param padChar  the pad character to use
092     * @return the {@code formatter} instance, not null
093     */
094    public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
095            final int precision, final char padChar) {
096        return append(seq, formatter, flags, width, precision, padChar, null);
097    }
098
099    /**
100     * Handles the common {@link Formattable} operations of truncate-pad-append,
101     * padding width underflow with spaces.
102     * 
103     * @param seq  the string to handle, not null
104     * @param formatter  the destination formatter, not null
105     * @param flags  the flags for formatting, see {@code Formattable}
106     * @param width  the width of the output, see {@code Formattable}
107     * @param precision  the precision of the output, see {@code Formattable}
108     * @param ellipsis  the ellipsis to use when precision dictates truncation, null or
109     *  empty causes a hard truncation
110     * @return the {@code formatter} instance, not null
111     */
112    public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
113            final int precision, final CharSequence ellipsis) {
114        return append(seq, formatter, flags, width, precision, ' ', ellipsis);
115    }
116
117    /**
118     * Handles the common {@link Formattable} operations of truncate-pad-append.
119     * 
120     * @param seq  the string to handle, not null
121     * @param formatter  the destination formatter, not null
122     * @param flags  the flags for formatting, see {@code Formattable}
123     * @param width  the width of the output, see {@code Formattable}
124     * @param precision  the precision of the output, see {@code Formattable}
125     * @param padChar  the pad character to use
126     * @param ellipsis  the ellipsis to use when precision dictates truncation, null or
127     *  empty causes a hard truncation
128     * @return the {@code formatter} instance, not null
129     */
130    public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
131            final int precision, final char padChar, final CharSequence ellipsis) {
132        if ( ! (ellipsis == null || precision < 0 || ellipsis.length() <= precision) ) {
133            throw new IllegalArgumentException(String.format("Specified ellipsis '%1$s' exceeds precision of %2$s", ellipsis, Integer.valueOf(precision)));
134        }
135        final StringBuilder buf = new StringBuilder(seq);
136        if (precision >= 0 && precision < seq.length()) {
137            final CharSequence _ellipsis;
138            if (ellipsis == null) {
139                _ellipsis = "";
140            } else {
141                _ellipsis = ellipsis;
142            }
143            buf.replace(precision - _ellipsis.length(), seq.length(), _ellipsis.toString());
144        }
145        final boolean leftJustify = (flags & LEFT_JUSTIFY) == LEFT_JUSTIFY;
146        for (int i = buf.length(); i < width; i++) {
147            buf.insert(leftJustify ? i : 0, padChar);
148        }
149        formatter.format(buf.toString());
150        return formatter;
151    }
152
153}