KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jorphan > util > JOrphanUtils


1 // $Header: /home/cvs/jakarta-jmeter/src/jorphan/org/apache/jorphan/util/JOrphanUtils.java,v 1.10.2.1 2005/02/20 19:43:50 sebb Exp $
2
/*
3  * Copyright 2002-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17 */

18
19 package org.apache.jorphan.util;
20
21 import java.io.UnsupportedEncodingException JavaDoc;
22 import java.lang.reflect.Method JavaDoc;
23 import java.net.URLDecoder JavaDoc;
24 import java.net.URLEncoder JavaDoc;
25 import java.util.Vector JavaDoc;
26
27 import junit.framework.TestCase;
28
29 /**
30  * This class contains frequently-used static utility methods.
31  *
32  * @author <a HREF="mailto://jsalvata@atg.com">Jordi Salvat i Alabart</a>
33  * Created 27th December 2002
34  * @version $Revision: 1.10.2.1 $ Last updated: $Date: 2005/02/20 19:43:50 $
35  */

36 public final class JOrphanUtils
37 {
38     /**
39      * Private constructor to prevent instantiation.
40      */

41     private JOrphanUtils()
42     {
43     }
44     
45     /**
46      * This is _almost_ equivalent to the String.split method in JDK 1.4. It is
47      * here to enable us to support earlier JDKs.
48      *
49      * Note that unlike JDK1.4 spilt(), it ignores leading split Characters.
50      *
51      * <P>This piece of code used to be part of JMeterUtils, but was moved
52      * here because some JOrphan classes use it too.
53      *
54      * @param splittee String to be split
55      * @param splitChar Character to split the string on
56      * @return Array of all the tokens.
57      */

58     public static String JavaDoc[] split(String JavaDoc splittee, String JavaDoc splitChar)
59     {
60         if (splittee == null || splitChar == null)
61         {
62             return new String JavaDoc[0];
63         }
64         int spot;
65         while ((spot = splittee.indexOf(splitChar + splitChar)) != -1)
66         {
67             splittee =
68                 splittee.substring(0, spot + splitChar.length())
69                     + splittee.substring(
70                         spot + 2 * splitChar.length(),
71                         splittee.length());
72         }
73         Vector JavaDoc returns = new Vector JavaDoc();
74         int start = 0;
75         int length = splittee.length();
76         spot = 0;
77         while (start < length
78             && (spot = splittee.indexOf(splitChar, start)) > -1)
79         {
80             if (spot > 0)
81             {
82                 returns.addElement(splittee.substring(start, spot));
83             }
84             start = spot + splitChar.length();
85         }
86         if (start < length)
87         {
88             returns.add(splittee.substring(start));
89         }
90         String JavaDoc[] values = new String JavaDoc[returns.size()];
91         returns.copyInto(values);
92         return values;
93     }
94
95     private static final String JavaDoc SPACES = " ";
96     private static final int SPACES_LEN = SPACES.length();
97
98     /**
99      * Right aligns some text in a StringBuffer
100      * N.B. modifies the input buffer
101      *
102      * @param in StringBuffer containing some text
103      * @param len output length desired
104      * @return input StringBuffer, with leading spaces
105      */

106     public static StringBuffer JavaDoc rightAlign(StringBuffer JavaDoc in, int len){
107         int pfx = len - in.length();
108         if (pfx <= 0 ) return in;
109         if (pfx > SPACES_LEN) pfx = SPACES_LEN;
110         in.insert(0,SPACES.substring(0,pfx));
111         return in;
112     }
113     
114     /**
115      * Left aligns some text in a StringBuffer
116      * N.B. modifies the input buffer
117      *
118      * @param in StringBuffer containing some text
119      * @param len output length desired
120      * @return input StringBuffer, with trailing spaces
121      */

122     public static StringBuffer JavaDoc leftAlign(StringBuffer JavaDoc in, int len){
123         int sfx = len - in.length();
124         if (sfx <= 0 ) return in;
125         if (sfx > SPACES_LEN) sfx = SPACES_LEN;
126         in.append(SPACES.substring(0,sfx));
127         return in;
128     }
129     
130     /**
131      * Convert a boolean to its string representation
132      * Equivalent to Boolean.valueOf(boolean).toString()
133      * but valid also for JDK 1.3, which does not have valueOf(boolean)
134      *
135      * @param value boolean to convert
136      * @return "true" or "false"
137      */

138     public static String JavaDoc booleanToString(boolean value){
139         return value ? "true" : "false";
140     }
141
142     /**
143      * Convert a boolean to its string representation
144      * Equivalent to Boolean.valueOf(boolean).toString().toUpperCase()
145      * but valid also for JDK 1.3, which does not have valueOf(boolean)
146      *
147      * @param value boolean to convert
148      * @return "TRUE" or "FALSE"
149      */

150     public static String JavaDoc booleanToSTRING(boolean value){
151         return value ? "TRUE" : "FALSE";
152     }
153     
154     /**
155      * Version of Boolean.valueOf() for JDK 1.3
156      *
157      * @param value boolean to convert
158      * @return Boolean.TRUE or Boolean.FALSE
159      */

160     public static Boolean JavaDoc valueOf(boolean value)
161     {
162         return value ? Boolean.TRUE : Boolean.FALSE;
163     }
164     
165     private static Method JavaDoc decodeMethod = null;
166     private static Method JavaDoc encodeMethod = null;
167     
168     static {
169         Class JavaDoc URLEncoder = URLEncoder JavaDoc.class;
170         Class JavaDoc URLDecoder = URLDecoder JavaDoc.class;
171         Class JavaDoc [] argTypes = { String JavaDoc.class, String JavaDoc.class };
172         try
173         {
174             decodeMethod = URLDecoder.getMethod("decode",argTypes);
175             encodeMethod = URLEncoder.getMethod("encode",argTypes);
176             //System.out.println("Using JDK1.4 xxcode() calls");
177
}
178         catch (Exception JavaDoc e)
179         {
180             //e.printStackTrace();
181
}
182         //System.out.println("java.version="+System.getProperty("java.version"));
183
}
184     
185     /**
186      * Version of URLEncoder().encode(string,encoding) for JDK1.3
187      * Also supports JDK1.4 (but will be a bit slower)
188      *
189      * @param string to be encoded
190      * @param encoding (ignored for JDK1.3)
191      * @return the encoded string
192      */

193     public static String JavaDoc encode(String JavaDoc string, String JavaDoc encoding)
194     throws UnsupportedEncodingException JavaDoc
195     {
196         if (encodeMethod != null) {
197             //JDK1.4: return URLEncoder.encode(string, encoding);
198
Object JavaDoc args [] = {string,encoding};
199             try
200             {
201                 return (String JavaDoc) encodeMethod.invoke(null, args );
202             }
203             catch (Exception JavaDoc e)
204             {
205                 e.printStackTrace();
206                 return string;
207             }
208         } else {
209             return URLEncoder.encode(string);
210         }
211         
212     }
213
214     /**
215      * Version of URLDecoder().decode(string,encoding) for JDK1.3
216      * Also supports JDK1.4 (but will be a bit slower)
217      *
218      * @param string to be decoded
219      * @param encoding (ignored for JDK1.3)
220      * @return the encoded string
221      */

222     public static String JavaDoc decode(String JavaDoc string, String JavaDoc encoding)
223     throws UnsupportedEncodingException JavaDoc
224     {
225         if (decodeMethod != null) {
226             //JDK1.4: return URLDecoder.decode(string, encoding);
227
Object JavaDoc args [] = {string,encoding};
228             try {
229                 return (String JavaDoc) decodeMethod.invoke(null, args );
230             }
231             catch (Exception JavaDoc e)
232             {
233                 e.printStackTrace();
234                 return string;
235             }
236         } else {
237             return URLDecoder.decode(string);
238         }
239     }
240
241     /**
242      * Simple-minded String.replace() for JDK1.3
243      * Should probably be recoded...
244      *
245      * @param source input string
246      * @param search string to look for (no regular expressions)
247      * @param replace string to replace the search string
248      * @return the output string
249      */

250     public static String JavaDoc replaceFirst(String JavaDoc source, String JavaDoc search,String JavaDoc replace)
251     {
252         int start=source.indexOf(search);
253         int len=search.length();
254         if (start == -1) return source;
255         if (start == 0) return replace+source.substring(len);
256         return source.substring(0,start)+replace+source.substring(start+len);
257     }
258     
259     public static class Test extends TestCase
260     {
261         public void testReplace1()
262         {
263             assertEquals("xyzdef",replaceFirst("abcdef","abc","xyz"));
264         }
265         public void testReplace2()
266         {
267             assertEquals("axyzdef",replaceFirst("abcdef","bc","xyz"));
268         }
269         public void testReplace3()
270         {
271             assertEquals("abcxyz",replaceFirst("abcdef","def","xyz"));
272         }
273         public void testReplace4()
274         {
275             assertEquals("abcdef",replaceFirst("abcdef","bce","xyz"));
276         }
277         public void testReplace5()
278         {
279             assertEquals("abcdef",replaceFirst("abcdef","alt=\"\" ",""));
280         }
281         public void testReplace6()
282         {
283             assertEquals("abcdef",replaceFirst("abcdef","alt=\"\" ",""));
284         }
285         public void testReplace7()
286         {
287             assertEquals("alt=\"\"",replaceFirst("alt=\"\"","alt=\"\" ",""));
288         }
289         public void testReplace8()
290         {
291             assertEquals("img SRC=xyz ",replaceFirst("img SRC=xyz alt=\"\" ","alt=\"\" ",""));
292         }
293         public void testSplit1()
294         {
295             String JavaDoc in="a,bc,,"; // Test ignore trailing split characters
296
String JavaDoc out[]=split(in,",");
297             assertEquals(2,out.length);
298             assertEquals("a",out[0]);
299             assertEquals("bc",out[1]);
300         }
301         public void testSplit2()
302         {
303             String JavaDoc in=",,a,bc"; // Test leading split characters
304
String JavaDoc out[]=split(in,",");
305             assertEquals("Should detect the leading split chars; ",2,out.length-2);
306             assertEquals("",out[0]);
307             assertEquals("",out[1]);
308             assertEquals("a",out[2]);
309             assertEquals("bc",out[3]);
310         }
311     }
312 }
313
Popular Tags