KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > string > util > StringW


1 /*
2  * Copyright 1999,2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 // Copied from GenerationJava Core Library.
17
//package com.generationjava.lang;
18

19 package org.apache.taglibs.string.util;
20
21 import org.apache.commons.lang.StringUtils;
22
23 /**
24  * A set of String library static methods. While extending String or
25  * StringBuffer would have been the nicest solution, that is not
26  * possible, so a simple set of static methods seems the most workable.
27  *
28  * Method ideas have so far been taken from the PHP4, Ruby and .NET languages.
29  *
30  * @author bayard@generationjava.com
31  * @version 0.4 20010812
32  */

33 final public class StringW {
34
35     /**
36      * Quote a string so that it may be used in a regular expression
37      * without any parts of the string being considered as a
38      * part of the regular expression's control characters.
39      */

40     static public String JavaDoc quoteRegularExpression(String JavaDoc str) {
41         // replace ? + * / . ^ $ as long as they're not in character
42
// class. so must be done by hand
43
char[] chrs = str.toCharArray();
44         int sz = chrs.length;
45         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(2*sz);
46         for(int i=0; i<sz; i++) {
47             switch(chrs[i]) {
48               case '[' :
49               case ']' :
50               case '?' :
51               case '+' :
52               case '*' :
53               case '/' :
54               case '.' :
55               case '^' :
56               case '$' :
57                 buffer.append("\\");
58               default :
59                 buffer.append(chrs[i]);
60             }
61         }
62         return buffer.toString();
63     }
64
65     /**
66      * Create a word-wrapped version of a String. Wrap at 80 characters and
67      * use newlines as the delimiter. If a word is over 80 characters long
68      * use a - sign to split it.
69      */

70     static public String JavaDoc wordWrap(String JavaDoc str) {
71         return wordWrap(str, 80, "\n", "-", true);
72     }
73     /**
74      * Create a word-wrapped version of a String. Wrap at a specified width and
75      * use newlines as the delimiter. If a word is over the width in lenght
76      * use a - sign to split it.
77      */

78     static public String JavaDoc wordWrap(String JavaDoc str, int width) {
79         return wordWrap(str, width, "\n", "-", true);
80     }
81     /**
82      * Word-wrap a string.
83      *
84      * @param str String to word-wrap
85      * @param width int to wrap at
86      * @param delim String to use to separate lines
87      * @param split String to use to split a word greater than width long
88      *
89      * @return String that has been word wrapped (with the delim inside width boundaries)
90      */

91   static public String JavaDoc wordWrap(String JavaDoc str, int width, String JavaDoc delim, String JavaDoc split ) {
92     return wordWrap(str, width, delim, split, true);
93   }
94   
95     /**
96      * Word-wrap a string.
97      *
98      * @param str String to word-wrap
99      * @param width int to wrap at
100      * @param delim String to use to separate lines
101      * @param split String to use to split a word greater than width long
102      * @param delimInside wheter or not delim should be included in chunk before length reaches width.
103      *
104      * @return String that has been word wrapped
105      */

106     static public String JavaDoc wordWrap(String JavaDoc str, int width, String JavaDoc delim,
107                                   String JavaDoc split, boolean delimInside) {
108         int sz = str.length();
109
110         // System.err.println( ">>>> inside: " + delimInside + " sz : " + sz );
111

112         /// shift width up one. mainly as it makes the logic easier
113
width++;
114
115         // our best guess as to an initial size
116
StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(sz/width*delim.length()+sz);
117
118         // every line might include a delim on the end
119
// System.err.println( "width before: "+ width );
120
if ( delimInside ) {
121           width = width - delim.length();
122         } else {
123           width --;
124         }
125         // System.err.println( "width after: "+ width );
126

127         int idx = -1;
128         String JavaDoc substr = null;
129
130         // beware: i is rolled-back inside the loop
131
for(int i=0; i<sz; i+=width) {
132
133             // on the last line
134
if(i > sz - width) {
135                 buffer.append(str.substring(i));
136 // System.err.print("LAST-LINE: "+str.substring(i));
137
break;
138             }
139
140 // System.err.println("loop[i] is: "+i);
141
// the current line
142
substr = str.substring(i, i+width);
143             // System.err.println( "substr: " + substr );
144

145             // is the delim already on the line
146
idx = substr.indexOf(delim);
147             // System.err.println( "i: " + i + " idx : " + idx );
148
if(idx != -1) {
149                 buffer.append(substr.substring(0,idx));
150 // System.err.println("Substr: '"substr.substring(0,idx)+"'");
151
buffer.append(delim);
152                 i -= width-idx-delim.length();
153                 
154 // System.err.println("loop[i] is now: "+i);
155
// System.err.println("ounfd-whitespace: '"+substr.charAt(idx+1)+"'.");
156
// Erase a space after a delim. Is this too obscure?
157
if(substr.length() > idx+1) {
158                     if(substr.charAt(idx+1) != '\n') {
159                         if(Character.isWhitespace(substr.charAt(idx+1))) {
160                             i++;
161                         }
162                     }
163                 }
164 // System.err.println("i -= "+width+"-"+idx);
165
continue;
166             }
167
168             idx = -1;
169
170             // figure out where the last space is
171
char[] chrs = substr.toCharArray();
172             for(int j=width; j>0; j--) {
173                 if(Character.isWhitespace(chrs[j-1])) {
174                     idx = j;
175 // System.err.println("Found whitespace: "+idx);
176
break;
177                 }
178             }
179
180             // idx is the last whitespace on the line.
181
// System.err.println("idx is "+idx);
182
if(idx == -1) {
183                 for(int j=width; j>0; j--) {
184                     if(chrs[j-1] == '-') {
185                         idx = j;
186 // System.err.println("Found Dash: "+idx);
187
break;
188                     }
189                 }
190                 if(idx == -1) {
191                     buffer.append(substr);
192                     buffer.append(delim);
193 // System.err.print(substr);
194
// System.err.print(delim);
195
} else {
196                     if(idx != width) {
197                         idx++;
198                     }
199                     buffer.append(substr.substring(0,idx));
200                     buffer.append(delim);
201 // System.err.print(substr.substring(0,idx));
202
// System.err.print(delim);
203
i -= width-idx;
204                 }
205             } else {
206                 /*
207                 if(force) {
208                     if(idx == width-1) {
209                         buffer.append(substr);
210                         buffer.append(delim);
211                     } else {
212                         // stick a split in.
213                         int splitsz = split.length();
214                         buffer.append(substr.substring(0,width-splitsz));
215                         buffer.append(split);
216                         buffer.append(delim);
217                         i -= splitsz;
218                     }
219                 } else {
220                 */

221                     // insert spaces
222
buffer.append(substr.substring(0,idx));
223                     buffer.append(StringUtils.repeat(" ",width-idx));
224 // System.err.print(substr.substring(0,idx));
225
// System.err.print(StringUtils.repeat(" ",width-idx));
226
buffer.append(delim);
227 // System.err.print(delim);
228
// System.err.println("i -= "+width+"-"+idx);
229
i -= width-idx;
230 // }
231
}
232         }
233 // System.err.println("\n*************");
234
return buffer.toString();
235     }
236
237     /**
238      * Truncates a string nicely. It will search for the first space
239      * after the lower limit and truncate the string there. It will
240      * also append any string passed as a parameter to the end of the
241      * string. The hard limit can be specified to forcibily truncate a
242      * string (in the case of an extremely long word or such). All
243      * HTML/XML markup will be stripped from the string prior to
244      * processing for truncation.
245      *
246      * @param str String the string to be truncated.
247      * @param lower int value of the lower limit.
248      * @param upper int value of the upper limit, -1 if no limit is
249      * desired. If the uppper limit is lower than the
250      * lower limit, it will be adjusted to be same as
251      * the lower limit.
252      * @param appendToEnd String to be appended to the end of the
253      * truncated string.
254      * This is appended ONLY if the string was indeed
255      * truncated. The append is does not count towards
256      * any lower/upper limits.
257      *
258      * @author timster@mac.com
259      */

260     public static String JavaDoc truncateNicely(String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd)
261     {
262         // strip markup from the string
263
str = XmlW.removeXml(str);
264         
265         // quickly adjust the upper if it is set lower than 'lower'
266
if(upper < lower) {
267             upper = lower;
268         }
269         
270         // now determine if the string fits within the upper limit
271
// if it does, go straight to return, do not pass 'go' and collect $200
272
if(str.length() > upper) {
273             // the magic location int
274
int loc;
275         
276             // first we determine where the next space appears after lower
277
loc = str.lastIndexOf(' ', upper);
278             
279             // now we'll see if the location is greater than the lower limit
280
if(loc >= lower) {
281                 // yes it was, so we'll cut it off here
282
str = str.substring(0, loc);
283             } else {
284                 // no it wasnt, so we'll cut it off at the upper limit
285
str = str.substring(0, upper);
286             }
287     
288             // the string was truncated, so we append the appendToEnd String
289
str = str + appendToEnd;
290         }
291         
292         return str;
293     }
294 }
295
Popular Tags