KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > iapi > util > StringUtil


1 /*
2
3    Derby - Class com.ihost.cs.StringUtil
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to you under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derby.iapi.util;
23 import java.util.Locale JavaDoc;
24
25 /**
26     A set of public static methods for dealing with Strings
27 */

28 public class StringUtil
29 {
30     /**
31      * Used to print out a string for error messages,
32      * chops is off at 60 chars for historical reasons.
33      */

34     public final static String JavaDoc formatForPrint(String JavaDoc input)
35     {
36         if (input.length() > 60)
37         {
38             StringBuffer JavaDoc tmp = new StringBuffer JavaDoc(input.substring(0, 60));
39             tmp.append("&");
40             input = tmp.toString();
41         }
42         return input;
43     }
44
45     /**
46      * A method that receive an array of Objects and return a
47      * String array representation of that array.
48      */

49     public static String JavaDoc [] toStringArray(Object JavaDoc [] objArray) {
50         int idx;
51         int len=objArray.length;
52         String JavaDoc [] strArray=new String JavaDoc[len];
53
54         for (idx=0 ; idx<len ; idx++) {
55             strArray[idx]=objArray[idx].toString();
56         }
57
58         return strArray;
59     }
60
61     /**
62         Get 7-bit ASCII character array from input String.
63         The lower 7 bits of each character in the input string is assumed to be
64         the ASCII character value.
65
66      Hexadecimal - Character
67
68      | 00 NUL| 01 SOH| 02 STX| 03 ETX| 04 EOT| 05 ENQ| 06 ACK| 07 BEL|
69      | 08 BS | 09 HT | 0A NL | 0B VT | 0C NP | 0D CR | 0E SO | 0F SI |
70      | 10 DLE| 11 DC1| 12 DC2| 13 DC3| 14 DC4| 15 NAK| 16 SYN| 17 ETB|
71      | 18 CAN| 19 EM | 1A SUB| 1B ESC| 1C FS | 1D GS | 1E RS | 1F US |
72      | 20 SP | 21 ! | 22 " | 23 # | 24 $ | 25 % | 26 & | 27 ' |
73      | 28 ( | 29 ) | 2A * | 2B + | 2C , | 2D - | 2E . | 2F / |
74      | 30 0 | 31 1 | 32 2 | 33 3 | 34 4 | 35 5 | 36 6 | 37 7 |
75      | 38 8 | 39 9 | 3A : | 3B ; | 3C < | 3D = | 3E > | 3F ? |
76      | 40 @ | 41 A | 42 B | 43 C | 44 D | 45 E | 46 F | 47 G |
77      | 48 H | 49 I | 4A J | 4B K | 4C L | 4D M | 4E N | 4F O |
78      | 50 P | 51 Q | 52 R | 53 S | 54 T | 55 U | 56 V | 57 W |
79      | 58 X | 59 Y | 5A Z | 5B [ | 5C \ | 5D ] | 5E ^ | 5F _ |
80      | 60 ` | 61 a | 62 b | 63 c | 64 d | 65 e | 66 f | 67 g |
81      | 68 h | 69 i | 6A j | 6B k | 6C l | 6D m | 6E n | 6F o |
82      | 70 p | 71 q | 72 r | 73 s | 74 t | 75 u | 76 v | 77 w |
83      | 78 x | 79 y | 7A z | 7B { | 7C | | 7D } | 7E ~ | 7F DEL|
84
85      */

86     public static byte[] getAsciiBytes(String JavaDoc input)
87     {
88         char[] c = input.toCharArray();
89         byte[] b = new byte[c.length];
90         for (int i = 0; i < c.length; i++)
91             b[i] = (byte)(c[i] & 0x007F);
92
93         return b;
94     }
95
96     /**
97      * Trim off trailing blanks but not leading blanks
98      *
99      * @param str
100      *
101      * @return The input with trailing blanks stipped off
102      */

103     public static String JavaDoc trimTrailing( String JavaDoc str)
104     {
105         if( str == null)
106             return null;
107         int len = str.length();
108         for( ; len > 0; len--)
109         {
110             if( ! Character.isWhitespace( str.charAt( len - 1)))
111                 break;
112         }
113         return str.substring( 0, len);
114     } // end of trimTrailing
115

116
117     /**
118         Truncate a String to the given length with no warnings
119         or error raised if it is bigger.
120     
121         @param value String to be truncated
122         @param length Maximum length of string
123
124         @return Returns value if value is null or value.length() is less or equal to than length, otherwise a String representing
125             value truncated to length.
126     */

127     public static String JavaDoc truncate(String JavaDoc value, int length)
128     {
129         if (value != null && value.length() > length)
130             value = value.substring(0, length);
131         return value;
132     }
133     
134     /**
135      * Return a slice (substring) of the passed in value, optionally trimmed.
136      * WARNING - endOffset is inclusive for historical reasons, unlike
137      * String.substring() which has an exclusive ending offset.
138      * @param value Value to slice, must be non-null.
139      * @param beginOffset Inclusive start character
140      * @param endOffset Inclusive end character
141      * @param trim To trim or not to trim
142      * @return Sliceed value.
143      */

144     public static String JavaDoc slice(String JavaDoc value,
145             int beginOffset, int endOffset,
146             boolean trim)
147     {
148         String JavaDoc retval = value.substring(beginOffset, endOffset + 1);
149         
150         if (trim)
151             retval = retval.trim();
152         
153         return retval;
154     }
155
156
157     private static char[] hex_table = {
158                 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
159                 'a', 'b', 'c', 'd', 'e', 'f'
160             };
161
162
163     /**
164         Convert a byte array to a String with a hexidecimal format.
165         The String may be converted back to a byte array using fromHexString.
166         <BR>
167         For each byte (b) two characaters are generated, the first character
168         represents the high nibble (4 bits) in hexidecimal (<code>b & 0xf0</code>), the second character
169         represents the low nibble (<code>b & 0x0f</code>).
170         <BR>
171         The byte at <code>data[offset]</code> is represented by the first two characters in the returned String.
172
173         @param data byte array
174         @param offset starting byte (zero based) to convert.
175         @param length number of bytes to convert.
176
177         @return the String (with hexidecimal format) form of the byte array
178     */

179     public static String JavaDoc toHexString(byte[] data, int offset, int length)
180     {
181         StringBuffer JavaDoc s = new StringBuffer JavaDoc(length*2);
182         int end = offset+length;
183
184         for (int i = offset; i < end; i++)
185         {
186             int high_nibble = (data[i] & 0xf0) >>> 4;
187             int low_nibble = (data[i] & 0x0f);
188             s.append(hex_table[high_nibble]);
189             s.append(hex_table[low_nibble]);
190         }
191
192         return s.toString();
193     }
194
195     /**
196
197         Convert a string into a byte array in hex format.
198         <BR>
199         For each character (b) two bytes are generated, the first byte
200         represents the high nibble (4 bits) in hexidecimal (<code>b & 0xf0</code>),
201         the second byte represents the low nibble (<code>b & 0x0f</code>).
202         <BR>
203         The character at <code>str.charAt(0)</code> is represented by the first two bytes
204         in the returned String.
205
206         @param str string
207         @param offset starting character (zero based) to convert.
208         @param length number of characters to convert.
209
210         @return the byte[] (with hexidecimal format) form of the string (str)
211     */

212     public static byte[] toHexByte(String JavaDoc str, int offset, int length)
213     {
214         byte[] data = new byte[(length - offset) * 2];
215         int end = offset+length;
216
217         for (int i = offset; i < end; i++)
218         {
219             char ch = str.charAt(i);
220             int high_nibble = (ch & 0xf0) >>> 4;
221             int low_nibble = (ch & 0x0f);
222             data[i] = (byte)high_nibble;
223             data[i+1] = (byte)low_nibble;
224         }
225         return data;
226     }
227         
228     /**
229         Convert a hexidecimal string generated by toHexString() back
230         into a byte array.
231
232         @param s String to convert
233         @param offset starting character (zero based) to convert.
234         @param length number of characters to convert.
235
236         @return the converted byte array. Returns null if the length is
237         not a multiple of 2.
238     */

239     public static byte[] fromHexString(String JavaDoc s, int offset, int length)
240     {
241         if ((length%2) != 0)
242             return null;
243
244         byte[] byteArray = new byte[length/2];
245
246         int j = 0;
247         int end = offset+length;
248         for (int i = offset; i < end; i += 2)
249         {
250             int high_nibble = Character.digit(s.charAt(i), 16);
251             int low_nibble = Character.digit(s.charAt(i+1), 16);
252
253             if (high_nibble == -1 || low_nibble == -1)
254             {
255                 // illegal format
256
return null;
257             }
258
259             byteArray[j++] = (byte)(((high_nibble << 4) & 0xf0) | (low_nibble & 0x0f));
260         }
261         return byteArray;
262     }
263     /**
264         Convert a byte array to a human-readable String for debugging purposes.
265     */

266     public static String JavaDoc hexDump(byte[] data)
267     {
268             byte byte_value;
269
270
271             StringBuffer JavaDoc str = new StringBuffer JavaDoc(data.length * 3);
272
273             str.append("Hex dump:\n");
274
275             for (int i = 0; i < data.length; i += 16)
276             {
277                 // dump the header: 00000000:
278
String JavaDoc offset = Integer.toHexString(i);
279
280                 // "0" left pad offset field so it is always 8 char's long.
281
for (int offlen = offset.length(); offlen < 8; offlen++)
282                     str.append("0");
283                 str.append(offset);
284                 str.append(":");
285
286                 // dump hex version of 16 bytes per line.
287
for (int j = 0; (j < 16) && ((i + j) < data.length); j++)
288                 {
289                     byte_value = data[i + j];
290
291                     // add spaces between every 2 bytes.
292
if ((j % 2) == 0)
293                         str.append(" ");
294
295                     // dump a single byte.
296
byte high_nibble = (byte) ((byte_value & 0xf0) >>> 4);
297                     byte low_nibble = (byte) (byte_value & 0x0f);
298
299                     str.append(hex_table[high_nibble]);
300                     str.append(hex_table[low_nibble]);
301                 }
302
303                 // dump ascii version of 16 bytes
304
str.append(" ");
305
306                 for (int j = 0; (j < 16) && ((i + j) < data.length); j++)
307                 {
308                     char char_value = (char) data[i + j];
309
310                     // RESOLVE (really want isAscii() or isPrintable())
311
if (Character.isLetterOrDigit(char_value))
312                         str.append(String.valueOf(char_value));
313                     else
314                         str.append(".");
315                 }
316                     
317                 // new line
318
str.append("\n");
319             }
320             return(str.toString());
321
322     }
323
324     // The functions below are used for uppercasing SQL in a consistent manner.
325
// Cloudscape will uppercase Turkish to the English locale to avoid i
326
// uppercasing to an uppercase dotted i. In future versions, all
327
// casing will be done in English. The result will be that we will get
328
// only the 1:1 mappings in
329
// http://www.unicode.org/Public/3.0-Update1/UnicodeData-3.0.1.txt
330
// and avoid the 1:n mappings in
331
//http://www.unicode.org/Public/3.0-Update1/SpecialCasing-3.txt
332
//
333
// Any SQL casing should use these functions
334

335
336     /** Convert string to uppercase
337      * Always use the java.util.ENGLISH locale
338      * @param s string to uppercase
339      * @return uppercased string
340      */

341     public static String JavaDoc SQLToUpperCase(String JavaDoc s)
342     {
343             return s.toUpperCase(Locale.ENGLISH);
344     }
345
346
347     /** Convert string to lowercase
348      * Return java.util.Locale.ENGLISH lowercasing
349      * @param s string to lowercase
350      * @return lowercased string
351      */

352     public static String JavaDoc SQLToLowerCase(String JavaDoc s)
353     {
354         return s.toLowerCase(Locale.ENGLISH);
355
356     }
357
358
359     /** Compares two strings
360      * Strings will be uppercased in english and compared
361      * equivalent to s1.equalsIgnoreCase(s2)
362      * throws NPE if s1 is null
363      *
364      * @param s1 first string to compare
365      * @param s2 second string to compare
366      *
367      * @return true if the two upppercased ENGLISH values are equal
368      * return false if s2 is null
369      */

370     public static boolean SQLEqualsIgnoreCase(String JavaDoc s1, String JavaDoc s2)
371     {
372         if (s2 == null)
373             return false;
374         else
375             return s1.toUpperCase(Locale.ENGLISH).equals(s2.toUpperCase(Locale.ENGLISH));
376
377     }
378
379 }
380
381
Popular Tags