1    package com.instantbank.collections.util;
2    
3    import java.io.BufferedReader;
4    import java.io.FileReader;
5    import java.util.Calendar;
6    import java.util.StringTokenizer;
7    import javax.servlet.http.HttpServletRequest;
8    
9    /**
10    * Title:        Strings<br>
11    * Description:  Picks up String handling where jdk1.2.2 left off
12    *
13    * @author Tracy Milburn<br>
14    * @version 1.0
15    */
16   
17   public class Strings {
18   
19     private Strings() { }
20   
21   
22     /**
23      * Implementation of trimming the right side of a String
24      *
25      * @param str Description of the Parameter
26      * @return Description of the Return Value
27      */
28     public static String rTrim(String str) {
29       int i = str.length() - 1;
30       while(Character.isWhitespace(str.charAt(i)) && i > 0) {
31         i--;
32       }
33       return new String(str.substring(0, i + 1));
34     }
35   
36   
37     /**
38      * Takes a date and the format it's in, and transforms it to another format
39      *
40      * @param dateStr Description of the Parameter
41      * @param inPic Description of the Parameter
42      * @param outPic Description of the Parameter
43      * @param delimeter Description of the Parameter
44      * @return Description of the Return Value
45      */
46     public static String transformDate(String dateStr, String inPic, String outPic,
47                                        String delimeter) {
48   
49       String year = null;
50   
51       String month = null;
52   
53       String day = null;
54   
55       String outStr = null;
56   
57       // Determine the in format and pick out the day, month & year
58       if("YYYYMMDD".equals(inPic)) {
59         year = dateStr.substring(0, 4);
60         month = dateStr.substring(4, 6);
61         day = dateStr.substring(6, 8);
62       }
63   
64       // Now determine the out format
65       if("MMDDYY".equals(outPic)) {
66         outStr = month + delimeter + day + delimeter;
67         if(year.length() > 3) {
68           year = year.substring(2, 4);
69         }
70         outStr += year;
71       }
72   
73       return outStr;
74     }
75   
76   
77     /**
78      * Returns a short version of today's date
79      *
80      * @return The shortDate value
81      */
82     public static String getShortDate() {
83       Calendar cal = Calendar.getInstance();
84   
85       StringBuffer currDate = new StringBuffer(10);
86       if((cal.get(Calendar.MONTH) + 1) < 10) {
87         currDate.append('0');
88       }
89       currDate.append(String.valueOf(cal.get(Calendar.MONTH) + 1) + '/');
90       if(cal.get(Calendar.DAY_OF_MONTH) < 10) {
91         currDate.append('0');
92       }
93       currDate.append(String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + '/');
94       currDate.append(String.valueOf(cal.get(Calendar.YEAR)));
95   
96       return currDate.toString();
97     }
98   
99   
100    /**
101     * Returns a short version of the current time
102     *
103     * @return The shortTime value
104     */
105    public static String getShortTime() {
106      Calendar cal = Calendar.getInstance();
107  
108      StringBuffer currDate = new StringBuffer(8);
109      int hour = cal.get(Calendar.HOUR_OF_DAY);
110      int min = cal.get(Calendar.MINUTE);
111      int sec = cal.get(Calendar.SECOND);
112      int milli = cal.get(Calendar.MILLISECOND);
113  
114      if(hour < 10) {
115        currDate.append('0');
116      }
117      currDate.append(String.valueOf(hour) + ':');
118  
119      if(min < 10) {
120        currDate.append('0');
121      }
122      currDate.append(String.valueOf(min) + ':');
123  
124      if(sec < 10) {
125        currDate.append('0');
126      }
127      currDate.append(String.valueOf(sec) + ':');
128  
129      currDate.append(String.valueOf(milli));
130  
131      return currDate.toString();
132    }
133  
134  
135    /**
136     * Breaks lines at every chars_per_line character
137     *
138     * @param in Description of the Parameter
139     * @param chars_per_line Description of the Parameter
140     * @return Description of the Return Value
141     */
142    public static String line_break(String in, int chars_per_line) {
143      StringBuffer ret = new StringBuffer(in.length() + chars_per_line * 2);
144      for(int i = 0; i < in.length(); i++) {
145        if(i > 0) {
146          if((i % chars_per_line) == 0) {
147            ret.append("\n");
148          }
149        }
150        ret.append(in.charAt(i));
151      }
152      return ret.toString();
153    }
154  
155  
156    public static String line_break(FileReader f, int chars_per_line) {
157  
158      String ret = null;
159  
160      BufferedReader br = new BufferedReader(f);
161      try {
162        ret = br.readLine();
163      }
164      catch(Exception e) {
165        System.out.println("Error reading file: " + e);
166      }
167      return line_break(ret, chars_per_line);
168    }
169  
170  
171    public static boolean isWhiteSpace(String str) {
172      for(int i = 0; i < str.length(); i++) {
173        if(!Character.isWhitespace(str.charAt(i))) {
174          return false;
175        }
176      }
177      return true;
178    }
179  
180  
181    /**
182     * Just creates and fills a character array of length qty with char ch
183     *
184     * @param ch Description of the Parameter
185     * @param qty Description of the Parameter
186     * @return Description of the Return Value
187     */
188    private static char[] createCharArray(char ch, int qty) {
189      char[] ca = new char[qty];
190      for(int i = 0; i < qty; i++) {
191        ca[i] = ch;
192      }
193      return ca;
194    }
195  
196  
197    /**
198     * This method returns a String that is the original string padded to the
199     * left by a certain # of characters
200     *
201     * @param str Description of the Parameter
202     * @param ch Description of the Parameter
203     * @param qty Description of the Parameter
204     * @return Description of the Return Value
205     */
206    public static String padLeft(String str, char ch, int qty) {
207  
208      return new StringBuffer(str.length() + qty).append(createCharArray(ch, qty)).append(str).toString();
209    }
210  
211  
212    /**
213     * This method returns a String that is the original string padded to the
214     * right by a certain # of characters
215     *
216     * @param str Description of the Parameter
217     * @param ch Description of the Parameter
218     * @param qty Description of the Parameter
219     * @return Description of the Return Value
220     */
221    public static String padRight(String str, char ch, int qty) {
222  
223      return new StringBuffer(str.length() + qty).append(str).append(createCharArray(ch, qty)).toString();
224    }
225  
226  
227    /**
228     * This method returns a String that is the original string padded to the
229     * left by lch and padded to the right by rch
230     *
231     * @param str Description of the Parameter
232     * @param lch Description of the Parameter
233     * @param lqty Description of the Parameter
234     * @param rch Description of the Parameter
235     * @param rqty Description of the Parameter
236     * @return Description of the Return Value
237     */
238    public static String pad(String str, char lch, int lqty, char rch, int rqty) {
239  
240      return new StringBuffer(str.length() + lqty + rqty).append(padLeft(str, lch, lqty))
241        .append(padRight("", rch, rqty)).toString();
242    }
243  
244  
245    /**
246     * This method makes the string fit into a certain width, left-justified and padded to right with spaces
247     *
248     * @param str Description of the Parameter
249     * @param ch Description of the Parameter
250     * @param width Description of the Parameter
251     * @return Description of the Return Value
252     */
253    public static String fitLeft(String str, char ch, int width) {
254  
255      if(str.length() > width) {
256        return str.substring(0, width);
257      }  // Concatenate to force it to fit
258  
259      return (padRight(str, ch, width - str.length()));
260    }
261  
262  
263    /**
264     * This method makes the string fit into a certain width, left-justified and padded to right with spaces
265     *
266     * @param str Description of the Parameter
267     * @param width Description of the Parameter
268     * @return Description of the Return Value
269     */
270    public static String fitLeft(String str, int width) {
271      return (fitLeft(str, ' ', width));
272    }
273  
274  
275    /**
276     * This method makes the string fit into a certain width, right-justified and
277     * padded to left with some character
278     *
279     * @param str Description of the Parameter
280     * @param ch Description of the Parameter
281     * @param width Description of the Parameter
282     * @return Description of the Return Value
283     */
284    public static String fitRight(String str, char ch, int width) {
285  
286      if(str.length() > width) {
287        return str.substring(0, width);
288      }  // Concatenate to force it to fit
289  
290      return (padLeft(str, ch, width - str.length()));
291    }
292  
293  
294    /**
295     * This method makes the string fit into a certain width, right-justified and
296     * padded to left with spaces
297     *
298     * @param str Description of the Parameter
299     * @param width Description of the Parameter
300     * @return Description of the Return Value
301     */
302    public static String fitRight(String str, int width) {
303      return (fitRight(str, ' ', width));
304    }
305  
306  
307    /**
308     * Often-used method for retrieving a value from an http request, and throwing an exception
309     * if it doesn't exist
310     *
311     * @param req Description of the Parameter
312     * @param id Description of the Parameter
313     * @return The requiredHttpString value
314     * @throws Exception Description of the Exception
315     */
316    public static final String getRequiredHttpString(HttpServletRequest req, String id) throws Exception {
317  
318      String str = req.getParameter(id);
319      if(str == null || str.length() == 0) {
320        throw new Exception("Missing required string parameter:  " + id);
321      }
322  
323      return str;
324    }
325  
326  
327    /**
328     * Often-used method for retrieving an int from an http request, and throwing an exception
329     * if it doesn't exist
330     *
331     * @param req Description of the Parameter
332     * @param id Description of the Parameter
333     * @return The requiredHttpInt value
334     * @throws Exception Description of the Exception
335     */
336    public static final int getRequiredHttpInt(HttpServletRequest req, String id) throws Exception {
337  
338      return Integer.parseInt(getRequiredHttpString(req, id));
339    }
340  
341  
342    /**
343     * Strip all occurences of a character from a string
344     *
345     * @param s Description of the Parameter
346     * @param c Description of the Parameter
347     * @return Description of the Return Value
348     */
349    public static final String strip(String s, char c) {
350  
351      if(s == null) {
352        return s;
353      }
354  
355      int len = s.length();
356      StringBuffer sb = new StringBuffer(len);
357      for(int i = 0; i < len; i++) {
358        char ch = s.charAt(i);
359        if(ch != c) {
360          sb.append(ch);
361        }
362      }
363      return sb.toString();
364    }
365  
366  
367    /**
368     * Remove the ending string from another string
369     *
370     * @param str Description of the Parameter
371     * @param toClip Description of the Parameter
372     * @return Description of the Return Value
373     */
374    public static final String rClip(String str, String toClip) {
375  
376      if(str == null) {
377        return null;
378      }
379      if(!str.endsWith(toClip) || toClip.length() > str.length()) {
380        return str;
381      }
382  
383      String returnStr = null;
384  
385      int idx = str.lastIndexOf(toClip);
386      if(idx != -1) {
387        returnStr = str.substring(0, idx);
388      }
389  
390      return returnStr;
391    }
392  
393  
394    /**
395     * Appends an element to a string
396     *
397     * @param source Description of the Parameter
398     * @param token Description of the Parameter
399     * @return Description of the Return Value
400     */
401    public static final String appendToken(String source, String token) {
402  
403      if(source == null || source.length() == 0) {
404        return token;
405      }
406  
407      return source + ';' + token;
408    }
409  
410  
411    /**
412     * Appends an element to a string
413     *
414     * @param tokens Description of the Parameter
415     * @return The lastToken value
416     */
417    public static final String getLastToken(String tokens) {
418  
419      if(tokens == null || tokens.length() == 0) {
420        return tokens;
421      }
422  
423      int idx = tokens.lastIndexOf(";");
424      if(idx == -1) {
425        return tokens;
426      }
427      else {
428        return tokens.substring(idx + 1);
429      }
430    }
431  
432  
433    /**
434     * Appends a page to the history path of the webcenter
435     *
436     * @param history Description of the Parameter
437     * @param currentPage Description of the Parameter
438     * @return Description of the Return Value
439     */
440    public static final String appendWebCenterHistory(String history, String currentPage) {
441  
442      if(history == null || history.length() == 0) {
443        return currentPage;
444      }
445  
446      // Don't add the search results page to the history; we never print that
447      //  except on the seach results page itself
448      // If already there, don't add it
449      if("SearchResults".equals(currentPage)) {
450        return history;
451      }
452  
453      StringTokenizer st = new StringTokenizer(history, ";");
454      while(st.hasMoreTokens()) {
455        String next = st.nextToken();
456        if(next != null && next.equals(currentPage)) {
457          return history;
458        }
459      }
460  
461      return appendToken(history, currentPage);
462    }
463  
464  
465    /**
466     * return T or F string of a boolean
467     *
468     * @param tf Description of the Parameter
469     * @return Description of the Return Value
470     */
471    public static final String booleanToTFString(boolean tf) {
472      if(tf) {
473        return "T";
474      }
475      else {
476        return "F";
477      }
478    }
479  
480  
481    /**
482     * return boolean of TF string
483     *
484     * @param tf Description of the Parameter
485     * @return Description of the Return Value
486     */
487    public static final boolean tfStringToBoolean(String tf) {
488      if("T".equalsIgnoreCase(tf)) {
489        return true;
490      }
491      else {
492        return false;
493      }
494    }
495  
496  
497    /**
498     * Remove all occurences of toRemove from str.  I can't believe this isn't
499     * in the String class!
500     *
501     * @param src Description of the Parameter
502     * @param toRemove Description of the Parameter
503     * @return Description of the Return Value
504     */
505    public static final String remove(String src, String toRemove) {
506  
507      int idx = src.indexOf(toRemove);
508      while(idx != -1) {
509        src = new String(src.substring(0, idx) + src.substring(idx + toRemove.length(),
510          src.length()));
511        idx = src.indexOf(toRemove);
512      }
513  
514      return src;
515    }
516  
517  
518    /**
519     * Replace a string with another string
520     *
521     * @param originalString Description of the Parameter
522     * @param searchString Description of the Parameter
523     * @param replacementString Description of the Parameter
524     * @return Description of the Return Value
525     */
526    public static final String replaceAll(String originalString, String searchString,
527                                          String replacementString) {
528      int index = -1;
529      int lastIndex = 0;
530      String tempString = originalString;
531      StringBuffer sb = new StringBuffer();
532  
533      while((index = tempString.indexOf(searchString, lastIndex)) != -1) {
534        sb.append(tempString.substring(lastIndex, index));
535        sb.append(replacementString);
536        lastIndex = index + searchString.length();
537      }
538      sb.append(tempString.substring(lastIndex, tempString.length()));
539      return sb.toString();
540    }
541  
542  
543    public static void main(String[] args) {
544      System.out.println(Strings.fitRight("123", 7));
545      System.exit(1);
546    }
547  }
548