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