View Javadoc

1   /**
2    * Copyright (c) 2012, University of Konstanz, Distributed Systems Group
3    * All rights reserved.
4    * 
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions are met:
7    * * Redistributions of source code must retain the above copyright
8    * notice, this list of conditions and the following disclaimer.
9    * * Redistributions in binary form must reproduce the above copyright
10   * notice, this list of conditions and the following disclaimer in the
11   * documentation and/or other materials provided with the distribution.
12   * * Neither the name of the University of Konstanz nor the
13   * names of its contributors may be used to endorse or promote products
14   * derived from this software without specific prior written permission.
15   * 
16   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19   * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
20   * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21   * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24   * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26   */
27  package org.perfidix.ouput.asciitable;
28  
29  import org.perfidix.ouput.asciitable.AbstractTabularComponent.Alignment;
30  
31  /**
32   * Utilities for the ascii table.
33   */
34  public final class Util {
35  
36      /**
37       * private constructor.
38       */
39      private Util() {
40          // do nothing.
41      }
42  
43      /**
44       * Combines an unknown number of Strings to one String.
45       * 
46       * @param args
47       *            multiple Strings
48       * @return the combined string
49       */
50      protected static String combine(final String... args) {
51          final StringBuilder builder = new StringBuilder();
52          for (final String arg : args) {
53              builder.append(arg);
54          }
55          return builder.toString();
56      }
57  
58      /**
59       * This method fills one char either on the right site of a given string or
60       * on the left site or on both sites. Refer to the example below.
61       * 
62       * <pre>
63       *  pad (&quot;hello&quot;,'-',11,NiceTable.LEFT);
64       *  results in &quot;hello------&quot;
65       *  pad(&quot;hello&quot;,'/',11,NiceTable.RIGHT);
66       *  results in &quot;//////hello&quot;;
67       *  pad(&quot;hello&quot;,'.',11,NiceTable.CENTER);
68       *  results in &quot;...hello...&quot;
69       * </pre>
70       * 
71       * @return padded string
72       * @param doPadWithThis
73       *            the string to pad the string with
74       * @param data
75       *            the data to pad
76       * @param orientation
77       *            which orientation to take
78       * @param totalWidth
79       *            the total width of the result string
80       */
81      protected static String pad(final String data, final char doPadWithThis, final int totalWidth,
82          final Alignment orientation) {
83  
84          final String pad = repeat(new String(new char[] {
85              doPadWithThis
86          }), Math.max(0, totalWidth - data.length()));
87          String returnVal = "";
88          if (orientation == null) {
89              returnVal = new StringBuilder(data).append(pad).toString();
90          } else {
91              switch (orientation) {
92              case Center:
93                  returnVal =
94                      pad.substring(0, pad.length() / 2) + data + pad.substring(pad.length() / 2, pad.length());
95                  break;
96              case Right:
97                  returnVal = new StringBuilder(pad).append(data).toString();
98                  break;
99              default:
100                 returnVal = new StringBuilder(data).append(pad).toString();
101 
102             }
103         }
104         return returnVal;
105     }
106 
107     /**
108      * Concantenate a String array "what" with glue "glue".
109      * 
110      * @param what
111      *            the array of strings to concantenate
112      * @param glue
113      *            the glue string to use.
114      * 
115      *            <pre>
116      * String[] what = {
117      *     &quot;a&quot;, &quot;b&quot;, &quot;c&quot;
118      * };
119      * 
120      * String s = Util.implode(&quot;-&quot;, what);
121      * // result is &quot;a-b-c&quot;
122      * </pre>
123      * @return String
124      */
125     protected static String implode(final String glue, final String[] what) {
126 
127         final StringBuilder builder = new StringBuilder();
128         for (int i = 0; i < what.length; i++) {
129             builder.append(what[i]);
130             if (i + 1 != what.length) {
131                 builder.append(glue);
132             }
133         }
134         return builder.toString();
135     }
136 
137     /**
138      * a str_repeat function.
139      * 
140      * @param toBeRepeated
141      *            the string to repeat
142      * @param numTimes
143      *            how many times to concantenate the string
144      * @return the repeated string.
145      */
146     protected static String repeat(final String toBeRepeated, final int numTimes) {
147         final StringBuilder builder = new StringBuilder();
148 
149         for (int i = 0; i < numTimes; i++) {
150             builder.append(toBeRepeated);
151         }
152         return builder.toString();
153     }
154 
155     /**
156      * Splits a string with the help of a given char.
157      * 
158      * @return an array of elements
159      * @param splitter
160      *            the separator char
161      * @param toBeSplitted
162      *            the string to be splitted
163      */
164     private static String[] explode(final char splitter, final String toBeSplitted) {
165         return toBeSplitted.split("\\" + splitter);
166     }
167 
168     /**
169      * Returns how many new lines are in the string.
170      * 
171      * @param toExamine
172      *            the string to look upon.
173      * @return the number of occurences of {@link NiceTable#NEWLINE} in the
174      *         string.
175      */
176     private static int numNewLines(final String toExamine) {
177         final char[] arr = toExamine.toCharArray();
178         int result = 0;
179         for (char ch : arr) {
180             if (AbstractTabularComponent.NEWLINE.equals(new String(new char[] {
181                 ch
182             }))) {
183                 result++;
184             }
185         }
186         return result;
187     }
188 
189     /**
190      * Tells us whether the string contains newlines. it's important to note
191      * that only newlines within the string are important, not the newlines at
192      * the front or the end of the string.
193      * 
194      * @param toExamine
195      *            to be checked
196      * @return boolean if the string contains newlines.
197      */
198     public static boolean containsNewlines(final String toExamine) {
199         return toExamine.trim().contains(AbstractTabularComponent.NEWLINE);
200     }
201 
202     /**
203      * Creates a matrix according to the number of new lines given into the
204      * method.
205      * 
206      * @return the matrix.
207      * @param data
208      *            an array of row data
209      */
210     public static String[][] createMatrix(final String[] data) {
211         int maxNewLines = 0;
212         for (final String col : data) {
213             maxNewLines = Math.max(maxNewLines, Util.numNewLines(col));
214         }
215         final String[][] matrix = new String[maxNewLines + 1][data.length];
216         for (int col = 0; col < data.length; col++) {
217             final String[] exploded = Util.explode('\n', data[col]);
218             for (int row = 0; row < maxNewLines + 1; row++) {
219                 if (exploded.length > row) {
220                     matrix[row][col] = exploded[row];
221                 } else {
222                     matrix[row][col] = "";
223                 }
224             }
225         }
226 
227         return matrix;
228 
229     }
230 
231 }