View Javadoc

1   package net.sourceforge.argval.utils;
2   
3   
4   import java.util.ArrayList;
5   import java.util.Collection;
6   import java.util.HashSet;
7   import java.util.List;
8   import java.util.Set;
9   import java.util.StringTokenizer;
10  
11  import net.sourceforge.argval.lang.SystemConstants;
12  
13  
14  
15  /**
16   * Utility class for String related functions. 
17   */
18  public final class StringUtil {
19      public final static String LINE_SEPARATOR = System.getProperty(SystemConstants.LINE_SEPARATOR); 
20  
21  
22      /** The class only contains static methods. */
23      private StringUtil() {
24      }
25  
26      
27      /** 
28       * Trims spaces on the outside of the text and in the case of an empty 
29       * string <code>null</code> is returned.
30       * 
31       * @param  text  The text to polish.
32       * @return  The text without leading and trailing spaces that remain or 
33       *          <code>null</code>, when no characters are left.
34       */
35      public static String polish(String text) {
36          if (text == null) {
37              return null;
38          }
39          text = text.trim();
40          if (text.length() == 0) {
41              return null;
42          }
43          return text;
44      }
45  
46  
47      /**
48       * Returns the polished text, see {@link #polish(String)}, or when that leads to 
49       * <code>null</code> the default text.
50       * 
51       * @param  text  The text to polish.
52       * @param  defaultText  The default text to return, if the polished text, result 
53       *                      in to <code>null</code>.
54       * @return  The polished text, or when that's equal to <code>null</code>, the default text.
55       */
56      public static String polish(String text, String defaultText) {
57          text = polish(text);
58          return (text != null) ? text : defaultText; 
59      }
60      
61      
62      /**
63       * Converts the text into separated String instance, based on the separator.
64       * <p>
65       * Example:
66       * <code>convertToSet("Winnie The Pooh;Piglet;Tigger;Rabbit", ";")</code> will return a Set instance
67       * containing the Strings:
68       * <ul>
69       *   <li><code>"Winnie The Pooh"</code></li>
70       *   <li><code>"Piglet"</code></li>
71       *   <li><code>"Tigger"</code></li>
72       *   <li><code>"Rabbit"</code></li>
73       * </ul>
74       * </p>
75       * 
76       * @param  text  The text to separate. 
77       * @param  separator  The separator String instance.
78       * @return  The Set containing the separated Strings.
79       */
80      public static Set<String> convertToSet(String text, String separator) {
81          return (Set<String>)convertToCollection(text, separator, new HashSet<String>());
82      }
83      public static Set<String> convertToSet(String text) {
84      	return convertToSet(text, null);
85      }
86  
87  
88      public static List<String> convertToList(String text, String separator) {
89          return (List<String>)convertToCollection(text, separator, new ArrayList<String>());
90      }
91      public static List<String> convertToList(String text) {
92      	return convertToList(text, null);
93      }
94  
95  
96  	private static Collection<String> convertToCollection(String text, String separator, Collection<String> coll) {
97  		if (text != null) {
98  	        StringTokenizer stringTokenizer = (separator != null) 
99  	        		? new StringTokenizer(text, separator)
100 	        		: new StringTokenizer(text);
101 	        while (stringTokenizer.hasMoreTokens()) {
102 	        	coll.add(polish(stringTokenizer.nextToken()));
103 	        }
104         }
105 		return coll;
106 	}
107 
108     
109     /**
110      * Removes the character instances from the given text.
111      * <p>
112      * Example: 
113      * <code>removeCharacter("ISBN: 0-596-10094-9", '-')</code> will return <code>"ISBN: 0596100949"</code>
114      * </p>
115      * 
116      * @param  text  The text to filter. 
117      * @param  character  The character to remove.
118      * @return  Returns the text, with out all the instance of the given charater.
119      */
120     public static String removeCharacter(String text, char character) {
121         if (text == null) {
122             return text;
123         }
124         if (text.indexOf(character) < 0) {
125             return text;
126         }
127         
128         StringTokenizer tokenizer = new StringTokenizer(text, Character.toString(character));
129         StringBuffer strBuf = new StringBuffer();
130         while (tokenizer.hasMoreTokens()) {
131             strBuf.append(tokenizer.nextToken());
132         }
133         return strBuf.toString();
134     }
135 
136 
137     /**
138      * Removes all the given characters from the given text.
139      * <p>
140      * Exmaple:
141      * <code>removeCharacter("ISBN: 0-596-10094-9", new char[] { '-', ':' } )</code> will return <code>"ISBN 0596100949"</code>
142      * </p>
143      *   
144      * @param  text  The text to filter. 
145      * @param  character  The character to remove.
146      * @return  The clean text, which doesn;t contain any of the given characters any more.
147      */
148     public static String removeCharacter(String text, char[] characterArray) {
149         if (text == null || characterArray == null || characterArray.length == 0) {
150             return text;
151         }
152         for (int index = 0; index < characterArray.length; index++) {
153             text = removeCharacter(text, characterArray[index]);
154         }
155         return text;
156     }
157 
158 
159     /**
160      * Cleans up the text, by removing the toRemove instance(s).
161      * <p>
162      * This can be used to remove unwanted Strings from a text.
163      * <pre>
164      *   // Remove "ISBN:" from the text
165      *   StringUtil.remove("ISBN: 0-596-10094-9", "ISBN:");
166      * </pre>
167      * This will return the text <code>" 0-596-10094-9"</code>.
168      * </p>
169      * 
170      * @param  text  The text, which needs to be clean up.
171      * @param  toRemove  The character sequence which needs to be removed, from the given text.
172      * @return  A new text, without the 'toRemove' string instances.
173      */
174     public static String remove(String text, String toRemove) {
175         StringBuffer strBuf = new StringBuffer();
176         StringTokenizer tokenizer = new StringTokenizer(text, toRemove);
177         while (tokenizer.hasMoreTokens()) {
178             strBuf.append(tokenizer.nextToken());
179         }
180         return strBuf.toString();
181     }
182     
183     
184     /**
185      * Returns the class name, without the package prefix.
186      * @param  clazz  The class, from which to get it's name.
187      * @return  The class name.
188      */
189     public static String getClassName(Class<?> clazz) {
190         // FIXME [20071210 tv]: Remove circular dependency.
191 //        ArgumentValidation argVal = new ArgumentValidation();
192 //        argVal.isValidWhenNotNull("clazz", clazz);
193 //        if (argVal.containsIllegalArgument()) throw new IllegalArgumentException(argVal.getMessage());
194         
195         
196         String className = clazz.getName();
197         return className.substring(className.lastIndexOf(".") + 1);
198     }
199     /**
200      * Returns the package name, without the class name.
201      * @param clazz  The class, from which to get it's package name.
202      * @return  The package name.
203      */
204     public static String getPackageName(Class<?> clazz) {
205         // FIXME [20071210 tv]: Remove circular dependency.
206 //        ArgumentValidation argVal = new ArgumentValidation();
207 //        argVal.isValidWhenNotNull("clazz", clazz);
208 //        if (argVal.containsIllegalArgument()) throw new IllegalArgumentException(argVal.getMessage());
209         
210         String className = clazz.getName();
211         return className.substring(0, className.lastIndexOf("."));
212     }
213 
214     
215     public static int charCount(String text, char ch) {
216         if (text.indexOf(ch) < 0) {
217             return 0;
218         }
219         return getCharIndexList(text, ch).size();
220     }
221     
222     
223     public static List<Integer> getCharIndexList(String text, char ch) {
224         ArrayList<Integer> indexList = new ArrayList<Integer>();
225         if (text.indexOf(ch) < 0) {
226             return indexList;
227         }
228 
229         int index = text.indexOf(ch);
230         while (! (index < 0)) {
231             indexList.add(new Integer(index));
232             index = text.indexOf(ch, index + 1);
233         }
234         return indexList;
235     }
236     
237 
238     /**
239      * Converts a byte array into a hex string.
240      * @param  byteArray  The bytes.
241      * @return  The hex representation of the bytes.
242      */
243     public static String toHexString(byte[] byteArray) {
244         StringBuffer strBuf = new StringBuffer();
245         for (int index = 0; index < byteArray.length; index++) {
246             String hexStr = Integer.toHexString(0xFF & byteArray[index]);
247             if (hexStr.length() == 1) {
248                 strBuf.append("0");
249             }
250             strBuf.append(hexStr);
251         }
252         return strBuf.toString();
253     }
254     
255     
256     public static List<String> toHexList(byte[] byteArray) {
257         List<String> hexList = new ArrayList<String>();
258         for (int index = 0; index < byteArray.length; index++) {
259             String hexStr = Integer.toHexString(0xFF & byteArray[index]);
260             hexList.add((hexStr.length() == 1) ? "0" + hexStr : hexStr);
261         }
262         return hexList;
263     }
264     
265     
266     public static List<String> toHexList(String hexStr) {
267         if (hexStr.length() % 2 != 0) {
268             throw new IllegalArgumentException("");
269         }
270         
271         List<String> hexList = new ArrayList<String>();
272         for (int index = 0; index < hexStr.length() / 2; index++) {
273             hexList.add(hexStr.substring(index * 2, index * 2 + 2));
274         }
275         return hexList;
276     }
277     
278 }