001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements.  See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership.  The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the
007     * "License"); you may not use this file except in compliance
008     * with the License.  You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    
019    package org.apache.hadoop.util;
020    
021    import java.io.PrintWriter;
022    import java.io.StringWriter;
023    import java.net.URI;
024    import java.net.URISyntaxException;
025    import java.text.DateFormat;
026    import java.util.ArrayList;
027    import java.util.Arrays;
028    import java.util.Collection;
029    import java.util.Date;
030    import java.util.Iterator;
031    import java.util.List;
032    import java.util.Locale;
033    import java.util.Map;
034    import java.util.StringTokenizer;
035    import java.util.regex.Matcher;
036    import java.util.regex.Pattern;
037    
038    import org.apache.commons.lang.SystemUtils;
039    import org.apache.hadoop.classification.InterfaceAudience;
040    import org.apache.hadoop.classification.InterfaceStability;
041    import org.apache.hadoop.fs.Path;
042    import org.apache.hadoop.net.NetUtils;
043    
044    import com.google.common.net.InetAddresses;
045    
046    /**
047     * General string utils
048     */
049    @InterfaceAudience.Private
050    @InterfaceStability.Unstable
051    public class StringUtils {
052    
053      /**
054       * Priority of the StringUtils shutdown hook.
055       */
056      public static final int SHUTDOWN_HOOK_PRIORITY = 0;
057    
058      /**
059       * Shell environment variables: $ followed by one letter or _ followed by
060       * multiple letters, numbers, or underscores.  The group captures the
061       * environment variable name without the leading $.
062       */
063      public static final Pattern SHELL_ENV_VAR_PATTERN =
064        Pattern.compile("\\$([A-Za-z_]{1}[A-Za-z0-9_]*)");
065    
066      /**
067       * Windows environment variables: surrounded by %.  The group captures the
068       * environment variable name without the leading and trailing %.
069       */
070      public static final Pattern WIN_ENV_VAR_PATTERN = Pattern.compile("%(.*?)%");
071    
072      /**
073       * Regular expression that matches and captures environment variable names
074       * according to platform-specific rules.
075       */
076      public static final Pattern ENV_VAR_PATTERN = Shell.WINDOWS ?
077        WIN_ENV_VAR_PATTERN : SHELL_ENV_VAR_PATTERN;
078    
079      /**
080       * Make a string representation of the exception.
081       * @param e The exception to stringify
082       * @return A string with exception name and call stack.
083       */
084      public static String stringifyException(Throwable e) {
085        StringWriter stm = new StringWriter();
086        PrintWriter wrt = new PrintWriter(stm);
087        e.printStackTrace(wrt);
088        wrt.close();
089        return stm.toString();
090      }
091      
092      /**
093       * Given a full hostname, return the word upto the first dot.
094       * @param fullHostname the full hostname
095       * @return the hostname to the first dot
096       */
097      public static String simpleHostname(String fullHostname) {
098        if (InetAddresses.isInetAddress(fullHostname)) {
099          return fullHostname;
100        }
101        int offset = fullHostname.indexOf('.');
102        if (offset != -1) {
103          return fullHostname.substring(0, offset);
104        }
105        return fullHostname;
106      }
107      
108      /**
109       * Given an integer, return a string that is in an approximate, but human 
110       * readable format. 
111       * @param number the number to format
112       * @return a human readable form of the integer
113       *
114       * @deprecated use {@link TraditionalBinaryPrefix#long2String(long, String, int)}.
115       */
116      @Deprecated
117      public static String humanReadableInt(long number) {
118        return TraditionalBinaryPrefix.long2String(number, "", 1);
119      }
120    
121      /** The same as String.format(Locale.ENGLISH, format, objects). */
122      public static String format(final String format, final Object... objects) {
123        return String.format(Locale.ENGLISH, format, objects);
124      }
125    
126      /**
127       * Format a percentage for presentation to the user.
128       * @param fraction the percentage as a fraction, e.g. 0.1 = 10%
129       * @param decimalPlaces the number of decimal places
130       * @return a string representation of the percentage
131       */
132      public static String formatPercent(double fraction, int decimalPlaces) {
133        return format("%." + decimalPlaces + "f%%", fraction*100);
134      }
135      
136      /**
137       * Given an array of strings, return a comma-separated list of its elements.
138       * @param strs Array of strings
139       * @return Empty string if strs.length is 0, comma separated list of strings
140       * otherwise
141       */
142      
143      public static String arrayToString(String[] strs) {
144        if (strs.length == 0) { return ""; }
145        StringBuilder sbuf = new StringBuilder();
146        sbuf.append(strs[0]);
147        for (int idx = 1; idx < strs.length; idx++) {
148          sbuf.append(",");
149          sbuf.append(strs[idx]);
150        }
151        return sbuf.toString();
152      }
153    
154      /**
155       * Given an array of bytes it will convert the bytes to a hex string
156       * representation of the bytes
157       * @param bytes
158       * @param start start index, inclusively
159       * @param end end index, exclusively
160       * @return hex string representation of the byte array
161       */
162      public static String byteToHexString(byte[] bytes, int start, int end) {
163        if (bytes == null) {
164          throw new IllegalArgumentException("bytes == null");
165        }
166        StringBuilder s = new StringBuilder(); 
167        for(int i = start; i < end; i++) {
168          s.append(format("%02x", bytes[i]));
169        }
170        return s.toString();
171      }
172    
173      /** Same as byteToHexString(bytes, 0, bytes.length). */
174      public static String byteToHexString(byte bytes[]) {
175        return byteToHexString(bytes, 0, bytes.length);
176      }
177    
178      /**
179       * Given a hexstring this will return the byte array corresponding to the
180       * string
181       * @param hex the hex String array
182       * @return a byte array that is a hex string representation of the given
183       *         string. The size of the byte array is therefore hex.length/2
184       */
185      public static byte[] hexStringToByte(String hex) {
186        byte[] bts = new byte[hex.length() / 2];
187        for (int i = 0; i < bts.length; i++) {
188          bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
189        }
190        return bts;
191      }
192      /**
193       * 
194       * @param uris
195       */
196      public static String uriToString(URI[] uris){
197        if (uris == null) {
198          return null;
199        }
200        StringBuilder ret = new StringBuilder(uris[0].toString());
201        for(int i = 1; i < uris.length;i++){
202          ret.append(",");
203          ret.append(uris[i].toString());
204        }
205        return ret.toString();
206      }
207      
208      /**
209       * @param str
210       *          The string array to be parsed into an URI array.
211       * @return <tt>null</tt> if str is <tt>null</tt>, else the URI array
212       *         equivalent to str.
213       * @throws IllegalArgumentException
214       *           If any string in str violates RFC&nbsp;2396.
215       */
216      public static URI[] stringToURI(String[] str){
217        if (str == null) 
218          return null;
219        URI[] uris = new URI[str.length];
220        for (int i = 0; i < str.length;i++){
221          try{
222            uris[i] = new URI(str[i]);
223          }catch(URISyntaxException ur){
224            throw new IllegalArgumentException(
225                "Failed to create uri for " + str[i], ur);
226          }
227        }
228        return uris;
229      }
230      
231      /**
232       * 
233       * @param str
234       */
235      public static Path[] stringToPath(String[] str){
236        if (str == null) {
237          return null;
238        }
239        Path[] p = new Path[str.length];
240        for (int i = 0; i < str.length;i++){
241          p[i] = new Path(str[i]);
242        }
243        return p;
244      }
245      /**
246       * 
247       * Given a finish and start time in long milliseconds, returns a 
248       * String in the format Xhrs, Ymins, Z sec, for the time difference between two times. 
249       * If finish time comes before start time then negative valeus of X, Y and Z wil return. 
250       * 
251       * @param finishTime finish time
252       * @param startTime start time
253       */
254      public static String formatTimeDiff(long finishTime, long startTime){
255        long timeDiff = finishTime - startTime; 
256        return formatTime(timeDiff); 
257      }
258      
259      /**
260       * 
261       * Given the time in long milliseconds, returns a 
262       * String in the format Xhrs, Ymins, Z sec. 
263       * 
264       * @param timeDiff The time difference to format
265       */
266      public static String formatTime(long timeDiff){
267        StringBuilder buf = new StringBuilder();
268        long hours = timeDiff / (60*60*1000);
269        long rem = (timeDiff % (60*60*1000));
270        long minutes =  rem / (60*1000);
271        rem = rem % (60*1000);
272        long seconds = rem / 1000;
273        
274        if (hours != 0){
275          buf.append(hours);
276          buf.append("hrs, ");
277        }
278        if (minutes != 0){
279          buf.append(minutes);
280          buf.append("mins, ");
281        }
282        // return "0sec if no difference
283        buf.append(seconds);
284        buf.append("sec");
285        return buf.toString(); 
286      }
287      /**
288       * Formats time in ms and appends difference (finishTime - startTime) 
289       * as returned by formatTimeDiff().
290       * If finish time is 0, empty string is returned, if start time is 0 
291       * then difference is not appended to return value. 
292       * @param dateFormat date format to use
293       * @param finishTime fnish time
294       * @param startTime start time
295       * @return formatted value. 
296       */
297      public static String getFormattedTimeWithDiff(DateFormat dateFormat, 
298                                                    long finishTime, long startTime){
299        StringBuilder buf = new StringBuilder();
300        if (0 != finishTime) {
301          buf.append(dateFormat.format(new Date(finishTime)));
302          if (0 != startTime){
303            buf.append(" (" + formatTimeDiff(finishTime , startTime) + ")");
304          }
305        }
306        return buf.toString();
307      }
308      
309      /**
310       * Returns an arraylist of strings.
311       * @param str the comma seperated string values
312       * @return the arraylist of the comma seperated string values
313       */
314      public static String[] getStrings(String str){
315        Collection<String> values = getStringCollection(str);
316        if(values.size() == 0) {
317          return null;
318        }
319        return values.toArray(new String[values.size()]);
320      }
321    
322      /**
323       * Returns a collection of strings.
324       * @param str comma seperated string values
325       * @return an <code>ArrayList</code> of string values
326       */
327      public static Collection<String> getStringCollection(String str){
328        List<String> values = new ArrayList<String>();
329        if (str == null)
330          return values;
331        StringTokenizer tokenizer = new StringTokenizer (str,",");
332        values = new ArrayList<String>();
333        while (tokenizer.hasMoreTokens()) {
334          values.add(tokenizer.nextToken());
335        }
336        return values;
337      }
338    
339      /**
340       * Splits a comma separated value <code>String</code>, trimming leading and trailing whitespace on each value.
341       * @param str a comma separated <String> with values
342       * @return a <code>Collection</code> of <code>String</code> values
343       */
344      public static Collection<String> getTrimmedStringCollection(String str){
345        return new ArrayList<String>(
346          Arrays.asList(getTrimmedStrings(str)));
347      }
348      
349      /**
350       * Splits a comma separated value <code>String</code>, trimming leading and trailing whitespace on each value.
351       * @param str a comma separated <String> with values
352       * @return an array of <code>String</code> values
353       */
354      public static String[] getTrimmedStrings(String str){
355        if (null == str || str.trim().isEmpty()) {
356          return emptyStringArray;
357        }
358    
359        return str.trim().split("\\s*,\\s*");
360      }
361    
362      final public static String[] emptyStringArray = {};
363      final public static char COMMA = ',';
364      final public static String COMMA_STR = ",";
365      final public static char ESCAPE_CHAR = '\\';
366      
367      /**
368       * Split a string using the default separator
369       * @param str a string that may have escaped separator
370       * @return an array of strings
371       */
372      public static String[] split(String str) {
373        return split(str, ESCAPE_CHAR, COMMA);
374      }
375      
376      /**
377       * Split a string using the given separator
378       * @param str a string that may have escaped separator
379       * @param escapeChar a char that be used to escape the separator
380       * @param separator a separator char
381       * @return an array of strings
382       */
383      public static String[] split(
384          String str, char escapeChar, char separator) {
385        if (str==null) {
386          return null;
387        }
388        ArrayList<String> strList = new ArrayList<String>();
389        StringBuilder split = new StringBuilder();
390        int index = 0;
391        while ((index = findNext(str, separator, escapeChar, index, split)) >= 0) {
392          ++index; // move over the separator for next search
393          strList.add(split.toString());
394          split.setLength(0); // reset the buffer 
395        }
396        strList.add(split.toString());
397        // remove trailing empty split(s)
398        int last = strList.size(); // last split
399        while (--last>=0 && "".equals(strList.get(last))) {
400          strList.remove(last);
401        }
402        return strList.toArray(new String[strList.size()]);
403      }
404    
405      /**
406       * Split a string using the given separator, with no escaping performed.
407       * @param str a string to be split. Note that this may not be null.
408       * @param separator a separator char
409       * @return an array of strings
410       */
411      public static String[] split(
412          String str, char separator) {
413        // String.split returns a single empty result for splitting the empty
414        // string.
415        if (str.isEmpty()) {
416          return new String[]{""};
417        }
418        ArrayList<String> strList = new ArrayList<String>();
419        int startIndex = 0;
420        int nextIndex = 0;
421        while ((nextIndex = str.indexOf((int)separator, startIndex)) != -1) {
422          strList.add(str.substring(startIndex, nextIndex));
423          startIndex = nextIndex + 1;
424        }
425        strList.add(str.substring(startIndex));
426        // remove trailing empty split(s)
427        int last = strList.size(); // last split
428        while (--last>=0 && "".equals(strList.get(last))) {
429          strList.remove(last);
430        }
431        return strList.toArray(new String[strList.size()]);
432      }
433      
434      /**
435       * Finds the first occurrence of the separator character ignoring the escaped
436       * separators starting from the index. Note the substring between the index
437       * and the position of the separator is passed.
438       * @param str the source string
439       * @param separator the character to find
440       * @param escapeChar character used to escape
441       * @param start from where to search
442       * @param split used to pass back the extracted string
443       */
444      public static int findNext(String str, char separator, char escapeChar, 
445                                 int start, StringBuilder split) {
446        int numPreEscapes = 0;
447        for (int i = start; i < str.length(); i++) {
448          char curChar = str.charAt(i);
449          if (numPreEscapes == 0 && curChar == separator) { // separator 
450            return i;
451          } else {
452            split.append(curChar);
453            numPreEscapes = (curChar == escapeChar)
454                            ? (++numPreEscapes) % 2
455                            : 0;
456          }
457        }
458        return -1;
459      }
460      
461      /**
462       * Escape commas in the string using the default escape char
463       * @param str a string
464       * @return an escaped string
465       */
466      public static String escapeString(String str) {
467        return escapeString(str, ESCAPE_CHAR, COMMA);
468      }
469      
470      /**
471       * Escape <code>charToEscape</code> in the string 
472       * with the escape char <code>escapeChar</code>
473       * 
474       * @param str string
475       * @param escapeChar escape char
476       * @param charToEscape the char to be escaped
477       * @return an escaped string
478       */
479      public static String escapeString(
480          String str, char escapeChar, char charToEscape) {
481        return escapeString(str, escapeChar, new char[] {charToEscape});
482      }
483      
484      // check if the character array has the character 
485      private static boolean hasChar(char[] chars, char character) {
486        for (char target : chars) {
487          if (character == target) {
488            return true;
489          }
490        }
491        return false;
492      }
493      
494      /**
495       * @param charsToEscape array of characters to be escaped
496       */
497      public static String escapeString(String str, char escapeChar, 
498                                        char[] charsToEscape) {
499        if (str == null) {
500          return null;
501        }
502        StringBuilder result = new StringBuilder();
503        for (int i=0; i<str.length(); i++) {
504          char curChar = str.charAt(i);
505          if (curChar == escapeChar || hasChar(charsToEscape, curChar)) {
506            // special char
507            result.append(escapeChar);
508          }
509          result.append(curChar);
510        }
511        return result.toString();
512      }
513      
514      /**
515       * Unescape commas in the string using the default escape char
516       * @param str a string
517       * @return an unescaped string
518       */
519      public static String unEscapeString(String str) {
520        return unEscapeString(str, ESCAPE_CHAR, COMMA);
521      }
522      
523      /**
524       * Unescape <code>charToEscape</code> in the string 
525       * with the escape char <code>escapeChar</code>
526       * 
527       * @param str string
528       * @param escapeChar escape char
529       * @param charToEscape the escaped char
530       * @return an unescaped string
531       */
532      public static String unEscapeString(
533          String str, char escapeChar, char charToEscape) {
534        return unEscapeString(str, escapeChar, new char[] {charToEscape});
535      }
536      
537      /**
538       * @param charsToEscape array of characters to unescape
539       */
540      public static String unEscapeString(String str, char escapeChar, 
541                                          char[] charsToEscape) {
542        if (str == null) {
543          return null;
544        }
545        StringBuilder result = new StringBuilder(str.length());
546        boolean hasPreEscape = false;
547        for (int i=0; i<str.length(); i++) {
548          char curChar = str.charAt(i);
549          if (hasPreEscape) {
550            if (curChar != escapeChar && !hasChar(charsToEscape, curChar)) {
551              // no special char
552              throw new IllegalArgumentException("Illegal escaped string " + str + 
553                  " unescaped " + escapeChar + " at " + (i-1));
554            } 
555            // otherwise discard the escape char
556            result.append(curChar);
557            hasPreEscape = false;
558          } else {
559            if (hasChar(charsToEscape, curChar)) {
560              throw new IllegalArgumentException("Illegal escaped string " + str + 
561                  " unescaped " + curChar + " at " + i);
562            } else if (curChar == escapeChar) {
563              hasPreEscape = true;
564            } else {
565              result.append(curChar);
566            }
567          }
568        }
569        if (hasPreEscape ) {
570          throw new IllegalArgumentException("Illegal escaped string " + str + 
571              ", not expecting " + escapeChar + " in the end." );
572        }
573        return result.toString();
574      }
575      
576      /**
577       * Return a message for logging.
578       * @param prefix prefix keyword for the message
579       * @param msg content of the message
580       * @return a message for logging
581       */
582      private static String toStartupShutdownString(String prefix, String [] msg) {
583        StringBuilder b = new StringBuilder(prefix);
584        b.append("\n/************************************************************");
585        for(String s : msg)
586          b.append("\n" + prefix + s);
587        b.append("\n************************************************************/");
588        return b.toString();
589      }
590    
591      /**
592       * Print a log message for starting up and shutting down
593       * @param clazz the class of the server
594       * @param args arguments
595       * @param LOG the target log object
596       */
597      public static void startupShutdownMessage(Class<?> clazz, String[] args,
598                                         final org.apache.commons.logging.Log LOG) {
599        final String hostname = NetUtils.getHostname();
600        final String classname = clazz.getSimpleName();
601        LOG.info(
602            toStartupShutdownString("STARTUP_MSG: ", new String[] {
603                "Starting " + classname,
604                "  host = " + hostname,
605                "  args = " + Arrays.asList(args),
606                "  version = " + VersionInfo.getVersion(),
607                "  classpath = " + System.getProperty("java.class.path"),
608                "  build = " + VersionInfo.getUrl() + " -r "
609                             + VersionInfo.getRevision()  
610                             + "; compiled by '" + VersionInfo.getUser()
611                             + "' on " + VersionInfo.getDate(),
612                "  java = " + System.getProperty("java.version") }
613            )
614          );
615    
616        if (SystemUtils.IS_OS_UNIX) {
617          try {
618            SignalLogger.INSTANCE.register(LOG);
619          } catch (Throwable t) {
620            LOG.warn("failed to register any UNIX signal loggers: ", t);
621          }
622        }
623        ShutdownHookManager.get().addShutdownHook(
624          new Runnable() {
625            @Override
626            public void run() {
627              LOG.info(toStartupShutdownString("SHUTDOWN_MSG: ", new String[]{
628                "Shutting down " + classname + " at " + hostname}));
629            }
630          }, SHUTDOWN_HOOK_PRIORITY);
631    
632      }
633    
634      /**
635       * The traditional binary prefixes, kilo, mega, ..., exa,
636       * which can be represented by a 64-bit integer.
637       * TraditionalBinaryPrefix symbol are case insensitive. 
638       */
639      public static enum TraditionalBinaryPrefix {
640        KILO(10),
641        MEGA(KILO.bitShift + 10),
642        GIGA(MEGA.bitShift + 10),
643        TERA(GIGA.bitShift + 10),
644        PETA(TERA.bitShift + 10),
645        EXA (PETA.bitShift + 10);
646    
647        public final long value;
648        public final char symbol;
649        public final int bitShift;
650        public final long bitMask;
651    
652        private TraditionalBinaryPrefix(int bitShift) {
653          this.bitShift = bitShift;
654          this.value = 1L << bitShift;
655          this.bitMask = this.value - 1L;
656          this.symbol = toString().charAt(0);
657        }
658    
659        /**
660         * @return The TraditionalBinaryPrefix object corresponding to the symbol.
661         */
662        public static TraditionalBinaryPrefix valueOf(char symbol) {
663          symbol = Character.toUpperCase(symbol);
664          for(TraditionalBinaryPrefix prefix : TraditionalBinaryPrefix.values()) {
665            if (symbol == prefix.symbol) {
666              return prefix;
667            }
668          }
669          throw new IllegalArgumentException("Unknown symbol '" + symbol + "'");
670        }
671    
672        /**
673         * Convert a string to long.
674         * The input string is first be trimmed
675         * and then it is parsed with traditional binary prefix.
676         *
677         * For example,
678         * "-1230k" will be converted to -1230 * 1024 = -1259520;
679         * "891g" will be converted to 891 * 1024^3 = 956703965184;
680         *
681         * @param s input string
682         * @return a long value represented by the input string.
683         */
684        public static long string2long(String s) {
685          s = s.trim();
686          final int lastpos = s.length() - 1;
687          final char lastchar = s.charAt(lastpos);
688          if (Character.isDigit(lastchar))
689            return Long.parseLong(s);
690          else {
691            long prefix;
692            try {
693              prefix = TraditionalBinaryPrefix.valueOf(lastchar).value;
694            } catch (IllegalArgumentException e) {
695              throw new IllegalArgumentException("Invalid size prefix '" + lastchar
696                  + "' in '" + s
697                  + "'. Allowed prefixes are k, m, g, t, p, e(case insensitive)");
698            }
699            long num = Long.parseLong(s.substring(0, lastpos));
700            if (num > (Long.MAX_VALUE/prefix) || num < (Long.MIN_VALUE/prefix)) {
701              throw new IllegalArgumentException(s + " does not fit in a Long");
702            }
703            return num * prefix;
704          }
705        }
706    
707        /**
708         * Convert a long integer to a string with traditional binary prefix.
709         * 
710         * @param n the value to be converted
711         * @param unit The unit, e.g. "B" for bytes.
712         * @param decimalPlaces The number of decimal places.
713         * @return a string with traditional binary prefix.
714         */
715        public static String long2String(long n, String unit, int decimalPlaces) {
716          if (unit == null) {
717            unit = "";
718          }
719          //take care a special case
720          if (n == Long.MIN_VALUE) {
721            return "-8 " + EXA.symbol + unit;
722          }
723    
724          final StringBuilder b = new StringBuilder();
725          //take care negative numbers
726          if (n < 0) {
727            b.append('-');
728            n = -n;
729          }
730          if (n < KILO.value) {
731            //no prefix
732            b.append(n);
733            return (unit.isEmpty()? b: b.append(" ").append(unit)).toString();
734          } else {
735            //find traditional binary prefix
736            int i = 0;
737            for(; i < values().length && n >= values()[i].value; i++);
738            TraditionalBinaryPrefix prefix = values()[i - 1];
739    
740            if ((n & prefix.bitMask) == 0) {
741              //exact division
742              b.append(n >> prefix.bitShift);
743            } else {
744              final String  format = "%." + decimalPlaces + "f";
745              String s = format(format, n/(double)prefix.value);
746              //check a special rounding up case
747              if (s.startsWith("1024")) {
748                prefix = values()[i];
749                s = format(format, n/(double)prefix.value);
750              }
751              b.append(s);
752            }
753            return b.append(' ').append(prefix.symbol).append(unit).toString();
754          }
755        }
756      }
757    
758        /**
759         * Escapes HTML Special characters present in the string.
760         * @param string
761         * @return HTML Escaped String representation
762         */
763        public static String escapeHTML(String string) {
764          if(string == null) {
765            return null;
766          }
767          StringBuilder sb = new StringBuilder();
768          boolean lastCharacterWasSpace = false;
769          char[] chars = string.toCharArray();
770          for(char c : chars) {
771            if(c == ' ') {
772              if(lastCharacterWasSpace){
773                lastCharacterWasSpace = false;
774                sb.append("&nbsp;");
775              }else {
776                lastCharacterWasSpace=true;
777                sb.append(" ");
778              }
779            }else {
780              lastCharacterWasSpace = false;
781              switch(c) {
782              case '<': sb.append("&lt;"); break;
783              case '>': sb.append("&gt;"); break;
784              case '&': sb.append("&amp;"); break;
785              case '"': sb.append("&quot;"); break;
786              default : sb.append(c);break;
787              }
788            }
789          }
790          
791          return sb.toString();
792        }
793    
794      /**
795       * @return a byte description of the given long interger value.
796       */
797      public static String byteDesc(long len) {
798        return TraditionalBinaryPrefix.long2String(len, "B", 2);
799      }
800    
801      /** @deprecated use StringUtils.format("%.2f", d). */
802      @Deprecated
803      public static String limitDecimalTo2(double d) {
804        return format("%.2f", d);
805      }
806      
807      /**
808       * Concatenates strings, using a separator.
809       *
810       * @param separator Separator to join with.
811       * @param strings Strings to join.
812       */
813      public static String join(CharSequence separator, Iterable<?> strings) {
814        Iterator<?> i = strings.iterator();
815        if (!i.hasNext()) {
816          return "";
817        }
818        StringBuilder sb = new StringBuilder(i.next().toString());
819        while (i.hasNext()) {
820          sb.append(separator);
821          sb.append(i.next().toString());
822        }
823        return sb.toString();
824      }
825    
826      /**
827       * Concatenates strings, using a separator.
828       *
829       * @param separator to join with
830       * @param strings to join
831       * @return  the joined string
832       */
833      public static String join(CharSequence separator, String[] strings) {
834        // Ideally we don't have to duplicate the code here if array is iterable.
835        StringBuilder sb = new StringBuilder();
836        boolean first = true;
837        for (String s : strings) {
838          if (first) {
839            first = false;
840          } else {
841            sb.append(separator);
842          }
843          sb.append(s);
844        }
845        return sb.toString();
846      }
847    
848      /**
849       * Convert SOME_STUFF to SomeStuff
850       *
851       * @param s input string
852       * @return camelized string
853       */
854      public static String camelize(String s) {
855        StringBuilder sb = new StringBuilder();
856        String[] words = split(s.toLowerCase(Locale.US), ESCAPE_CHAR, '_');
857    
858        for (String word : words)
859          sb.append(org.apache.commons.lang.StringUtils.capitalize(word));
860    
861        return sb.toString();
862      }
863    
864      /**
865       * Matches a template string against a pattern, replaces matched tokens with
866       * the supplied replacements, and returns the result.  The regular expression
867       * must use a capturing group.  The value of the first capturing group is used
868       * to look up the replacement.  If no replacement is found for the token, then
869       * it is replaced with the empty string.
870       * 
871       * For example, assume template is "%foo%_%bar%_%baz%", pattern is "%(.*?)%",
872       * and replacements contains 2 entries, mapping "foo" to "zoo" and "baz" to
873       * "zaz".  The result returned would be "zoo__zaz".
874       * 
875       * @param template String template to receive replacements
876       * @param pattern Pattern to match for identifying tokens, must use a capturing
877       *   group
878       * @param replacements Map<String, String> mapping tokens identified by the
879       *   capturing group to their replacement values
880       * @return String template with replacements
881       */
882      public static String replaceTokens(String template, Pattern pattern,
883          Map<String, String> replacements) {
884        StringBuffer sb = new StringBuffer();
885        Matcher matcher = pattern.matcher(template);
886        while (matcher.find()) {
887          String replacement = replacements.get(matcher.group(1));
888          if (replacement == null) {
889            replacement = "";
890          }
891          matcher.appendReplacement(sb, Matcher.quoteReplacement(replacement));
892        }
893        matcher.appendTail(sb);
894        return sb.toString();
895      }
896      
897      /**
898       * Get stack trace for a given thread.
899       */
900      public static String getStackTrace(Thread t) {
901        final StackTraceElement[] stackTrace = t.getStackTrace();
902        StringBuilder str = new StringBuilder();
903        for (StackTraceElement e : stackTrace) {
904          str.append(e.toString() + "\n");
905        }
906        return str.toString();
907      }
908    }