EMMA Coverage Report (generated Fri May 26 15:35:26 CDT 2006)
[all classes][com.mysql.jdbc]

COVERAGE SUMMARY FOR SOURCE FILE [StringUtils.java]

nameclass, %method, %block, %line, %
StringUtils.java100% (1/1)91%  (29/32)70%  (1488/2135)72%  (345.4/482)

COVERAGE BREAKDOWN BY CLASS AND METHOD

nameclass, %method, %block, %line, %
     
class StringUtils100% (1/1)91%  (29/32)70%  (1488/2135)72%  (345.4/482)
StringUtils (): void 0%   (0/1)0%   (0/3)0%   (0/1)
getBytes (char [], SingleByteCharsetConverter, String, String, boolean): byte [] 0%   (0/1)0%   (0/72)0%   (0/13)
getBytes (char [], String, String, boolean): byte [] 0%   (0/1)0%   (0/29)0%   (0/4)
wildCompare (String, String): int 100% (1/1)5%   (10/209)5%   (3/55)
getBytes (String, SingleByteCharsetConverter, String, String, int, int, boole... 100% (1/1)13%  (13/99)22%  (4/18)
getBytes (char [], SingleByteCharsetConverter, String, String, int, int, bool... 100% (1/1)33%  (33/101)51%  (9.7/19)
getBytes (String, String, String, boolean): byte [] 100% (1/1)38%  (11/29)50%  (2/4)
getBytes (String, SingleByteCharsetConverter, String, String, boolean): byte [] 100% (1/1)66%  (42/64)75%  (9/12)
consistentToString (BigDecimal): String 100% (1/1)72%  (13/18)50%  (4/8)
getLong (byte []): long 100% (1/1)78%  (125/160)79%  (28.6/36)
startsWithIgnoreCaseAndWs (String, String): boolean 100% (1/1)81%  (25/31)88%  (7/8)
split (String, String, boolean): List 100% (1/1)81%  (35/43)83%  (10/12)
startsWithIgnoreCaseAndNonAlphaNumeric (String, String): boolean 100% (1/1)82%  (27/33)89%  (8/9)
getInt (byte []): int 100% (1/1)84%  (123/147)85%  (30.6/36)
firstNonWsCharUc (String): char 100% (1/1)85%  (22/26)75%  (6/8)
getShort (byte []): short 100% (1/1)85%  (132/156)85%  (30.6/36)
indexOfIgnoreCaseRespectMarker (int, String, String, String, String, boolean)... 100% (1/1)87%  (69/79)93%  (16.7/18)
split (String, String, String, String, boolean): List 100% (1/1)88%  (61/69)89%  (17/19)
indexOfIgnoreCaseRespectQuotes (int, String, String, char, boolean): int 100% (1/1)89%  (59/66)93%  (14/15)
endsWith (byte [], String): boolean 100% (1/1)93%  (27/29)83%  (5/6)
indexOfIgnoreCase (int, String, String): int 100% (1/1)94%  (98/104)86%  (23.3/27)
escapeEasternUnicodeByteStream (byte [], String, int, int): byte [] 100% (1/1)97%  (111/115)97%  (34/35)
<static initializer> 100% (1/1)98%  (61/62)99%  (12.9/13)
dumpAsHex (byte [], int): String 100% (1/1)100% (208/208)100% (34/34)
fixDecimalExponent (String): String 100% (1/1)100% (68/68)100% (13/13)
indexOfIgnoreCase (String, String): int 100% (1/1)100% (5/5)100% (1/1)
startsWith (byte [], String): boolean 100% (1/1)100% (19/19)100% (4/4)
startsWithIgnoreCase (String, String): boolean 100% (1/1)100% (5/5)100% (1/1)
startsWithIgnoreCase (String, int, String): boolean 100% (1/1)100% (9/9)100% (1/1)
stripEnclosure (byte [], String, String): byte [] 100% (1/1)100% (46/46)100% (9/9)
toAsciiString (byte []): String 100% (1/1)100% (6/6)100% (1/1)
toAsciiString (byte [], int, int): String 100% (1/1)100% (25/25)100% (6/6)

1/*
2 Copyright (C) 2002-2004 MySQL AB
3 
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of version 2 of the GNU General Public License as 
6 published by the Free Software Foundation.
7 
8 There are special exceptions to the terms and conditions of the GPL 
9 as it is applied to this software. View the full text of the 
10 exception in file EXCEPTIONS-CONNECTOR-J in the directory of this 
11 software distribution.
12 
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 
22 
23 
24 */
25package com.mysql.jdbc;
26 
27import java.io.ByteArrayOutputStream;
28import java.io.UnsupportedEncodingException;
29import java.lang.reflect.InvocationTargetException;
30import java.lang.reflect.Method;
31import java.math.BigDecimal;
32 
33import java.sql.SQLException;
34 
35import java.util.ArrayList;
36import java.util.List;
37import java.util.StringTokenizer;
38 
39/**
40 * Various utility methods for converting to/from byte arrays in the platform
41 * encoding
42 * 
43 * @author Mark Matthews
44 */
45public class StringUtils {
46        
47        private static final int BYTE_RANGE = (1 + Byte.MAX_VALUE) - Byte.MIN_VALUE;
48 
49        private static byte[] allBytes = new byte[BYTE_RANGE];
50 
51        private static char[] byteToChars = new char[BYTE_RANGE];
52 
53        private static Method toPlainStringMethod;
54 
55        static final int WILD_COMPARE_MATCH_NO_WILD = 0;
56 
57        static final int WILD_COMPARE_MATCH_WITH_WILD = 1;
58 
59        static final int WILD_COMPARE_NO_MATCH = -1;
60 
61        static {
62                for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) {
63                        allBytes[i - Byte.MIN_VALUE] = (byte) i;
64                }
65 
66                String allBytesString = new String(allBytes, 0, Byte.MAX_VALUE
67                                - Byte.MIN_VALUE);
68 
69                int allBytesStringLen = allBytesString.length();
70 
71                for (int i = 0; (i < (Byte.MAX_VALUE - Byte.MIN_VALUE))
72                                && (i < allBytesStringLen); i++) {
73                        byteToChars[i] = allBytesString.charAt(i);
74                }
75 
76                try {
77                        toPlainStringMethod = BigDecimal.class.getMethod("toPlainString",
78                                        new Class[0]);
79                } catch (NoSuchMethodException nsme) {
80                        // that's okay, we fallback to .toString()
81                }
82        }
83 
84        /**
85         * Takes care of the fact that Sun changed the output of
86         * BigDecimal.toString() between JDK-1.4 and JDK 5
87         * 
88         * @param decimal
89         *            the big decimal to stringify
90         * 
91         * @return a string representation of 'decimal'
92         */
93        public static String consistentToString(BigDecimal decimal) {
94                if (decimal == null) {
95                        return null;
96                }
97 
98                if (toPlainStringMethod != null) {
99                        try {
100                                return (String) toPlainStringMethod.invoke(decimal, null);
101                        } catch (InvocationTargetException invokeEx) {
102                                // that's okay, we fall-through to decimal.toString()
103                        } catch (IllegalAccessException accessEx) {
104                                // that's okay, we fall-through to decimal.toString()
105                        }
106                }
107 
108                return decimal.toString();
109        }
110 
111        /**
112         * Dumps the given bytes to STDOUT as a hex dump (up to length bytes).
113         * 
114         * @param byteBuffer
115         *            the data to print as hex
116         * @param length
117         *            the number of bytes to print
118         * 
119         * @return ...
120         */
121        public static final String dumpAsHex(byte[] byteBuffer, int length) {
122                StringBuffer outputBuf = new StringBuffer(length * 4);
123 
124                int p = 0;
125                int rows = length / 8;
126 
127                for (int i = 0; (i < rows) && (p < length); i++) {
128                        int ptemp = p;
129 
130                        for (int j = 0; j < 8; j++) {
131                                String hexVal = Integer.toHexString(byteBuffer[ptemp] & 0xff);
132 
133                                if (hexVal.length() == 1) {
134                                        hexVal = "0" + hexVal; //$NON-NLS-1$
135                                }
136 
137                                outputBuf.append(hexVal + " "); //$NON-NLS-1$
138                                ptemp++;
139                        }
140 
141                        outputBuf.append("    "); //$NON-NLS-1$
142 
143                        for (int j = 0; j < 8; j++) {
144                                if ((byteBuffer[p] > 32) && (byteBuffer[p] < 127)) {
145                                        outputBuf.append((char) byteBuffer[p] + " "); //$NON-NLS-1$
146                                } else {
147                                        outputBuf.append(". "); //$NON-NLS-1$
148                                }
149 
150                                p++;
151                        }
152 
153                        outputBuf.append("\n"); //$NON-NLS-1$
154                }
155 
156                int n = 0;
157 
158                for (int i = p; i < length; i++) {
159                        String hexVal = Integer.toHexString(byteBuffer[i] & 0xff);
160 
161                        if (hexVal.length() == 1) {
162                                hexVal = "0" + hexVal; //$NON-NLS-1$
163                        }
164 
165                        outputBuf.append(hexVal + " "); //$NON-NLS-1$
166                        n++;
167                }
168 
169                for (int i = n; i < 8; i++) {
170                        outputBuf.append("   "); //$NON-NLS-1$
171                }
172 
173                outputBuf.append("    "); //$NON-NLS-1$
174 
175                for (int i = p; i < length; i++) {
176                        if ((byteBuffer[i] > 32) && (byteBuffer[i] < 127)) {
177                                outputBuf.append((char) byteBuffer[i] + " "); //$NON-NLS-1$
178                        } else {
179                                outputBuf.append(". "); //$NON-NLS-1$
180                        }
181                }
182 
183                outputBuf.append("\n"); //$NON-NLS-1$
184 
185                return outputBuf.toString();
186        }
187 
188        private static boolean endsWith(byte[] dataFrom, String suffix) {
189                for (int i = 1; i <= suffix.length(); i++) {
190                        int dfOffset = dataFrom.length - i;
191                        int suffixOffset = suffix.length() - i;
192                        if (dataFrom[dfOffset] != suffix.charAt(suffixOffset)) {
193                                return false;
194                        }
195                }
196                return true;
197        }
198 
199        /**
200         * Unfortunately, SJIS has 0x5c as a high byte in some of its double-byte
201         * characters, so we need to escape it.
202         * 
203         * @param origBytes
204         *            the original bytes in SJIS format
205         * @param origString
206         *            the string that had .getBytes() called on it
207         * @param offset
208         *            where to start converting from
209         * @param length
210         *            how many characters to convert.
211         * 
212         * @return byte[] with 0x5c escaped
213         */
214        public static byte[] escapeEasternUnicodeByteStream(byte[] origBytes,
215                        String origString, int offset, int length) {
216                if ((origBytes == null) || (origBytes.length == 0)) {
217                        return origBytes;
218                }
219 
220                int bytesLen = origBytes.length;
221                int bufIndex = 0;
222                int strIndex = 0;
223 
224                ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(bytesLen);
225 
226                while (true) {
227                        if (origString.charAt(strIndex) == '\\') {
228                                // write it out as-is
229                                bytesOut.write(origBytes[bufIndex++]);
230 
231                                // bytesOut.write(origBytes[bufIndex++]);
232                        } else {
233                                // Grab the first byte
234                                int loByte = origBytes[bufIndex];
235 
236                                if (loByte < 0) {
237                                        loByte += 256; // adjust for signedness/wrap-around
238                                }
239 
240                                // We always write the first byte
241                                bytesOut.write(loByte);
242 
243                                //
244                                // The codepage characters in question exist between
245                                // 0x81-0x9F and 0xE0-0xFC...
246                                //
247                                // See:
248                                //
249                                // http://www.microsoft.com/GLOBALDEV/Reference/dbcs/932.htm
250                                //
251                                // Problematic characters in GBK
252                                //
253                                // U+905C : CJK UNIFIED IDEOGRAPH
254                                //
255                                // Problematic characters in Big5
256                                //
257                                // B9F0 = U+5C62 : CJK UNIFIED IDEOGRAPH
258                                //
259                                if (loByte >= 0x80) {
260                                        if (bufIndex < (bytesLen - 1)) {
261                                                int hiByte = origBytes[bufIndex + 1];
262 
263                                                if (hiByte < 0) {
264                                                        hiByte += 256; // adjust for signedness/wrap-around
265                                                }
266 
267                                                // write the high byte here, and increment the index
268                                                // for the high byte
269                                                bytesOut.write(hiByte);
270                                                bufIndex++;
271 
272                                                // escape 0x5c if necessary
273                                                if (hiByte == 0x5C) {
274                                                        bytesOut.write(hiByte);
275                                                }
276                                        }
277                                } else if (loByte == 0x5c) {
278                                        if (bufIndex < (bytesLen - 1)) {
279                                                int hiByte = origBytes[bufIndex + 1];
280 
281                                                if (hiByte < 0) {
282                                                        hiByte += 256; // adjust for signedness/wrap-around
283                                                }
284 
285                                                if (hiByte == 0x62) {
286                                                        // we need to escape the 0x5c
287                                                        bytesOut.write(0x5c);
288                                                        bytesOut.write(0x62);
289                                                        bufIndex++;
290                                                }
291                                        }
292                                }
293 
294                                bufIndex++;
295                        }
296 
297                        if (bufIndex >= bytesLen) {
298                                // we're done
299                                break;
300                        }
301 
302                        strIndex++;
303                }
304 
305                return bytesOut.toByteArray();
306        }
307 
308        /**
309         * Returns the first non whitespace char, converted to upper case
310         * 
311         * @param searchIn
312         *            the string to search in
313         * 
314         * @return the first non-whitespace character, upper cased.
315         */
316        public static char firstNonWsCharUc(String searchIn) {
317                if (searchIn == null) {
318                        return 0;
319                }
320 
321                int length = searchIn.length();
322 
323                for (int i = 0; i < length; i++) {
324                        char c = searchIn.charAt(i);
325 
326                        if (!Character.isWhitespace(c)) {
327                                return Character.toUpperCase(c);
328                        }
329                }
330 
331                return 0;
332        }
333 
334        /**
335         * Adds '+' to decimal numbers that are positive (MySQL doesn't understand
336         * them otherwise
337         * 
338         * @param dString
339         *            The value as a string
340         * 
341         * @return String the string with a '+' added (if needed)
342         */
343        public static final String fixDecimalExponent(String dString) {
344                int ePos = dString.indexOf("E"); //$NON-NLS-1$
345 
346                if (ePos == -1) {
347                        ePos = dString.indexOf("e"); //$NON-NLS-1$
348                }
349 
350                if (ePos != -1) {
351                        if (dString.length() > (ePos + 1)) {
352                                char maybeMinusChar = dString.charAt(ePos + 1);
353 
354                                if (maybeMinusChar != '-' && maybeMinusChar != '+') {
355                                        StringBuffer buf = new StringBuffer(dString.length() + 1);
356                                        buf.append(dString.substring(0, ePos + 1));
357                                        buf.append('+');
358                                        buf.append(dString.substring(ePos + 1, dString.length()));
359                                        dString = buf.toString();
360                                }
361                        }
362                }
363 
364                return dString;
365        }
366 
367        public static final byte[] getBytes(char[] c,
368                        SingleByteCharsetConverter converter, String encoding,
369                        String serverEncoding, boolean parserKnowsUnicode)
370                        throws SQLException {
371                try {
372                        byte[] b = null;
373 
374                        if (converter != null) {
375                                b = converter.toBytes(c);
376                        } else if (encoding == null) {
377                                b = new String(c).getBytes();
378                        } else {
379                                String s = new String(c);
380 
381                                b = s.getBytes(encoding);
382 
383                                if (!parserKnowsUnicode && (encoding.equalsIgnoreCase("SJIS") //$NON-NLS-1$
384                                                || encoding.equalsIgnoreCase("BIG5") //$NON-NLS-1$
385                                || encoding.equalsIgnoreCase("GBK"))) { //$NON-NLS-1$
386 
387                                        if (!encoding.equalsIgnoreCase(serverEncoding)) {
388                                                b = escapeEasternUnicodeByteStream(b, s, 0, s.length());
389                                        }
390                                }
391                        }
392 
393                        return b;
394                } catch (UnsupportedEncodingException uee) {
395                        throw new SQLException(Messages.getString("StringUtils.5") //$NON-NLS-1$
396                                        + encoding + Messages.getString("StringUtils.6"),
397                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$
398                }
399        }
400 
401        public static final byte[] getBytes(char[] c,
402                        SingleByteCharsetConverter converter, String encoding,
403                        String serverEncoding, int offset, int length,
404                        boolean parserKnowsUnicode) throws SQLException {
405                try {
406                        byte[] b = null;
407 
408                        if (converter != null) {
409                                b = converter.toBytes(c, offset, length);
410                        } else if (encoding == null) {
411                                byte[] temp = new String(c, offset, length).getBytes();
412 
413                                length = temp.length;
414                                
415                                b = new byte[length];
416                                System.arraycopy(temp, 0, b, 0, length);
417                        } else {
418                                String s = new String(c, offset, length);
419 
420                                byte[] temp = s.getBytes(encoding);
421 
422                                length = temp.length;
423                                
424                                b = new byte[length];
425                                System.arraycopy(temp, 0, b, 0, length);
426 
427                                if (!parserKnowsUnicode && (encoding.equalsIgnoreCase("SJIS") //$NON-NLS-1$
428                                                || encoding.equalsIgnoreCase("BIG5") //$NON-NLS-1$
429                                || encoding.equalsIgnoreCase("GBK"))) { //$NON-NLS-1$
430 
431                                        if (!encoding.equalsIgnoreCase(serverEncoding)) {
432                                                b = escapeEasternUnicodeByteStream(b, s, offset, length);
433                                        }
434                                }
435                        }
436 
437                        return b;
438                } catch (UnsupportedEncodingException uee) {
439                        throw new SQLException(Messages.getString("StringUtils.10") //$NON-NLS-1$
440                                        + encoding + Messages.getString("StringUtils.11"),
441                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$
442                }
443        }
444 
445        public static final byte[] getBytes(char[] c, String encoding,
446                        String serverEncoding, boolean parserKnowsUnicode)
447                        throws SQLException {
448                try {
449                        SingleByteCharsetConverter converter = SingleByteCharsetConverter
450                                        .getInstance(encoding, null);
451 
452                        return getBytes(c, converter, encoding, serverEncoding,
453                                        parserKnowsUnicode);
454                } catch (UnsupportedEncodingException uee) {
455                        throw new SQLException(Messages.getString("StringUtils.0") //$NON-NLS-1$
456                                        + encoding + Messages.getString("StringUtils.1"),
457                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$
458                }
459        }
460 
461        /**
462         * Returns the byte[] representation of the given string (re)using the given
463         * charset converter, and the given encoding.
464         * 
465         * @param s
466         *            the string to convert
467         * @param converter
468         *            the converter to reuse
469         * @param encoding
470         *            the character encoding to use
471         * @param serverEncoding
472         *            DOCUMENT ME!
473         * @param parserKnowsUnicode
474         *            DOCUMENT ME!
475         * 
476         * @return byte[] representation of the string
477         * 
478         * @throws SQLException
479         *             if an encoding unsupported by the JVM is supplied.
480         */
481        public static final byte[] getBytes(String s,
482                        SingleByteCharsetConverter converter, String encoding,
483                        String serverEncoding, boolean parserKnowsUnicode)
484                        throws SQLException {
485                try {
486                        byte[] b = null;
487 
488                        if (converter != null) {
489                                b = converter.toBytes(s);
490                        } else if (encoding == null) {
491                                b = s.getBytes();
492                        } else {
493                                b = s.getBytes(encoding);
494 
495                                if (!parserKnowsUnicode && (encoding.equalsIgnoreCase("SJIS") //$NON-NLS-1$
496                                                || encoding.equalsIgnoreCase("BIG5") //$NON-NLS-1$
497                                || encoding.equalsIgnoreCase("GBK"))) { //$NON-NLS-1$
498 
499                                        if (!encoding.equalsIgnoreCase(serverEncoding)) {
500                                                b = escapeEasternUnicodeByteStream(b, s, 0, s.length());
501                                        }
502                                }
503                        }
504 
505                        return b;
506                } catch (UnsupportedEncodingException uee) {
507                        throw new SQLException(Messages.getString("StringUtils.5") //$NON-NLS-1$
508                                        + encoding + Messages.getString("StringUtils.6"),
509                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$
510                }
511        }
512 
513        /**
514         * DOCUMENT ME!
515         * 
516         * @param s
517         *            DOCUMENT ME!
518         * @param converter
519         *            DOCUMENT ME!
520         * @param encoding
521         *            DOCUMENT ME!
522         * @param serverEncoding
523         *            DOCUMENT ME!
524         * @param offset
525         *            DOCUMENT ME!
526         * @param length
527         *            DOCUMENT ME!
528         * @param parserKnowsUnicode
529         *            DOCUMENT ME!
530         * 
531         * @return DOCUMENT ME!
532         * 
533         * @throws SQLException
534         *             DOCUMENT ME!
535         */
536        public static final byte[] getBytes(String s,
537                        SingleByteCharsetConverter converter, String encoding,
538                        String serverEncoding, int offset, int length,
539                        boolean parserKnowsUnicode) throws SQLException {
540                try {
541                        byte[] b = null;
542 
543                        if (converter != null) {
544                                b = converter.toBytes(s, offset, length);
545                        } else if (encoding == null) {
546                                byte[] temp = s.substring(offset, offset + length).getBytes();
547 
548                                length = temp.length;
549                                
550                                b = new byte[length];
551                                System.arraycopy(temp, 0, b, 0, length);
552                        } else {
553 
554                                byte[] temp = s.substring(offset, offset + length)
555                                        .getBytes(encoding);
556 
557                                length = temp.length;
558                                
559                                b = new byte[length];
560                                System.arraycopy(temp, 0, b, 0, length);
561                                
562                                if (!parserKnowsUnicode && (encoding.equalsIgnoreCase("SJIS") //$NON-NLS-1$
563                                                || encoding.equalsIgnoreCase("BIG5") //$NON-NLS-1$
564                                || encoding.equalsIgnoreCase("GBK"))) { //$NON-NLS-1$
565 
566                                        if (!encoding.equalsIgnoreCase(serverEncoding)) {
567                                                b = escapeEasternUnicodeByteStream(b, s, offset, length);
568                                        }
569                                }
570                        }
571 
572                        return b;
573                } catch (UnsupportedEncodingException uee) {
574                        throw new SQLException(Messages.getString("StringUtils.10") //$NON-NLS-1$
575                                        + encoding + Messages.getString("StringUtils.11"),
576                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$
577                }
578        }
579 
580        /**
581         * Returns the byte[] representation of the given string using given
582         * encoding.
583         * 
584         * @param s
585         *            the string to convert
586         * @param encoding
587         *            the character encoding to use
588         * @param parserKnowsUnicode
589         *            DOCUMENT ME!
590         * 
591         * @return byte[] representation of the string
592         * 
593         * @throws SQLException
594         *             if an encoding unsupported by the JVM is supplied.
595         */
596        public static final byte[] getBytes(String s, String encoding,
597                        String serverEncoding, boolean parserKnowsUnicode)
598                        throws SQLException {
599                try {
600                        SingleByteCharsetConverter converter = SingleByteCharsetConverter
601                                        .getInstance(encoding, null);
602 
603                        return getBytes(s, converter, encoding, serverEncoding,
604                                        parserKnowsUnicode);
605                } catch (UnsupportedEncodingException uee) {
606                        throw new SQLException(Messages.getString("StringUtils.0") //$NON-NLS-1$
607                                        + encoding + Messages.getString("StringUtils.1"),
608                                        SQLError.SQL_STATE_ILLEGAL_ARGUMENT); //$NON-NLS-1$
609                }
610        }
611 
612        public static int getInt(byte[] buf) throws NumberFormatException {
613                int base = 10;
614 
615                int s = 0;
616 
617                /* Skip white space. */
618                while (Character.isWhitespace((char) buf[s]) && (s < buf.length)) {
619                        ++s;
620                }
621 
622                if (s == buf.length) {
623                        throw new NumberFormatException(new String(buf));
624                }
625 
626                /* Check for a sign. */
627                boolean negative = false;
628 
629                if ((char) buf[s] == '-') {
630                        negative = true;
631                        ++s;
632                } else if ((char) buf[s] == '+') {
633                        ++s;
634                }
635 
636                /* Save the pointer so we can check later if anything happened. */
637                int save = s;
638 
639                int cutoff = Integer.MAX_VALUE / base;
640                int cutlim = (Integer.MAX_VALUE % base);
641 
642                if (negative) {
643                        cutlim++;
644                }
645 
646                boolean overflow = false;
647 
648                int i = 0;
649 
650                for (; s < buf.length; s++) {
651                        char c = (char) buf[s];
652 
653                        if (Character.isDigit(c)) {
654                                c -= '0';
655                        } else if (Character.isLetter(c)) {
656                                c = (char) (Character.toUpperCase(c) - 'A' + 10);
657                        } else {
658                                break;
659                        }
660 
661                        if (c >= base) {
662                                break;
663                        }
664 
665                        /* Check for overflow. */
666                        if ((i > cutoff) || ((i == cutoff) && (c > cutlim))) {
667                                overflow = true;
668                        } else {
669                                i *= base;
670                                i += c;
671                        }
672                }
673 
674                if (s == save) {
675                        throw new NumberFormatException(new String(buf));
676                }
677 
678                if (overflow) {
679                        throw new NumberFormatException(new String(buf));
680                }
681 
682                /* Return the result of the appropriate sign. */
683                return (negative ? (-i) : i);
684        }
685 
686        public static long getLong(byte[] buf) throws NumberFormatException {
687                int base = 10;
688 
689                int s = 0;
690 
691                /* Skip white space. */
692                while (Character.isWhitespace((char) buf[s]) && (s < buf.length)) {
693                        ++s;
694                }
695 
696                if (s == buf.length) {
697                        throw new NumberFormatException(new String(buf));
698                }
699 
700                /* Check for a sign. */
701                boolean negative = false;
702 
703                if ((char) buf[s] == '-') {
704                        negative = true;
705                        ++s;
706                } else if ((char) buf[s] == '+') {
707                        ++s;
708                }
709 
710                /* Save the pointer so we can check later if anything happened. */
711                int save = s;
712 
713                long cutoff = Long.MAX_VALUE / base;
714                long cutlim = (int) (Long.MAX_VALUE % base);
715 
716                if (negative) {
717                        cutlim++;
718                }
719 
720                boolean overflow = false;
721                long i = 0;
722 
723                for (; s < buf.length; s++) {
724                        char c = (char) buf[s];
725 
726                        if (Character.isDigit(c)) {
727                                c -= '0';
728                        } else if (Character.isLetter(c)) {
729                                c = (char) (Character.toUpperCase(c) - 'A' + 10);
730                        } else {
731                                break;
732                        }
733 
734                        if (c >= base) {
735                                break;
736                        }
737 
738                        /* Check for overflow. */
739                        if ((i > cutoff) || ((i == cutoff) && (c > cutlim))) {
740                                overflow = true;
741                        } else {
742                                i *= base;
743                                i += c;
744                        }
745                }
746 
747                if (s == save) {
748                        throw new NumberFormatException(new String(buf));
749                }
750 
751                if (overflow) {
752                        throw new NumberFormatException(new String(buf));
753                }
754 
755                /* Return the result of the appropriate sign. */
756                return (negative ? (-i) : i);
757        }
758 
759        public static short getShort(byte[] buf) throws NumberFormatException {
760                short base = 10;
761 
762                int s = 0;
763 
764                /* Skip white space. */
765                while (Character.isWhitespace((char) buf[s]) && (s < buf.length)) {
766                        ++s;
767                }
768 
769                if (s == buf.length) {
770                        throw new NumberFormatException(new String(buf));
771                }
772 
773                /* Check for a sign. */
774                boolean negative = false;
775 
776                if ((char) buf[s] == '-') {
777                        negative = true;
778                        ++s;
779                } else if ((char) buf[s] == '+') {
780                        ++s;
781                }
782 
783                /* Save the pointer so we can check later if anything happened. */
784                int save = s;
785 
786                short cutoff = (short) (Short.MAX_VALUE / base);
787                short cutlim = (short) (Short.MAX_VALUE % base);
788 
789                if (negative) {
790                        cutlim++;
791                }
792 
793                boolean overflow = false;
794                short i = 0;
795 
796                for (; s < buf.length; s++) {
797                        char c = (char) buf[s];
798 
799                        if (Character.isDigit(c)) {
800                                c -= '0';
801                        } else if (Character.isLetter(c)) {
802                                c = (char) (Character.toUpperCase(c) - 'A' + 10);
803                        } else {
804                                break;
805                        }
806 
807                        if (c >= base) {
808                                break;
809                        }
810 
811                        /* Check for overflow. */
812                        if ((i > cutoff) || ((i == cutoff) && (c > cutlim))) {
813                                overflow = true;
814                        } else {
815                                i *= base;
816                                i += c;
817                        }
818                }
819 
820                if (s == save) {
821                        throw new NumberFormatException(new String(buf));
822                }
823 
824                if (overflow) {
825                        throw new NumberFormatException(new String(buf));
826                }
827 
828                /* Return the result of the appropriate sign. */
829                return (negative ? (short) -i : (short) i);
830        }
831 
832        public final static int indexOfIgnoreCase(int startingPosition,
833                        String searchIn, String searchFor) {
834                if ((searchIn == null) || (searchFor == null)
835                                || startingPosition > searchIn.length()) {
836                        return -1;
837                }
838 
839                int patternLength = searchFor.length();
840                int stringLength = searchIn.length();
841                int stopSearchingAt = stringLength - patternLength;
842 
843                int i = startingPosition;
844 
845                if (patternLength == 0) {
846                        return -1;
847                }
848 
849                // Brute force string pattern matching
850                // Some locales don't follow upper-case rule, so need to check both
851                char firstCharOfPatternUc = Character.toUpperCase(searchFor.charAt(0));
852                char firstCharOfPatternLc = Character.toLowerCase(searchFor.charAt(0));
853 
854                lookForFirstChar: while (true) {
855                        while ((i < stopSearchingAt)
856                                        && (Character.toUpperCase(searchIn.charAt(i)) != firstCharOfPatternUc)
857                                        && Character.toLowerCase(searchIn.charAt(i)) != firstCharOfPatternLc) {
858                                i++;
859                        }
860 
861                        if (i > stopSearchingAt) {
862                                return -1;
863                        }
864 
865                        int j = i + 1;
866                        int end = (j + patternLength) - 1;
867 
868                        int k = 1; // start at second char of pattern
869 
870                        while (j < end) {
871                                int searchInPos = j++;
872                                int searchForPos = k++;
873 
874                                if (Character.toUpperCase(searchIn.charAt(searchInPos)) != Character
875                                                .toUpperCase(searchFor.charAt(searchForPos))) {
876                                        i++;
877 
878                                        // start over
879                                        continue lookForFirstChar;
880                                }
881 
882                                // Georgian and Turkish locales don't have same convention, so
883                                // need to check lowercase
884                                // too!
885                                if (Character.toLowerCase(searchIn.charAt(searchInPos)) != Character
886                                                .toLowerCase(searchFor.charAt(searchForPos))) {
887                                        i++;
888 
889                                        // start over
890                                        continue lookForFirstChar;
891                                }
892                        }
893 
894                        return i; // found entire pattern
895                }
896        }
897 
898        /**
899         * DOCUMENT ME!
900         * 
901         * @param searchIn
902         *            DOCUMENT ME!
903         * @param searchFor
904         *            DOCUMENT ME!
905         * 
906         * @return DOCUMENT ME!
907         */
908        public final static int indexOfIgnoreCase(String searchIn, String searchFor) {
909                return indexOfIgnoreCase(0, searchIn, searchFor);
910        }
911 
912        public static int indexOfIgnoreCaseRespectMarker(int startAt, String src,
913                        String target, String marker, String markerCloses,
914                        boolean allowBackslashEscapes) {
915                char contextMarker = Character.MIN_VALUE;
916                boolean escaped = false;
917                int markerTypeFound = 0;
918                int srcLength = src.length();
919                int ind = 0;
920 
921                for (int i = startAt; i < srcLength; i++) {
922                        char c = src.charAt(i);
923 
924                        if (allowBackslashEscapes && c == '\\') {
925                                escaped = !escaped;
926                        } else if (c == markerCloses.charAt(markerTypeFound) && !escaped) {
927                                contextMarker = Character.MIN_VALUE;
928                        } else if ((ind = marker.indexOf(c)) != -1 && !escaped
929                                        && contextMarker == Character.MIN_VALUE) {
930                                markerTypeFound = ind;
931                                contextMarker = c;
932                        } else if (c == target.charAt(0) && !escaped
933                                        && contextMarker == Character.MIN_VALUE) {
934                                if (indexOfIgnoreCase(i, src, target) != -1)
935                                        return i;
936                        }
937                }
938 
939                return -1;
940 
941        }
942 
943        public static int indexOfIgnoreCaseRespectQuotes(int startAt, String src,
944                        String target, char quoteChar, boolean allowBackslashEscapes) {
945                char contextMarker = Character.MIN_VALUE;
946                boolean escaped = false;
947 
948                int srcLength = src.length();
949 
950                for (int i = startAt; i < srcLength; i++) {
951                        char c = src.charAt(i);
952 
953                        if (allowBackslashEscapes && c == '\\') {
954                                escaped = !escaped;
955                        } else if (c == contextMarker && !escaped) {
956                                contextMarker = Character.MIN_VALUE;
957                        } else if (c == quoteChar && !escaped
958                                        && contextMarker == Character.MIN_VALUE) {
959                                contextMarker = c;
960                        } else if (c == target.charAt(0) && !escaped
961                                        && contextMarker == Character.MIN_VALUE) {
962                                if (startsWithIgnoreCase(src, i, target))
963                                        return i;
964                        }
965                }
966 
967                return -1;
968 
969        }
970 
971        /**
972         * Splits stringToSplit into a list, using the given delimitter
973         * 
974         * @param stringToSplit
975         *            the string to split
976         * @param delimitter
977         *            the string to split on
978         * @param trim
979         *            should the split strings be whitespace trimmed?
980         * 
981         * @return the list of strings, split by delimitter
982         * 
983         * @throws IllegalArgumentException
984         *             DOCUMENT ME!
985         */
986        public static final List split(String stringToSplit, String delimitter,
987                        boolean trim) {
988                if (stringToSplit == null) {
989                        return new ArrayList();
990                }
991 
992                if (delimitter == null) {
993                        throw new IllegalArgumentException();
994                }
995 
996                StringTokenizer tokenizer = new StringTokenizer(stringToSplit,
997                                delimitter, false);
998 
999                List splitTokens = new ArrayList(tokenizer.countTokens());
1000 
1001                while (tokenizer.hasMoreTokens()) {
1002                        String token = tokenizer.nextToken();
1003 
1004                        if (trim) {
1005                                token = token.trim();
1006                        }
1007 
1008                        splitTokens.add(token);
1009                }
1010 
1011                return splitTokens;
1012        }
1013 
1014        /**
1015         * Splits stringToSplit into a list, using the given delimitter
1016         * 
1017         * @param stringToSplit
1018         *            the string to split
1019         * @param delimitter
1020         *            the string to split on
1021         * @param trim
1022         *            should the split strings be whitespace trimmed?
1023         * 
1024         * @return the list of strings, split by delimiter
1025         * 
1026         * @throws IllegalArgumentException
1027         *             DOCUMENT ME!
1028         */
1029        public static final List split(String stringToSplit, String delimiter,
1030                        String markers, String markerCloses, boolean trim) {
1031                if (stringToSplit == null) {
1032                        return new ArrayList();
1033                }
1034 
1035                if (delimiter == null) {
1036                        throw new IllegalArgumentException();
1037                }
1038 
1039                int delimPos = 0;
1040                int currentPos = 0;
1041 
1042                List splitTokens = new ArrayList();
1043 
1044                while ((delimPos = indexOfIgnoreCaseRespectMarker(currentPos,
1045                                stringToSplit, delimiter, markers, markerCloses, false)) != -1) {
1046                        String token = stringToSplit.substring(currentPos, delimPos);
1047 
1048                        if (trim) {
1049                                token = token.trim();
1050                        }
1051 
1052                        splitTokens.add(token);
1053                        currentPos = delimPos + 1;
1054                }
1055 
1056                if (currentPos < stringToSplit.length()) {
1057                        String token = stringToSplit.substring(currentPos);
1058 
1059                        if (trim) {
1060                                token = token.trim();
1061                        }
1062 
1063                        splitTokens.add(token);
1064                }
1065 
1066                return splitTokens;
1067        }
1068 
1069        private static boolean startsWith(byte[] dataFrom, String chars) {
1070                for (int i = 0; i < chars.length(); i++) {
1071                        if (dataFrom[i] != chars.charAt(i)) {
1072                                return false;
1073                        }
1074                }
1075                return true;
1076        }
1077 
1078        /**
1079         * Determines whether or not the string 'searchIn' contains the string
1080         * 'searchFor', dis-regarding case starting at 'startAt' Shorthand for a
1081         * String.regionMatch(...)
1082         * 
1083         * @param searchIn
1084         *            the string to search in
1085         * @param startAt
1086         *            the position to start at
1087         * @param searchFor
1088         *            the string to search for
1089         * 
1090         * @return whether searchIn starts with searchFor, ignoring case
1091         */
1092        public static boolean startsWithIgnoreCase(String searchIn, int startAt,
1093                        String searchFor) {
1094                return searchIn.regionMatches(true, startAt, searchFor, 0, searchFor
1095                                .length());
1096        }
1097 
1098        /**
1099         * Determines whether or not the string 'searchIn' contains the string
1100         * 'searchFor', dis-regarding case. Shorthand for a String.regionMatch(...)
1101         * 
1102         * @param searchIn
1103         *            the string to search in
1104         * @param searchFor
1105         *            the string to search for
1106         * 
1107         * @return whether searchIn starts with searchFor, ignoring case
1108         */
1109        public static boolean startsWithIgnoreCase(String searchIn, String searchFor) {
1110                return startsWithIgnoreCase(searchIn, 0, searchFor);
1111        }
1112 
1113        /**
1114         * Determines whether or not the sting 'searchIn' contains the string
1115         * 'searchFor', disregarding case,leading whitespace and non-alphanumeric
1116         * characters.
1117         * 
1118         * @param searchIn
1119         *            the string to search in
1120         * @param searchFor
1121         *            the string to search for
1122         * 
1123         * @return true if the string starts with 'searchFor' ignoring whitespace
1124         */
1125        public static boolean startsWithIgnoreCaseAndNonAlphaNumeric(
1126                        String searchIn, String searchFor) {
1127                if (searchIn == null) {
1128                        return searchFor == null;
1129                }
1130 
1131                int beginPos = 0;
1132 
1133                int inLength = searchIn.length();
1134 
1135                for (beginPos = 0; beginPos < inLength; beginPos++) {
1136                        char c = searchIn.charAt(beginPos);
1137 
1138                        if (Character.isLetterOrDigit(c)) {
1139                                break;
1140                        }
1141                }
1142 
1143                return startsWithIgnoreCase(searchIn, beginPos, searchFor);
1144        }
1145 
1146        /**
1147         * Determines whether or not the sting 'searchIn' contains the string
1148         * 'searchFor', disregarding case and leading whitespace
1149         * 
1150         * @param searchIn
1151         *            the string to search in
1152         * @param searchFor
1153         *            the string to search for
1154         * 
1155         * @return true if the string starts with 'searchFor' ignoring whitespace
1156         */
1157        public static boolean startsWithIgnoreCaseAndWs(String searchIn,
1158                        String searchFor) {
1159                if (searchIn == null) {
1160                        return searchFor == null;
1161                }
1162 
1163                int beginPos = 0;
1164 
1165                int inLength = searchIn.length();
1166 
1167                for (beginPos = 0; beginPos < inLength; beginPos++) {
1168                        if (!Character.isWhitespace(searchIn.charAt(beginPos))) {
1169                                break;
1170                        }
1171                }
1172 
1173                return startsWithIgnoreCase(searchIn, beginPos, searchFor);
1174        }
1175 
1176        /**
1177         * @param bytesToStrip
1178         * @param prefix
1179         * @param suffix
1180         * @return
1181         */
1182        public static byte[] stripEnclosure(byte[] source, String prefix,
1183                        String suffix) {
1184                if (source.length >= prefix.length() + suffix.length()
1185                                && startsWith(source, prefix) && endsWith(source, suffix)) {
1186 
1187                        int totalToStrip = prefix.length() + suffix.length();
1188                        int enclosedLength = source.length - totalToStrip;
1189                        byte[] enclosed = new byte[enclosedLength];
1190 
1191                        int startPos = prefix.length();
1192                        int numToCopy = enclosed.length;
1193                        System.arraycopy(source, startPos, enclosed, 0, numToCopy);
1194 
1195                        return enclosed;
1196                }
1197                return source;
1198        }
1199 
1200        /**
1201         * Returns the bytes as an ASCII String.
1202         * 
1203         * @param buffer
1204         *            the bytes representing the string
1205         * 
1206         * @return The ASCII String.
1207         */
1208        public static final String toAsciiString(byte[] buffer) {
1209                return toAsciiString(buffer, 0, buffer.length);
1210        }
1211 
1212        /**
1213         * Returns the bytes as an ASCII String.
1214         * 
1215         * @param buffer
1216         *            the bytes to convert
1217         * @param startPos
1218         *            the position to start converting
1219         * @param length
1220         *            the length of the string to convert
1221         * 
1222         * @return the ASCII string
1223         */
1224        public static final String toAsciiString(byte[] buffer, int startPos,
1225                        int length) {
1226                char[] charArray = new char[length];
1227                int readpoint = startPos;
1228 
1229                for (int i = 0; i < length; i++) {
1230                        charArray[i] = (char) buffer[readpoint];
1231                        readpoint++;
1232                }
1233 
1234                return new String(charArray);
1235        }
1236 
1237        /**
1238         * Compares searchIn against searchForWildcard with wildcards (heavily
1239         * borrowed from strings/ctype-simple.c in the server sources)
1240         * 
1241         * @param searchIn
1242         *            the string to search in
1243         * @param searchForWildcard
1244         *            the string to search for, using the 'standard' SQL wildcard
1245         *            chars of '%' and '_'
1246         * 
1247         * @return WILD_COMPARE_MATCH_NO_WILD if matched, WILD_COMPARE_NO_MATCH if
1248         *         not matched with wildcard, WILD_COMPARE_MATCH_WITH_WILD if
1249         *         matched with wildcard
1250         */
1251        public static int wildCompare(String searchIn, String searchForWildcard) {
1252                if ((searchIn == null) || (searchForWildcard == null)) {
1253                        return WILD_COMPARE_NO_MATCH;
1254                }
1255 
1256                if (searchForWildcard.equals("%")) { //$NON-NLS-1$
1257 
1258                        return WILD_COMPARE_MATCH_WITH_WILD;
1259                }
1260 
1261                int result = WILD_COMPARE_NO_MATCH; /* Not found, using wildcards */
1262 
1263                char wildcardMany = '%';
1264                char wildcardOne = '_';
1265                char wildcardEscape = '\\';
1266 
1267                int searchForPos = 0;
1268                int searchForEnd = searchForWildcard.length();
1269 
1270                int searchInPos = 0;
1271                int searchInEnd = searchIn.length();
1272 
1273                while (searchForPos != searchForEnd) {
1274                        char wildstrChar = searchForWildcard.charAt(searchForPos);
1275 
1276                        while ((searchForWildcard.charAt(searchForPos) != wildcardMany)
1277                                        && (wildstrChar != wildcardOne)) {
1278                                if ((searchForWildcard.charAt(searchForPos) == wildcardEscape)
1279                                                && ((searchForPos + 1) != searchForEnd)) {
1280                                        searchForPos++;
1281                                }
1282 
1283                                if ((searchInPos == searchInEnd)
1284                                                || (Character.toUpperCase(searchForWildcard
1285                                                                .charAt(searchForPos++)) != Character
1286                                                                .toUpperCase(searchIn.charAt(searchInPos++)))) {
1287                                        return WILD_COMPARE_MATCH_WITH_WILD; /* No match */
1288                                }
1289 
1290                                if (searchForPos == searchForEnd) {
1291                                        return ((searchInPos != searchInEnd) ? WILD_COMPARE_MATCH_WITH_WILD
1292                                                        : WILD_COMPARE_MATCH_NO_WILD); /*
1293                                                                                                                         * Match if both are
1294                                                                                                                         * at end
1295                                                                                                                         */
1296                                }
1297 
1298                                result = WILD_COMPARE_MATCH_WITH_WILD; /* Found an anchor char */
1299                        }
1300 
1301                        if (searchForWildcard.charAt(searchForPos) == wildcardOne) {
1302                                do {
1303                                        if (searchInPos == searchInEnd) { /*
1304                                                                                                                 * Skip one char if
1305                                                                                                                 * possible
1306                                                                                                                 */
1307 
1308                                                return (result);
1309                                        }
1310 
1311                                        searchInPos++;
1312                                } while ((++searchForPos < searchForEnd)
1313                                                && (searchForWildcard.charAt(searchForPos) == wildcardOne));
1314 
1315                                if (searchForPos == searchForEnd) {
1316                                        break;
1317                                }
1318                        }
1319 
1320                        if (searchForWildcard.charAt(searchForPos) == wildcardMany) { /*
1321                                                                                                                                                         * Found
1322                                                                                                                                                         * w_many
1323                                                                                                                                                         */
1324 
1325                                char cmp;
1326 
1327                                searchForPos++;
1328 
1329                                /* Remove any '%' and '_' from the wild search string */
1330                                for (; searchForPos != searchForEnd; searchForPos++) {
1331                                        if (searchForWildcard.charAt(searchForPos) == wildcardMany) {
1332                                                continue;
1333                                        }
1334 
1335                                        if (searchForWildcard.charAt(searchForPos) == wildcardOne) {
1336                                                if (searchInPos == searchInEnd) {
1337                                                        return (WILD_COMPARE_NO_MATCH);
1338                                                }
1339 
1340                                                searchInPos++;
1341 
1342                                                continue;
1343                                        }
1344 
1345                                        break; /* Not a wild character */
1346                                }
1347 
1348                                if (searchForPos == searchForEnd) {
1349                                        return WILD_COMPARE_MATCH_NO_WILD; /* Ok if w_many is last */
1350                                }
1351 
1352                                if (searchInPos == searchInEnd) {
1353                                        return WILD_COMPARE_NO_MATCH;
1354                                }
1355 
1356                                if (((cmp = searchForWildcard.charAt(searchForPos)) == wildcardEscape)
1357                                                && ((searchForPos + 1) != searchForEnd)) {
1358                                        cmp = searchForWildcard.charAt(++searchForPos);
1359                                }
1360 
1361                                searchForPos++;
1362 
1363                                do {
1364                                        while ((searchInPos != searchInEnd)
1365                                                        && (Character.toUpperCase(searchIn
1366                                                                        .charAt(searchInPos)) != Character
1367                                                                        .toUpperCase(cmp)))
1368                                                searchInPos++;
1369 
1370                                        if (searchInPos++ == searchInEnd) {
1371                                                return WILD_COMPARE_NO_MATCH;
1372                                        }
1373 
1374                                        {
1375                                                int tmp = wildCompare(searchIn, searchForWildcard);
1376 
1377                                                if (tmp <= 0) {
1378                                                        return (tmp);
1379                                                }
1380                                        }
1381                                } while ((searchInPos != searchInEnd)
1382                                                && (searchForWildcard.charAt(0) != wildcardMany));
1383 
1384                                return WILD_COMPARE_NO_MATCH;
1385                        }
1386                }
1387 
1388                return ((searchInPos != searchInEnd) ? WILD_COMPARE_MATCH_WITH_WILD
1389                                : WILD_COMPARE_MATCH_NO_WILD);
1390        }
1391}

[all classes][com.mysql.jdbc]
EMMA 2.0.4217 (C) Vladimir Roubtsov