KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > util > StringUtils


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: StringUtils.java,v 1.14 2007/02/20 04:08:10 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.util;
23
24 import java.util.ArrayList JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.StringTokenizer JavaDoc;
29
30 import org.opensubsystems.core.error.OSSInvalidDataException;
31 import org.opensubsystems.core.error.OSSException;
32
33 /**
34  * Utility methods for String manipulation.
35  *
36  * @version $Id: StringUtils.java,v 1.14 2007/02/20 04:08:10 bastafidli Exp $
37  * @author Peter Satury
38  * @code.reviewer Miro Halas
39  * @code.reviewed 1.11 2006/04/29 00:24:18 jlegeny
40  */

41 public final class StringUtils
42 {
43    // Constants ////////////////////////////////////////////////////////////////
44

45    /**
46     * Constant for assigning
47     */

48    public static final String JavaDoc EMPTY_STRING = "";
49    
50    /**
51     * Constant for assigning
52     */

53    public static final String JavaDoc COMMA_STRING = ",";
54    
55    /**
56     * Keep the original case of the string;
57     */

58    public static final int CASE_ORIGINAL = 0;
59    
60    /**
61     * Convert the string to upper case.
62     */

63    public static final int CASE_TOUPPER = 1;
64    
65    /**
66     * Convert the string to lower case.
67     */

68    public static final int CASE_TOLOWER = 2;
69    
70    // Constructors /////////////////////////////////////////////////////////////
71

72    /**
73     * Private constructor since this class cannot be instantiated
74     */

75    private StringUtils(
76    )
77    {
78       // Do nothing
79
}
80
81    // Public methods ///////////////////////////////////////////////////////////
82

83    /**
84     * Count number of occurences of lookup in text.
85     *
86     * @param text - text to search in for occurences of lookup
87     * @param lookup - character to count
88     * @return int - number of occurences of lookup in text.
89     */

90    public static int count(
91       String JavaDoc text,
92       char lookup
93    )
94    {
95       int iCount = 0;
96       
97       if (text != null)
98       {
99          int iIndex = text.indexOf(lookup);
100    
101          while (iIndex != -1)
102          {
103             iCount++;
104             iIndex = text.indexOf(lookup, iIndex + 1);
105          }
106       }
107       
108       return iCount;
109    }
110    
111    /**
112     * Parse textual representation of fraction to a floating point number
113     *
114     * @param textToParse - in the form "any_text whole_part quotient/divisor any_text"
115     * @param defaultValue - if the test is unparsable, what default value to return
116     * @param bIgnoreRest - if true, this will ignore the rest of the string
117     * (any_other_text) after the fraction, if false then
118     * the whole string is considered
119     * @return double - number coresponding to the fraction
120     */

121    public static double parseFraction(
122       String JavaDoc textToParse,
123       double defaultValue,
124       boolean bIgnoreRest
125    )
126    {
127       double parsed = defaultValue;
128       int iLength;
129       int iIndex;
130       int iIndexStart;
131       int iIndexEnd;
132       int iNumber;
133             
134       // lets use "xxxxxxx 123 456 / 789 yyyyy" as example or
135
// lets use "xxxxxxx 123 / 789 yyyyy" as example
136

137       iIndexStart = 0;
138       iLength = textToParse.length();
139       if (bIgnoreRest)
140       {
141          // Skip while not number
142
while ((iIndexStart < iLength)
143                && (!Character.isDigit(textToParse.charAt(iIndexStart))))
144          {
145             iIndexStart++;
146          }
147          // We skiped "xxxxxxx", iIndexStart is at "123 456 / 789 yyyyy"
148
}
149       
150       // We should be at first digit
151
if (iIndexStart < iLength)
152       {
153          // Find end of the number
154
iIndex = iIndexStart;
155          while ((iIndex < iLength)
156                && (Character.isDigit(textToParse.charAt(iIndex))))
157          {
158             iIndex++;
159          }
160          iIndexEnd = iIndex;
161          // We skiped "123", iIndexStart is at "123 456 / 789 yyyyy"
162
// iIndexEnd is at " 456 / 789 yyyyy"
163

164          if (iIndexStart != iIndexEnd)
165          {
166             // There was at least some digits
167
iNumber = Integer.parseInt(textToParse.substring(iIndexStart,
168                                                              iIndexEnd));
169             // iNumber is 123
170

171             // There was at least one digit, now is it whole part or quotient?
172
// Skip spaces
173
while ((iIndex < iLength)
174                   && ((textToParse.charAt(iIndex) == ' ')
175                      || (textToParse.charAt(iIndex) == '-')))
176             {
177                iIndex++;
178             }
179             // We skiped "123", iIndex is at "456 / 789 yyyyy"
180

181             // Now we have stopped because of 2 things, we either reached end of
182
// string or we have found something other than space, if it is /
183
// then it was qoutient, if it is digit, then it was whole part
184
if (iIndex == iLength)
185             {
186                // it was a whole part and we are done
187
parsed = iNumber;
188             }
189             else
190             {
191                int iQuotient = 0;
192                int iDivisor = Integer.MAX_VALUE;
193                
194                if (Character.isDigit(textToParse.charAt(iIndex)))
195                {
196                   int iWholePart = 0;
197                   
198                   // it was a whole part and we continue to look for the quotient
199
iWholePart = iNumber;
200                   
201                   // Find end of the number
202
iIndexStart = iIndex; // Remember start
203
while ((iIndex < iLength)
204                         && (Character.isDigit(textToParse.charAt(iIndex))))
205                   {
206                      iIndex++;
207                   }
208                   iIndexEnd = iIndex;
209                   // We skiped "456", iStartIndex is at "456 / 789 yyyyy"
210
// And iIndexEnd is at " / 789 yyyyy"
211

212                   iQuotient = Integer.parseInt(textToParse.substring(iIndexStart,
213                                                                      iIndexEnd));
214                   // iQuotient is 456
215

216                   // Skip spaces
217
while ((iIndex < iLength)
218                         && (textToParse.charAt(iIndex) == ' '))
219                   {
220                      iIndex++;
221                   }
222                   // And iIndex is at "/ 789 yyyyy"
223

224                   if (textToParse.charAt(iIndex) == '/')
225                   {
226                      // It was a quotient and we continue to look for divisor
227

228                      iIndexStart = iIndex + 1;
229                      while ((iIndexStart < iLength)
230                            && (textToParse.charAt(iIndexStart) == ' '))
231                      {
232                         iIndexStart++;
233                      }
234                      // And iIndexStart is at "789 yyyyy"
235

236                      // We should be at next digit
237
if (iIndexStart < iLength)
238                      {
239                         // Find end of the number
240
iIndex = iIndexStart;
241                         while ((iIndex < iLength)
242                               && (Character.isDigit(textToParse.charAt(iIndex))))
243                         {
244                            iIndex++;
245                         }
246                         iIndexEnd = iIndex;
247                         // We skiped "789", iStartIndex is at "789 yyyyy"
248
// And iIndexEnd is at " yyyyy"
249

250                         if (iIndexStart != iIndexEnd)
251                         {
252                            iDivisor = Integer.parseInt(textToParse.substring(iIndexStart,
253                                                                              iIndexEnd));
254                            // iDivisor is 789
255
if (iDivisor != 0)
256                            {
257                               if (iIndexEnd == iLength)
258                               {
259                                  // And we are at the end of the string
260
parsed = ((double)(iWholePart))
261                                           + (((double)iQuotient) / ((double)iDivisor));
262                               }
263                               else
264                               {
265                                  if (bIgnoreRest)
266                                  {
267                                     // And we can ignore what is after
268
parsed = ((double)(iWholePart))
269                                              + (((double)iQuotient) / ((double)iDivisor));
270                                  }
271                                  else
272                                  {
273                                     // there was something else we don't know what so
274
// return the default value
275
}
276                               }
277                            }
278                         }
279                         else
280                         {
281                            // The divisor is missing, return default value
282
}
283                      }
284                      else
285                      {
286                         // The divisor is missing, return default value
287
}
288                   }
289                   else
290                   {
291                      // The divisor is missing, return default value
292
}
293                }
294                else
295                {
296                   if (textToParse.charAt(iIndex) == '/')
297                   {
298                      // And iIndex is at "/ 456 yyyyy"
299

300                      // It was a quotient and we continue to look for divisor
301
iQuotient = iNumber;
302                      // iQuotient is 123
303

304                      iIndexStart = iIndex + 1;
305                      while ((iIndexStart < iLength)
306                            && (textToParse.charAt(iIndexStart) == ' '))
307                      {
308                         iIndexStart++;
309                      }
310                      // And iIndexStart is at "456 yyyyy"
311

312                      // We should be at next digit
313
if (iIndexStart < iLength)
314                      {
315                         // Find end of the number
316
iIndex = iIndexStart;
317                         while ((iIndex < iLength)
318                               && (Character.isDigit(textToParse.charAt(iIndex))))
319                         {
320                            iIndex++;
321                         }
322                         iIndexEnd = iIndex;
323                         // We skipped "456", iIndexStart is at "456 yyyyy"
324
// iIndexEnd is at " yyyyy"
325

326                         if (iIndexStart != iIndexEnd)
327                         {
328                            iDivisor = Integer.parseInt(textToParse.substring(iIndexStart,
329                                                                              iIndexEnd));
330                            // iDivisor is 456
331

332                            if (iDivisor != 0)
333                            {
334                               if (iIndexEnd == iLength)
335                               {
336                                  // And we are at the end of the string
337
parsed = ((double)iQuotient) / ((double)iDivisor);
338                               }
339                               else
340                               {
341                                  if (bIgnoreRest)
342                                  {
343                                     // And we can ignore what is after
344
parsed = ((double)iQuotient) / ((double)iDivisor);
345                                  }
346                                  else
347                                  {
348                                     // there was something else we don't know what so
349
// return the default value
350
}
351                               }
352                            }
353                         }
354                         else
355                         {
356                            // The divisor is missing, return default value
357
}
358                      }
359                      else
360                      {
361                         // The divisor is missing, return default value
362
}
363                   }
364                   else
365                   {
366                      // It was a whole part and there is something else
367
if (bIgnoreRest)
368                      {
369                          // and we are done
370
parsed = iNumber;
371                      }
372                      else
373                      {
374                         // there was something else we don't know what so
375
// return the default value
376
}
377                   }
378                }
379             }
380          }
381       }
382       
383       return parsed;
384    }
385    
386    /**
387     * Parse String to array of Strings while treating quoted values as single
388     * element.
389     *
390     * @param strParse - String to parse
391     * @param strDel - String deliminer
392     * @param bAllowSingleQuote - single qoutes such as ' can be used to group value
393     * @param bAllowDoubleQuote - double quote such as " can be used to group value
394     * @return String[] - parsed list
395     * @throws OSSInvalidDataException - error during parsing
396     */

397    public static String JavaDoc[] parseQuotedStringToStringArray(
398       String JavaDoc strParse,
399       String JavaDoc strDel,
400       boolean bAllowSingleQuote,
401       boolean bAllowDoubleQuote
402    ) throws OSSInvalidDataException
403    {
404       String JavaDoc[] arrayStrings;
405       
406       if (strParse == null)
407       {
408          arrayStrings = null;
409       }
410       else
411       {
412          List JavaDoc lstElements = new ArrayList JavaDoc();
413          int iCurrentIndex = 0;
414          int iNextIndex;
415          int iDelLength = strDel.length();
416          int iParseLength = strParse.length();
417          
418          while (iCurrentIndex < iParseLength)
419          {
420             if ((bAllowSingleQuote) && (strParse.charAt(iCurrentIndex) == '\''))
421             {
422                // Find next single quote and treat the things in the middle as
423
// single element
424
iNextIndex = strParse.indexOf('\'', iCurrentIndex + 1);
425                if (iNextIndex == -1)
426                {
427                   throw new OSSInvalidDataException(
428                                "Incorrect input. " + strParse
429                                + " No single quote following the one"
430                                + " at location " + iCurrentIndex);
431                }
432                lstElements.add(strParse.substring(iCurrentIndex + 1, iNextIndex));
433                iCurrentIndex = iNextIndex + 1;
434                if (strParse.substring(iCurrentIndex).startsWith(strDel))
435                {
436                   iCurrentIndex += iDelLength;
437                }
438             }
439             else if ((bAllowDoubleQuote) && (strParse.charAt(iCurrentIndex) == '"'))
440             {
441                // Find next double quote and treat the things in the middle as
442
// single element
443
iNextIndex = strParse.indexOf('"', iCurrentIndex + 1);
444                if (iNextIndex == -1)
445                {
446                   throw new OSSInvalidDataException(
447                                "Incorrect input. " + strParse
448                                + " No double quote following the one"
449                                + " at location " + iCurrentIndex);
450                }
451                lstElements.add(strParse.substring(iCurrentIndex + 1, iNextIndex));
452                iCurrentIndex = iNextIndex + 1;
453                if (strParse.substring(iCurrentIndex).startsWith(strDel))
454                {
455                   iCurrentIndex += iDelLength;
456                }
457             }
458             else
459             {
460                // Find next separator and treat the things in the middle as
461
// single element
462
iNextIndex = strParse.indexOf(strDel, iCurrentIndex);
463                if (iNextIndex == -1)
464                {
465                   // No other delimiter found so take the rest of the string
466
lstElements.add(strParse.substring(iCurrentIndex));
467                   iCurrentIndex = iParseLength;
468                }
469                else
470                {
471                   lstElements.add(strParse.substring(iCurrentIndex, iNextIndex));
472                   iCurrentIndex = iNextIndex + iDelLength;
473                }
474             }
475          }
476          arrayStrings = (String JavaDoc[])lstElements.toArray(new String JavaDoc[lstElements.size()]);
477       }
478       
479       return arrayStrings;
480    }
481
482    /**
483     * Parse String to array of integers.
484     *
485     * @param strParse - String to parse
486     * @param strDel - String deliminer
487     * @return int[] - parsed list
488     * @throws OSSException - error during parsing
489     */

490    public static int[] parseStringToIntArray(
491       String JavaDoc strParse,
492       String JavaDoc strDel
493    ) throws OSSException
494    {
495       int[] arrayInts;
496       try
497       {
498          if (strParse == null)
499          {
500              arrayInts = null;
501          }
502          else
503          {
504             // TODO: Performance: Memory vs speed, here we allocate list and then
505
// another array, how about just counting the number of elements
506
// and then allocating array and parsing directly to array without
507
// the extra list and copying from list to array?
508
List JavaDoc lstInts = parseStringToList(strParse, strDel);
509          
510             if (lstInts == null || lstInts.size() < 1)
511             {
512                arrayInts = null;
513             }
514             else
515             {
516                Iterator JavaDoc items;
517                int iCount;
518                
519                arrayInts = new int[lstInts.size()];
520                for (iCount = 0, items = lstInts.iterator(); items.hasNext();)
521                {
522                   arrayInts[iCount++] = Integer.parseInt(((String JavaDoc)items.next()).trim());
523                }
524             }
525          }
526       }
527       catch (NumberFormatException JavaDoc eExc)
528       {
529          throw new OSSInvalidDataException(
530                       "Problems with parsing String to array of int.",
531                       eExc);
532       }
533       return arrayInts;
534    }
535
536    /**
537     * Parse String to array of Integers.
538     *
539     * @param strParse - String to parse
540     * @param strDel - String deliminer
541     * @return Integer[] - parsed list
542     * @throws OSSException - error during parsing
543     */

544    public static Integer JavaDoc[] parseStringToIntegerArray(
545       String JavaDoc strParse,
546       String JavaDoc strDel
547    ) throws OSSException
548    {
549       Integer JavaDoc[] arrayInts;
550       try
551       {
552          if (strParse == null)
553          {
554              arrayInts = null;
555          }
556          else
557          {
558             // TODO: Performance: Memory vs speed, here we allocate list and then
559
// another array, how about just counting the number of elements
560
// and then allocating array and parsing directly to array without
561
// the extra list and copying from list to array?
562
List JavaDoc strInts = parseStringToList(strParse, strDel);
563          
564             if (strInts == null || strInts.size() < 1)
565             {
566                arrayInts = null;
567             }
568             else
569             {
570                arrayInts = new Integer JavaDoc[strInts.size()];
571                for (int iCount = 0; iCount < strInts.size(); iCount++)
572                {
573                   arrayInts[iCount] = Integer.valueOf((String JavaDoc) strInts.get(iCount));
574                }
575             }
576          }
577       }
578       catch (NumberFormatException JavaDoc eExc)
579       {
580          throw new OSSInvalidDataException(
581                       "Problems with parsing String to array of int.",
582                       eExc);
583       }
584       return arrayInts;
585    }
586
587    /**
588     * Parse String to array of Strings.
589     *
590     * @param strParse - String to parse
591     * @param strDel - String deliminer
592     * @return String[] - parsed list
593     */

594    public static String JavaDoc[] parseStringToStringArray(
595       String JavaDoc strParse,
596       String JavaDoc strDel
597    )
598    {
599       String JavaDoc[] arrayStrings;
600       
601       if (strParse == null)
602       {
603           arrayStrings = null;
604       }
605       else
606       {
607          // TODO: Performance: Memory vs speed, here we allocate list and then
608
// another array, how about just counting the number of elements
609
// and then allocating array and parsing directly to array without
610
// the extra list and copying from list to array?
611
List JavaDoc lstStrings = parseStringToList(strParse, strDel);
612       
613          if ((lstStrings == null) || (lstStrings.isEmpty()))
614          {
615             arrayStrings = null;
616          }
617          else
618          {
619             arrayStrings = (String JavaDoc[])lstStrings.toArray(new String JavaDoc[lstStrings.size()]);
620          }
621       }
622       
623       return arrayStrings;
624    }
625
626    /**
627     * Parse array of integers to String.
628     *
629     * @param arrParse - int array to parse
630     * @param strDel - String deliminer
631     * @return String - parsed array
632     */

633    public static String JavaDoc parseIntArrayToString(
634       int[] arrParse,
635       String JavaDoc strDel
636    )
637    {
638       StringBuffer JavaDoc strbInts = new StringBuffer JavaDoc();
639       if ((arrParse != null) && (arrParse.length > 0))
640       {
641          for (int iCount = 0; iCount < arrParse.length; iCount++)
642          {
643             if (iCount > 0)
644             {
645                strbInts.append(strDel);
646             }
647             strbInts.append(arrParse[iCount]);
648          }
649       }
650       return strbInts.toString();
651    }
652    
653    /**
654     * Parse collection of objects to String by calling toString on each element.
655     *
656     * @param colObjects - collection of data objects to parse
657     * @param strDel - String deliminer
658     * @return String - parsed array
659     */

660    public static String JavaDoc parseCollectionToString(
661       Collection JavaDoc colObjects,
662       String JavaDoc strDel
663    )
664    {
665       StringBuffer JavaDoc strbInts = new StringBuffer JavaDoc();
666       if ((colObjects != null) && (!colObjects.isEmpty()))
667       {
668          for (Iterator JavaDoc items = colObjects.iterator();
669               items.hasNext();)
670          {
671             if (strbInts.length() > 0)
672             {
673                strbInts.append(strDel);
674             }
675             strbInts.append(items.next().toString());
676          }
677       }
678       return strbInts.toString();
679    }
680
681    /**
682     * Parse String to List.
683     *
684     * @param strParse - String to parse
685     * @param strDel - String deliminer
686     * @return List - parsed list of items in the string delimtied by delimiter
687     */

688    public static List JavaDoc parseStringToList(
689       String JavaDoc strParse,
690       String JavaDoc strDel
691    )
692    {
693       return (List JavaDoc)parseStringToCollection(strParse, strDel, false,
694                                            CASE_ORIGINAL, null);
695    }
696
697    /**
698     * Parse String to ANY collection you specify and trim each item.
699     *
700     * @param strParse - String to parse
701     * @param strDel - String deliminer
702     * @param container - if specified then it will be filled with items (it WILL
703     * NOT be emptied first). If this is null, the default
704     * collection will be allocated. This allows you here
705     * to pass list or set so this method is more flexible.
706     * @param bTrim - should it be trimmed or not
707     * @param iConvertCase - how to convert the case of the string - one of the
708     * CASE_XXX costants
709     * @return Collection - parsed collection, if container was specified, the
710     * same object will be returned. If it was not specified
711     * default object will be returned. If strParse was not
712     * null, then this will be not null.
713     */

714    public static Collection JavaDoc parseStringToCollection(
715       String JavaDoc strParse,
716       String JavaDoc strDel,
717       boolean bTrim,
718       int iConvertCase,
719       Collection JavaDoc container
720    )
721    {
722       Collection JavaDoc colReturn;
723       
724       if (strParse == null || strParse.length() < 1)
725       {
726          if (container != null)
727          {
728             colReturn = container;
729          }
730          else
731          {
732             colReturn = null;
733          }
734       }
735       else
736       {
737          // TODO: Performance: StringTokenizer is considered to be slow
738
// because it creates lots of objects internally, consider replacing
739
// this with String.indexOf(delimiter)
740
StringTokenizer JavaDoc strTokParse = new StringTokenizer JavaDoc(strParse, strDel);
741          String JavaDoc strTemp;
742          
743          if (container == null)
744          {
745             // This has to be List since parseStringToList requires it
746
colReturn = new ArrayList JavaDoc();
747          }
748          else
749          {
750             container.clear();
751             colReturn = container;
752          }
753          
754          if (strParse.startsWith(strDel))
755          {
756             // If the string starts with the delimiter, tokenizer would skip it
757
// but we have to have empty element in front
758
colReturn.add("");
759          }
760          
761          while (strTokParse.hasMoreTokens())
762          {
763             strTemp = (String JavaDoc)strTokParse.nextToken();
764             if (bTrim)
765             {
766                strTemp = strTemp.trim();
767             }
768             switch (iConvertCase)
769             {
770                case (CASE_ORIGINAL) :
771                {
772                   // do nothing
773
break;
774                }
775                case (CASE_TOUPPER) :
776                {
777                   strTemp = strTemp.toUpperCase();
778                   break;
779                }
780                case (CASE_TOLOWER) :
781                {
782                   strTemp = strTemp.toLowerCase();
783                   break;
784                }
785                default :
786                {
787                   assert false : "Incorrect case specification.";
788                }
789             }
790             colReturn.add(strTemp);
791          }
792       }
793       return colReturn;
794    }
795
796    /**
797     * Method to limit String length for display and add '...' to the end
798     *
799     * @param limitLength - limit of length
800     * @param strValue - String to limit
801     * @return String - limited String
802     */

803    public static String JavaDoc limitStringLength(
804       int limitLength,
805       String JavaDoc strValue
806    )
807    {
808       StringBuffer JavaDoc sbReturn = new StringBuffer JavaDoc();
809       
810       if ((limitLength > 0) && (strValue.length() > limitLength))
811       {
812          // If limit length is lower then 5 we will do just exact substring
813
if (limitLength < 5)
814          {
815             sbReturn.append(strValue.substring(0, limitLength));
816          }
817          // If limit length is lower then 15 and higher then 4 we will
818
// return substring of (limit - 3) and '...'
819
else if (limitLength < 15)
820          {
821             sbReturn.append(strValue.substring(0, limitLength - 3));
822             sbReturn.append("...");
823          }
824          // If limit length is higher then 15 we will try to find
825
// some space ' ' near before limit and cut string there
826
else
827          {
828             // if we will not find ' ' near before limit
829
// we will return substring of (limit - 3) and '...'
830
if ((strValue.indexOf(" ", limitLength - 12) > (limitLength - 4))
831                || (strValue.indexOf(" ", limitLength - 12) < 0))
832             {
833                sbReturn.append(strValue.substring(0, limitLength - 3));
834                sbReturn.append("...");
835             }
836             // if we will find ' ' near before limit
837
// we will return substring until ' ' and ' ...'
838
else
839             {
840                sbReturn.append(strValue.substring(0, strValue.indexOf(
841                                  " ", limitLength - 12)));
842                sbReturn.append(" ...");
843             }
844          }
845       }
846       else
847       {
848          sbReturn.append(strValue);
849       }
850       
851       return sbReturn.toString();
852    }
853
854    /**
855     * Method to remove comma from start and from end of the string for examples
856     * to use it as parameter to SQL IN operator
857     *
858     * @param strToRemoveFrom - String to remove comma from
859     * @return String - string with removed commas from the start and end of the string
860     */

861    public static String JavaDoc removeComma(
862       String JavaDoc strToRemoveFrom
863    )
864    {
865       if (GlobalConstants.ERROR_CHECKING)
866       {
867          assert strToRemoveFrom.charAt(0) == ','
868                  : "String should to start with character ','";
869          assert strToRemoveFrom.charAt(strToRemoveFrom.length() - 1) == ','
870                  : "String should to end with character ','";
871       }
872       // we have to remove comma from start and from end of the string
873
// because then it can be used for SQL IN operator
874
if (strToRemoveFrom.length() > 2)
875       {
876          strToRemoveFrom = strToRemoveFrom.substring(1, strToRemoveFrom.length() - 1);
877       }
878       else
879       {
880          strToRemoveFrom = "";
881       }
882
883       return strToRemoveFrom;
884    }
885    
886    /**
887     * Concat all the specified strings to a single one
888     *
889     * @param strings - strings to concat, all null and empty ones will be ignored
890     * @param separator - separator to put in between the string elements
891     * @param quote - quote string to put around string elements, if null nothing
892     * will be put around them
893     * @return String with concatenated inputs
894     */

895    public static String JavaDoc concat(
896       String JavaDoc[] strings,
897       String JavaDoc separator,
898       String JavaDoc quote
899    )
900    {
901       StringBuffer JavaDoc output = new StringBuffer JavaDoc();
902       
903       if (strings != null)
904       {
905          int iIndex;
906          boolean bSeparator;
907          boolean bQuote;
908          
909          bSeparator = (separator != null) && (separator.length() > 0);
910          bQuote = (quote != null) && (quote.length() > 0);
911          for (iIndex = 0; iIndex < strings.length; iIndex++)
912          {
913             if ((strings[iIndex] != null) && (strings[iIndex].length() > 0))
914             {
915                if ((output.length() > 0) && (bSeparator))
916                {
917                   output.append(separator);
918                }
919                if (bQuote)
920                {
921                   output.append(quote);
922                }
923                output.append(strings[iIndex]);
924                if (bQuote)
925                {
926                   output.append(quote);
927                }
928             }
929          }
930       }
931       
932       return output.toString();
933    }
934    
935    /**
936     * Test if any element in the container contains given string.
937     *
938     * @param container - container of which elements will be searched to see if
939     * they contains given text
940     * @param strSearch - text to search in the elements of specified container
941     * @return boolean - true if any of the elements in container contains given
942     * text
943     */

944    public static boolean isContained(
945       Collection JavaDoc container,
946       String JavaDoc strSearch
947    )
948    {
949       boolean bReturn = false;
950       
951       if ((container != null) && (!container.isEmpty()))
952       {
953          for (Iterator JavaDoc itrElements = container.iterator();
954              (itrElements.hasNext() && (!bReturn));)
955          {
956             if (((String JavaDoc)itrElements.next()).indexOf(strSearch) != -1)
957             {
958                bReturn = true;
959             }
960          }
961       }
962       
963       return bReturn;
964    }
965
966    /**
967     * Test if given string contains any element in the container.
968     *
969     * @param container - container of which elements will be searched to see if
970     * they are contained within given text
971     * @param strSearch - text to search in for the elements of specified container
972     * @return boolean - true if the search text contains any of the elements in
973     * container
974     */

975    public static boolean contains(
976       Collection JavaDoc container,
977       String JavaDoc strSearch
978    )
979    {
980       boolean bReturn = false;
981       
982       if ((container != null) && (!container.isEmpty()))
983       {
984          for (Iterator JavaDoc itrElements = container.iterator();
985              (itrElements.hasNext() && (!bReturn));)
986          {
987             if (strSearch.indexOf((String JavaDoc)itrElements.next()) != -1)
988             {
989                bReturn = true;
990             }
991          }
992       }
993       
994       return bReturn;
995    }
996    
997    /**
998     * Method return boolean result if particular substring is contained
999     * within the list of substrings separated by a separator.
1000    *
1001    * @param strSearchIn - string of all substrings separated by separator to
1002    * search in
1003    * @param strSearchFor - string that will be search for
1004    * @param strSeparator - item separator
1005    * @return boolean - true if it contains the ID, false otherwise
1006    */

1007   public static boolean containsInSeparatedString(
1008      String JavaDoc strSearchIn,
1009      String JavaDoc strSearchFor,
1010      String JavaDoc strSeparator
1011   )
1012   {
1013      boolean bReturn = false;
1014      
1015      StringBuffer JavaDoc sbInputString = new StringBuffer JavaDoc();
1016      StringBuffer JavaDoc sbSearchString = new StringBuffer JavaDoc();
1017      
1018      if (strSearchIn.length() > 0)
1019      {
1020         // add separator at the beginning and end of the input string
1021
sbInputString.append(strSeparator);
1022         sbInputString.append(strSearchIn);
1023         sbInputString.append(strSeparator);
1024         
1025         // add separator at the beginning and end of the search string
1026
sbSearchString.append(strSeparator);
1027         sbSearchString.append(strSearchFor);
1028         sbSearchString.append(strSeparator);
1029         
1030         // search for particular ID
1031
if (sbInputString.indexOf(sbSearchString.toString()) != -1)
1032         {
1033            bReturn = true;
1034         }
1035      }
1036      
1037      return bReturn;
1038   }
1039}
1040
Popular Tags