View Javadoc
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;
18  
19  import static java.util.FormattableFlags.LEFT_JUSTIFY;
20  
21  import java.util.Formattable;
22  import java.util.Formatter;
23  
24  import org.apache.commons.lang3.StringUtils;
25  
26  /**
27   * Provides utilities for working with the {@code Formattable} interface.
28   *
29   * <p>The {@link Formattable} interface provides basic control over formatting
30   * when using a {@code Formatter}. It is primarily concerned with numeric precision
31   * and padding, and is not designed to allow generalised alternate formats.</p>
32   *
33   * @since 1.0
34   */
35  public class FormattableUtils {
36  
37      /**
38       * A format that simply outputs the value as a string.
39       */
40      private static final String SIMPLEST_FORMAT = "%s";
41  
42      /**
43       * Handles the common {@code Formattable} operations of truncate-pad-append,
44       * with no ellipsis on precision overflow, and padding width underflow with
45       * spaces.
46       *
47       * @param seq  the string to handle, not null
48       * @param formatter  the destination formatter, not null
49       * @param flags  the flags for formatting, see {@code Formattable}
50       * @param width  the width of the output, see {@code Formattable}
51       * @param precision  the precision of the output, see {@code Formattable}
52       * @return The {@code formatter} instance, not null
53       */
54      public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
55              final int precision) {
56          return append(seq, formatter, flags, width, precision, ' ', null);
57      }
58  
59      /**
60       * Handles the common {@link Formattable} operations of truncate-pad-append,
61       * with no ellipsis on precision overflow.
62       *
63       * @param seq  the string to handle, not null
64       * @param formatter  the destination formatter, not null
65       * @param flags  the flags for formatting, see {@code Formattable}
66       * @param width  the width of the output, see {@code Formattable}
67       * @param precision  the precision of the output, see {@code Formattable}
68       * @param padChar  the pad character to use
69       * @return The {@code formatter} instance, not null
70       */
71      public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
72              final int precision, final char padChar) {
73          return append(seq, formatter, flags, width, precision, padChar, null);
74      }
75  
76      /**
77       * Handles the common {@link Formattable} operations of truncate-pad-append.
78       *
79       * @param seq  the string to handle, not null
80       * @param formatter  the destination formatter, not null
81       * @param flags  the flags for formatting, see {@code Formattable}
82       * @param width  the width of the output, see {@code Formattable}
83       * @param precision  the precision of the output, see {@code Formattable}
84       * @param padChar  the pad character to use
85       * @param truncateEllipsis  the ellipsis to use when precision dictates truncation, null or
86       *  empty causes a hard truncation
87       * @return The {@code formatter} instance, not null
88       * @throws IllegalArgumentException if {@code ellipsis.length() > precision},
89       *  given that {@code ellipsis} is not null and {@code precision >= 0}
90       */
91      public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
92              final int precision, final char padChar, final CharSequence truncateEllipsis) {
93          if (!(truncateEllipsis == null || precision < 0 || truncateEllipsis.length() <= precision)) {
94              throw new IllegalArgumentException(
95                      String.format("Specified ellipsis '%s' exceeds precision of %s",
96                              truncateEllipsis,
97                              precision));
98          }
99          final StringBuilder buf = new StringBuilder(seq);
100         if (precision >= 0 && precision < seq.length()) {
101             final CharSequence ellipsis;
102             if (truncateEllipsis == null) {
103                 ellipsis = StringUtils.EMPTY;
104             } else {
105                 ellipsis = truncateEllipsis;
106             }
107             buf.replace(precision - ellipsis.length(), seq.length(), ellipsis.toString());
108         }
109         final boolean leftJustify = (flags & LEFT_JUSTIFY) == LEFT_JUSTIFY;
110         for (int i = buf.length(); i < width; i++) {
111             buf.insert(leftJustify ? i : 0, padChar);
112         }
113         formatter.format(buf.toString());
114         return formatter;
115     }
116 
117     /**
118      * Handles the common {@link Formattable} operations of truncate-pad-append,
119      * padding width underflow with spaces.
120      *
121      * @param seq  the string to handle, not null
122      * @param formatter  the destination formatter, not null
123      * @param flags  the flags for formatting, see {@code Formattable}
124      * @param width  the width of the output, see {@code Formattable}
125      * @param precision  the precision of the output, see {@code Formattable}
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      * @throws IllegalArgumentException if {@code ellipsis.length() > precision},
130      *  given that {@code ellipsis} is not null and {@code precision >= 0}
131      */
132     public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width,
133             final int precision, final CharSequence ellipsis) {
134         return append(seq, formatter, flags, width, precision, ' ', ellipsis);
135     }
136 
137     /**
138      * Gets the default formatted representation of the specified
139      * {@code Formattable}.
140      *
141      * @param formattable  the instance to convert to a string, not null
142      * @return The resulting string, not null
143      */
144     public static String toString(final Formattable formattable) {
145         return String.format(SIMPLEST_FORMAT, formattable);
146     }
147 
148     /**
149      * {@code FormattableUtils} instances should NOT be constructed in
150      * standard programming. Instead, the methods of the class should be invoked
151      * statically.
152      *
153      * <p>This constructor is public to permit tools that require a JavaBean
154      * instance to operate.</p>
155      */
156     public FormattableUtils() {
157     }
158 
159 }