A
download Tokenizer.java
Language: Java
License: AL20
Copyright: Copyright 2003-2004 The Apache Software Foundation.
LOC: 388
Project Info
jakarta-commons
Server: Apache
Type: svn
...va\org\apache\commons\lang\
   ArrayUtils.java
   BitField.java
   BooleanUtils.java
   CharRange.java
   CharSet.java
   CharSetUtils.java
   CharUtils.java
   ClassUtils.java
   Entities.java
   IllegalClassException.java
   ...eArgumentException.java
   Interpolation.java
   IntHashMap.java
   ...plementedException.java
   NullArgumentException.java
   NumberRange.java
   NumberUtils.java
   ObjectUtils.java
   RandomStringUtils.java
   ...alizationException.java
   SerializationUtils.java
   StringEscapeUtils.java
   StringPrintWriter.java
   StringUtils.java
   SystemUtils.java
   Tokenizer.java
   UnhandledException.java
   Validate.java
   WordUtils.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
/*
 * Copyright 2003-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.lang;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;

/**
 * Tokenizes a string based based on delimiters (separators)
 * and supporting quoting and ignored character concepts.
 * <p>
 * This class can split a String into many smaller strings.
 * It aims to do a similar job to java util StringTokenizer, however it offers
 * much more control and flexibility. By default, it is setup like StringTokenizer.
 * <p>
 * The input String is split into a number of <i>tokens</i>.
 * Each token is separated from the next String by a <i>delimiter</i>.
 * One or more delimiter characters must be specified.
 * <p>
 * The processing then strips all the <i>ignored</i> characters from each side of the token.
 * The token may also have <i>quotes</i> to mark an area not to be stripped or tokenized.
 * Empty tokens may be removed or returned as null.
 * This example is based on the CSV tokenizer.
 * <pre>
 * "a,b,c"       - Three tokens "a","b","c"   (comma delimiter)
 * "a, b , c"    - Three tokens "a","b","c"   (ignored space characters stripped)
 * "a, " b ", c" - Three tokens "a"," b ","c" (quoted text untouched)
 * </pre>
 * <p>
 *
 * This tokenizer has the following properties and options:
 *
 * <table>
 *  <tr>
 *   <th>Property</th><th>Type</th><th>Default</th>
 *  </tr>
 *  <tr>
 *   <td>delim</td><td>CharSetMatcher</td><td>{ \t\n\r\f}</td>
 *  </tr>
 *  <tr>
 *   <td>quote</td><td>NoneMatcher</td><td>{}</td>
 *  </tr>
 *  <tr>
 *   <td>ignore</td><td>NoneMatcher</td><td>{}</td>
 *  </tr>
 *  <tr>
 *   <td>emptyTokenAsNull</td><td>boolean</td><td>false</td>
 *  </tr>
 *  <tr>
 *   <td>ignoreEmptyTokens</td><td>boolean</td><td>true</td>
 *  </tr>
 * </table>
 *
 * @author Matthew Inger
 * @author Stephen Colebourne
 * @author Gary D. Gregory
 * @since 2.1
 * @version $Id: Tokenizer.java,v 1.6 2004/02/19 21:04:03 fredrik Exp $
 */
public class Tokenizer implements ListIterator, Cloneable {

    /**
     * A Matcher which matches the comma character.
     * Best used for <code>delimiter</code>.
     */
    public static final Matcher COMMA_MATCHER = new CharMatcher(',');
    /**
     * A Matcher which matches the tab character.
     * Best used for <code>delimiter</code>.
     */
    public static final Matcher TAB_MATCHER = new CharMatcher('\t');
    /**
     * A Matcher which matches the space character.
     * Best used for <code>delimiter</code>.
     */
    public static final Matcher SPACE_MATCHER = new CharMatcher(' ');
    /**
     * A Matcher which matches the same characters as StringTokenizer,
     * namely space, tab, newline, formfeed.
     * Best used for <code>delimiter</code>.
     */
    public static final Matcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f");
    /**
     * A Matcher which matches the double quote character.
     * Best used for <code>quote</code>.
     */
    public static final Matcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"');
    /**
     * A Matcher which matches the String trim() whitespace characters.
     * Best used for <code>ignored</code>.
     */
    public static final Matcher TRIM_MATCHER = new TrimMatcher();
    /**
     * A Matcher that matches no characters. Don't use this for delimiters!
     * Best used for <code>ignored</code>.
     */
    public static final Matcher NONE_MATCHER = new NoMatcher();
    
    private static final Tokenizer CSV_TOKENIZER_PROTOTYPE;
    private static final Tokenizer TSV_TOKENIZER_PROTOTYPE;

    static {
        CSV_TOKENIZER_PROTOTYPE = new Tokenizer(StringUtils.EMPTY);
        CSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(COMMA_MATCHER);
        CSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(DOUBLE_QUOTE_MATCHER);
        CSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(TRIM_MATCHER);
        CSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
        CSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);

        TSV_TOKENIZER_PROTOTYPE = new Tokenizer(StringUtils.EMPTY);
        TSV_TOKENIZER_PROTOTYPE.setDelimiterMatcher(TAB_MATCHER);
        TSV_TOKENIZER_PROTOTYPE.setQuoteMatcher(DOUBLE_QUOTE_MATCHER);
        TSV_TOKENIZER_PROTOTYPE.setIgnoredMatcher(TRIM_MATCHER);
        TSV_TOKENIZER_PROTOTYPE.setEmptyTokenAsNull(false);
        TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false);
    }

    /** The text to work on */
    private char chars[];
    /** The input text, null if char[] input */
    private String text;
    /** The parsed tokens */
    private String tokens[];
    /** The current iteration position */
    private int tokenPos;

    /** The delimiter matcher */
    private Matcher delim = SPLIT_MATCHER;
    /** The quote matcher */
    private Matcher quote = NONE_MATCHER;
    /** The ignored matcher */
    private Matcher ignored = NONE_MATCHER;
    /** Whether to return empty tokens as null */
    private boolean emptyAsNull = false;
    /** Whether to ignore empty tokens */
    private boolean ignoreEmptyTokens = true;

    //-----------------------------------------------------------------------
    /**
     * Get a tokenizer instance which parses Comma Seperated Value
     * strings.  You must call a "reset" method to set the string which
     * you want to parse.
     */
    public static final Tokenizer getCSVInstance() {
        return (Tokenizer)(CSV_TOKENIZER_PROTOTYPE.clone());
    }

    /**
     * Get a tokenizer instance which parses Comma Seperated Value
     * strings, initializing it with the given input.
     * 
     * @param input  the string to parse
     */
    public static final Tokenizer getCSVInstance(String input) {
        Tokenizer tok = (Tokenizer)(CSV_TOKENIZER_PROTOTYPE.clone());
        tok.reset(input);
        return tok;
    }

    /**
     * Get a tokenizer instance which parses Comma Seperated Value
     * strings, initializing it with the given input.
     * 
     * @param input  the text to parse
     */
    public static final Tokenizer getCSVInstance(char[] input) {
        Tokenizer tok = (Tokenizer)(CSV_TOKENIZER_PROTOTYPE.clone());
        tok.reset(input);
        return tok;
    }

    /**
     * Get a tokenizer instance which parses Tab Seperated Value
     * strings.  You must call a "reset" method to set the string which
     * you want to parse.
     */
    public static final Tokenizer getTSVInstance() {
        return (Tokenizer)(TSV_TOKENIZER_PROTOTYPE.clone());
    }

    /**
     * Get a tokenizer instance which parses Tab Seperated Value
     * strings, initializing it with the given input.
     * 
     * @param input  the string to parse
     */
    public static final Tokenizer getTSVInstance(String input) {
        Tokenizer tok = (Tokenizer)(TSV_TOKENIZER_PROTOTYPE.clone());
        tok.reset(input);
        return tok;
    }

    /**
     * Get a tokenizer instance which parses Tab Seperated Value
     * strings, initializing it with the given input.
     * 
     * @param input  the text to parse
     */
    public static final Tokenizer getTSVInstance(char[] input) {
        Tokenizer tok = (Tokenizer)(TSV_TOKENIZER_PROTOTYPE.clone());
        tok.reset(input);
        return tok;
    }

    //-----------------------------------------------------------------------
    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed
     */
    public Tokenizer(String input) {
        super();
        this.text = input;
        this.chars = input.toCharArray();  // no clone as toCharArray() clones
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed
     * @param delim  the field delimiter character
     */
    public Tokenizer(String input, char delim) {
        this(input);
        setDelimiterChar(delim);
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed
     * @param delim  the field delimiter character
     */
    public Tokenizer(String input, CharSetMatcher delim) {
        this(input);
        setDelimiterMatcher(delim);
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed
     * @param delim  the field delimiter character
     * @param quote  the field quoted string character
     */
    public Tokenizer(String input, char delim, char quote) {
        this(input, delim);
        setQuoteChar(quote);
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed
     * @param delim  the field delimiter character
     * @param quote  the field quoted string character
     */
    public Tokenizer(String input, CharSetMatcher delim, CharSetMatcher quote) {
        this(input, delim);
        setQuoteMatcher(quote);
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed, cloned
     */
    public Tokenizer(char[] input) {
        super();
        this.text = null;
        this.chars = (char[]) input.clone();
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed, cloned
     * @param delim the field delimiter character
     */
    public Tokenizer(char[] input, char delim) {
        this(input);
        setDelimiterChar(delim);
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed, cloned
     * @param delim  the field delimiter character
     */
    public Tokenizer(char[] input, CharSetMatcher delim) {
        this(input);
        setDelimiterMatcher(delim);
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed, cloned
     * @param delim  the field delimiter character
     * @param quote  the field quoted string character
     */
    public Tokenizer(char[] input, char delim, char quote) {
        this(input, delim);
        setQuoteChar(quote);
    }

    /**
     * Constructs a tokenizer splitting on space, tab, newline and formfeed
     * as per StringTokenizer.
     * 
     * @param input  the string which is to be parsed, cloned
     * @param delim  the field delimiter character
     * @param quote  the field quoted string character
     */
    public Tokenizer(char[] input, CharSetMatcher delim, CharSetMatcher quote) {
        this(input, delim);
        setQuoteMatcher(quote);
    }

    // API
    //-----------------------------------------------------------------------
    /**
     * Gets the number of tokens found in the String.
     * 
     * @return the number of matched tokens
     */
    public int size() {
        tokenize();
        return tokens.length;
    }

    /**
     * Gets the next token from the String.
     * 
     * @return the next sequential token, or null when no more tokens are found
     */
    public String nextToken() {
        if (hasNext()) {
            return tokens[tokenPos++];
        } else {
            return null;
        }
    }

    /**
     * Gets the previous token from the String.
     * 
     * @return the previous sequential token, or null when no more tokens are found
     */
    public String previousToken() {
        if (hasPrevious()) {
            return tokens[--tokenPos];
        } else {
            return null;
        }
    }

    /**
     * Gets a copy of the full token list.
     * 
     * @return the tokens as a String array
     */
    public String[] getAllTokens() {
        tokenize();
        return (String[]) tokens.clone();
    }

    /**
     * Resets this tokenizer, forgetting all parsing and iteration already completed.
     * <p>
     * This method allows the same tokenizer to be reused for the same String.
     */
    public void reset() {
        tokenPos = 0;
        tokens = null;
    }

    /**
     * Reset this tokenizer, giving it a new input string to parse.
     * In this manner you can re-use a tokenizer with the same settings
     * on multiple input lines.
     * 
     * @param input  the new string to tokenize
     */
    public void reset(String input) {
        reset();
        this.text = input;
        chars = input.toCharArray();  // no clone as toCharArray() clones
    }

    /**
     * Reset this tokenizer, giving it a new input string to parse.
     * In this manner you can re-use a tokenizer with the same settings
     * on multiple input lines.
     * 
     * @param input  the new character array to tokenize, cloned
     */
    public void reset(char [] input) {
        reset();
        this.text = null;
        chars = (char[]) input.clone();
    }

    // ListIterator
    //-----------------------------------------------------------------------
    /**
     * Checks whether there are any more tokens.
     * 
     * @return true if there are more tokens
     */
    public boolean hasNext() {
        tokenize();
        return (tokenPos < tokens.length);
    }

    /**
     * Gets the next token. This method is equivalent to {@link #nextToken()}.
     * 
     * @return the next String token
     */
    public Object next() {
        return nextToken();
    }

    /**
     * Gets the index of the next token to return.
     * 
     * @return the next token index
     */
    public int nextIndex() {
        return tokenPos;
    }

    /**
     * Checks whether there are any previous tokens that can be iterated to.
     * 
     * @return true if there are previous tokens
     */
    public boolean hasPrevious() {
        tokenize();
        return (tokenPos > 0);
    }

    /**
     * Gets the token previous to the last returned token.
     * 
     * @return the previous token
     */
    public Object previous() {
        return previousToken();
    }

    /**
     * Gets the index of the previous token.
     * 
     * @return the previous token index
     */
    public int previousIndex() {
        return (tokenPos - 1);
    }

    /**
     * Unsupported ListIterator operation.
     *
     * @throws UnsupportedOperationException always
     */
    public void remove() {
        throw new UnsupportedOperationException("remove() is unsupported");
    }

    /**
     * Unsupported ListIterator operation.
     *
     * @throws UnsupportedOperationException always
     */
    public void set(Object obj) {
        throw new UnsupportedOperationException("set() is unsupported");
    }

    /**
     * Unsupported ListIterator operation.
     *
     * @throws UnsupportedOperationException always
     */
    public void add(Object obj) {
        throw new UnsupportedOperationException("add() is unsupported");
    }

    // Implementation
    //-----------------------------------------------------------------------
    /**
     * Performs the tokenization if it hasn't already been done.
     */
    private void tokenize() {
        if (tokens == null) {
            this.tokens = readTokens();
        }
    }

    /**
     * Read all the tokens.
     */
    private String[] readTokens() {
        int len = chars.length;
        char cbuf[] = new char[len];
        StringBuffer token = new StringBuffer();
        int start = 0;
        List tokens = new ArrayList();
        String tok = null;

        // Keep going until we run out of characters
        while (start < len) {
            // read the next token
            start = readNextToken(start, cbuf, token);
            tok = token.toString();

            // Add the token, following the rules
            // in this object
            addToken(tokens, tok);

            // Reset the string buffer to zero length
            token.setLength(0);

            // Handle the special case where the very last
            // character is a delimiter, in which case, we
            // need another empty string
            if (start == len && delim.isMatch(chars[start - 1])) {
                // Add the token, following the rules
                // in this object
                addToken(tokens, new String());
            }
        }

        return (String[]) tokens.toArray(new String[tokens.size()]);
    }

    /**
     * Adds a token to a list, paying attention to the parameters we've set.
     * 
     * @param list  the list to add to
     * @param tok  the token to add
     */
    private void addToken(List list, String tok) {
        if (StringUtils.isEmpty(tok)) {
            if (ignoreEmptyTokens) {
                return;
            }
            if (emptyAsNull) {
                tok = null;
            }
        }
        list.add(tok);
    }

    /**
     * Reads character by character through the String to get the next token.
     * 
     * @param start  the first character of field
     * @param cbuf  a character buffer for temporary computations (so we
     *  don't have to keep recreating one)
     * @param token  a StringBuffer where the output token will go
     * @return the starting position of the next field (the character
     *  immediately after the delimiter, or if end of string found,
     *  then the length of string
     */
    private int readNextToken(int start, char cbuf[], StringBuffer token) {
        token.setLength(0);
        int len = chars.length;

        // Skip all leading whitespace, unless it is the
        // field delimiter or the quote character
        int current = start;
        while (current < len &&
                ignored.isMatch(chars[current]) &&
                !delim.isMatch(chars[current]) &&
                !quote.isMatch(chars[current])) {
            current++;
        }

        start = current;

        // Read the token depending on what the first
        // character is like
        if (delim.isMatch(chars[start])) {
            start = readEmpty(start, token);
        } else if (quote.isMatch(chars[start])) {
            start = readQuoted(start, cbuf, token);
        } else {
            start = readUnquoted(start, token);
        }

        return start;
    }

    /**
     * Reads a quoted string token.
     * 
     * @param start The first character of field (this will be the quote
     *              character)
     * @param cbuf A character buffer for temporary computations (so we
     *             don't have to keep recreating one)
     * @param token A StringBuffer where the output token will go.
     * @return The starting position of the next field (the character
     *         immediately after the delimiter, or if end of string found,
     *         then the length of string.
     */
    private int readQuoted(int start, char cbuf[], StringBuffer token) {
        // Loop until we've found the end of the quoted
        // string or the end of the input
        int cbufcnt = 0;
        int nd = start + 1;
        boolean done = false;
        boolean quoting = true;
        int len = chars.length;

        while (nd < len && !done) {
            // Quoting mode can occur several times throughout
            // a given string, so must switch between quoting
            // and non-quoting until we encounter a non-quoted
            // delimiter, or end of string, which inidicates end
            // of token.
            if (quoting) {
                // If we've found a quote character, see if it's
                // followed by a second quote.  If so, then we need
                // to actually put the quote character into the token
                // rather than end the token.
                if (quote.isMatch(chars[nd]) &&
                        nd + 1 < len &&
                        chars[nd + 1] == chars[nd]) {
                    cbuf[cbufcnt++] = chars[nd];
                    nd++;
                }
                // End the quoting if we get to this condition
                else if (quote.isMatch(chars[nd])) {
                    quoting = false;
                }
                // Otherwise, just put the character into the token
                else {
                    cbuf[cbufcnt++] = chars[nd];
                }
                nd++;
            }
            // If we're not in quoting mode, if we encounter
            // a delimiter, the token is ended.  If we encounter
            // a quote, we start quoting mode, otherwise, just append
            // the character
            else {
                // If we're
                if (delim.isMatch(chars[nd])) {
                    done = true;
                } else {
                    if (quote.isMatch(chars[nd])) {
                        quoting = true;
                    } else {
                        cbuf[cbufcnt++] = chars[nd];
                    }
                    nd++;
                }
            }
        }

        token.append(cbuf, 0, cbufcnt);

        return nd + 1;
    }

    /**
     * Read an unquoted string until a delimiter is found.
     * 
     * @param start  the first character of field
     * @param token  a StringBuffer where the output token will go.
     * @return  the starting position of the next field (the character
     *  immediately after the delimiter, or if end of string found,
     *  then the length of string.
     */
    private int readUnquoted(int start, StringBuffer token) {
        int len = chars.length;
        // Skip ahead until we get to a delimiter character, or
        // the end of the input
        int nd = start + 1;
        while (nd < len && !delim.isMatch(chars[nd])) {
            nd++;
        }

        token.append(chars, start, Math.min(nd, len) - start);

        return nd + 1;
    }

    /**
     * Read an empty string (basically, if a delimiter is found right
     * after another delimiter).
     * 
     * @param start  the first character of field (this will be the delimiter
     *  character)
     * @param token  a StringBuffer where the output token will go.
     * @return The starting position of the next field (the character
     *  immediately after the delimiter, or if end of string found,
     *  then the length of string.
     */
    private int readEmpty(int start, StringBuffer token) {
        token.setLength(0);
        return start + 1;
    }

    // Delimiter
    //-----------------------------------------------------------------------
    /**
     * Gets the field delimiter matcher.
     * 
     * @return the delimiter matcher in use
     */
    public Matcher getDelimiterMatcher() {
        return delim;
    }

    /**
     * Sets the field delimiter matcher.
     * <p>
     * The delimitier is used to separate one token from another.
     * 
     * @param delim  the delimiter matcher to use, null ignored
     */
    public void setDelimiterMatcher(Matcher delim) {
        if (delim != null) {
            this.delim = delim;
        }
    }

    /**
     * Sets the field delimiter character
     * 
     * @param delim  the delimiter character to use
     */
    public void setDelimiterChar(char delim) {
        setDelimiterMatcher(new CharMatcher(delim));
    }

    // Quote
    //-----------------------------------------------------------------------
    /**
     * Gets the quote matcher currently in use.
     * <p>
     * The quote character is used to wrap data between the tokens.
     * This enables delimiters to be entered as data.
     * The default value is '"' (double quote).
     * 
     * @return the quote matcher in use
     */
    public Matcher getQuoteMatcher() {
        return quote;
    }

    /**
     * Set the quote matcher to use.
     * <p>
     * The quote character is used to wrap data between the tokens.
     * This enables delimiters to be entered as data.
     * 
     * @param quote  the quote matcher to use, null ignored
     */
    public void setQuoteMatcher(Matcher quote) {
        if (quote != null) {
            this.quote = quote;
        }
    }

    /**
     * Sets the quote character to use.
     * <p>
     * The quote character is used to wrap data between the tokens.
     * This enables delimiters to be entered as data.
     * 
     * @param quote  the quote character to use
     */
    public void setQuoteChar(char quote) {
        setQuoteMatcher(new CharMatcher(quote));
    }

    // Ignored
    //-----------------------------------------------------------------------
    /**
     * Gets the ignored character matcher.
     * <p>
     * These characters are ignored when parsing the String, unless they are
     * within a quoted region.
     * The default value is space (' ') and all char control characters (32 and less).
     * 
     * @return the ignored matcher in use
     */
    public Matcher getIgnoredMatcher() {
        return ignored;
    }

    /**
     * Set the matcher for characters to ignore.
     * <p>
     * These characters are ignored when parsing the String, unless they are
     * within a quoted region.
     * 
     * @param ignored  the ignored matcher to use, null ignored
     */
    public void setIgnoredMatcher(Matcher ignored) {
        if (ignored != null) {
            this.ignored = ignored;
        }
    }

    /**
     * Set the character to ignore.
     * <p>
     * This character is ignored when parsing the String, unless it is
     * within a quoted region.
     * 
     * @param ignored  the ignored character to use
     */
    public void setIgnoredChar(char ignored) {
        setIgnoredMatcher(new CharMatcher(ignored));
    }

    //-----------------------------------------------------------------------
    /**
     * Gets whether the tokenizer currently returns empty tokens as null.
     * The default for this property is false.
     * 
     * @return true if empty tokens are returned as null
     */
    public boolean isEmptyTokenAsNull() {
        return emptyAsNull;
    }

    /**
     * Sets whether the tokenizer should return empty tokens as null.
     * The default for this property is false.
     * 
     * @param emptyAsNull  whether empty tokens are returned as null
     */
    public void setEmptyTokenAsNull(boolean emptyAsNull) {
        this.emptyAsNull = emptyAsNull;
    }

    //-----------------------------------------------------------------------
    /**
     * Gets whether the tokenizer currently ignores empty tokens.
     * The default for this property is false.
     * 
     * @return true if empty tokens are not returned
     */
    public boolean isIgnoreEmptyTokens() {
        return ignoreEmptyTokens;
    }

    /**
     * Sets whether the tokenizer should ignore and not return empty tokens.
     * The default for this property is false.
     * 
     * @param ignoreEmptyTokens  whether empty tokens are not returned
     */
    public void setIgnoreEmptyTokens(boolean ignoreEmptyTokens) {
        this.ignoreEmptyTokens = ignoreEmptyTokens;
    }

    //-----------------------------------------------------------------------
    /**
     * Gets the String content that the tokenizer is parsing.
     * 
     * @return the string content being parsed
     */
    public String getContent() {
        if (text == null) {
            text = new String(chars);
        }
        return text;
    }
    
    //-----------------------------------------------------------------------
    /**
     * Create a new instance of this Tokenizer.
     * The new instance is reset so that it will be at the start of the token list.
     */
    public Object clone() {
        try {
            Tokenizer cloned = (Tokenizer) super.clone();
            // chars[] does not need additional clone as it is treated as immutable
            cloned.reset();
            return cloned;
            
        } catch (CloneNotSupportedException ex) {
            return null;
        }
    }

    //-----------------------------------------------------------------------    
    /**
     * Class used to define a set of characters for matching purposes.
     */
    public static interface Matcher {
        /**
         * Returns true if the specified character matches.
         * 
         * @param ch  the character to check for
         * @return true if matches
         */
        boolean isMatch(char ch);
    }
    
    //-----------------------------------------------------------------------    
    /**
     * Class used to define a set of characters for matching purposes.
     */
    public static final class CharSetMatcher implements Matcher {
        private char chars[];

        /**
         * Constructor that creates a matcher from a character array.
         * 
         * @param chars  the characters to match, must not be null
         */
        public CharSetMatcher(char chars[]) {
            super();
            this.chars = (char[]) chars.clone();
            Arrays.sort(this.chars);
        }

        /**
         * Constructor that creates a matcher from a String.
         * 
         * @param chars  the characters to match, must not be null
         */
        public CharSetMatcher(String chars) {
            super();
            this.chars = chars.toCharArray();
            Arrays.sort(this.chars);
        }

        /**
         * Gets the characters being matched.
         * 
         * @return the characters being matched
         */
        public char[] getChars() {
            return (char[]) chars.clone();
        }

        /**
         * Returns whether or not the given charatcer matches.
         * 
         * @param ch the character to match.
         * @return whether or not the given charatcer matches.
         */
        public boolean isMatch(char ch) {
            return (Arrays.binarySearch(chars, ch) >= 0);
        }
    }
    
    //-----------------------------------------------------------------------    
    /**
     * Class used to define a character for matching purposes.
     */
    public static final class CharMatcher implements Matcher {
        private char ch;

        /**
         * Constructor that creates a matcher that matches a single character.
         * 
         * @param ch  the character to match
         */
        public CharMatcher(char ch) {
            super();
            this.ch = ch;
        }

        /**
         * Gets the character being matched.
         * 
         * @return the character being matched
         */
        public char getChar() {
            return this.ch;
        }

        /**
         * Returns whether or not the given charatcer matches.
         * 
         * @param ch the character to match.
         * @return whether or not the given charatcer matches.
         */
        public boolean isMatch(char ch) {
            return (this.ch == ch);
        }
    }
    
    //-----------------------------------------------------------------------    
    /**
     * Class used to match no characters.
     */
    static final class NoMatcher implements Matcher {

        NoMatcher() {
            super();
        }

        /**
         * Always returns <code>false</code>.
         * 
         * @param ch the character to match.
         * @return Always returns <code>false</code>.
         */
        public boolean isMatch(char ch) {
            return false;
        }
    }
    
    //-----------------------------------------------------------------------    
    /**
     * Class used to match whitespace as per trim().
     */
    static final class TrimMatcher implements Matcher {

        TrimMatcher() {
            super();
        }

        /**
         * Returns whether or not the given charatcer matches.
         * 
         * @param ch the character to match.
         * @return whether or not the given charatcer matches.
         */
        public boolean isMatch(char ch) {
            return (ch <= 32);
        }
    }
}

About Koders | Resources | Downloads | Support | Black Duck | Terms of Service | DMCA | Privacy Policy | Contact Us