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