View Javadoc
1   /**
2    * Copyright 2014 The Kuali Foundation Licensed under the
3    * Educational Community License, Version 2.0 (the "License"); you may
4    * not use this file except in compliance with the License. You may
5    * obtain a copy of the License at
6    *
7    * http://www.osedu.org/licenses/ECL-2.0
8    *
9    * Unless required by applicable law or agreed to in writing,
10   * software distributed under the License is distributed on an "AS IS"
11   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing
13   * permissions and limitations under the License.
14   *
15   * Created by Charles on 8/4/2014
16   */
17  package org.kuali.student.poc.jsonparser.consumer;
18  
19  import org.kuali.student.poc.jsonparser.producer.BaseProducer;
20  import org.kuali.student.poc.jsonparser.tokenizer.token.BaseToken;
21  import org.kuali.student.poc.jsonparser.tokenizer.token.NumberToken;
22  
23  import java.text.ParseException;
24  
25  /**
26   * Tokenizes a JSON number
27   *
28   * @author Kuali Student Team
29   */
30  public class NumberConsumer implements BaseConsumer {
31      @Override
32      public BaseToken consume(BaseProducer producer) throws ParseException {
33          if (!producer.hasNext()) {
34              return null;
35          }
36          char ch = producer.peek();
37          StringBuilder buf = new StringBuilder();
38          int dotCount = 0;
39          int i = 0;
40          while (ch == '-' || Character.isDigit(ch) || ch == '.') {
41              if (ch == '-' && i > 0) {
42                  String err = "Error at row = " + producer.getRow() + " col = " + producer.getColumn();
43                  throw new ParseException(err, producer.getColumn());
44              }
45              if (ch == '.') {
46                  dotCount++;
47                  if (dotCount > 1) {
48                      String err = "Error at row = " + producer.getRow() + " col = " + producer.getColumn();
49                      throw new ParseException(err, producer.getColumn());
50                  }
51              }
52              buf.append(ch);
53              producer.consume();
54              ch = producer.peek();
55              i++;
56          }
57          String numStr = buf.toString();
58          NumberToken numberToken = new NumberToken(numStr);
59          return numberToken;
60      }
61  }