View Javadoc

1   /*
2    *  Copyright 2009-2013 Stephen Colebourne
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package org.joda.money.format;
17  
18  import java.io.IOException;
19  import java.io.Serializable;
20  
21  import org.joda.money.BigMoney;
22  
23  /**
24   * Prints and parses a literal.
25   * <p>
26   * This class is immutable and thread-safe.
27   */
28  final class LiteralPrinterParser implements MoneyPrinter, MoneyParser, Serializable {
29  
30      /** Serialization version. */
31      private static final long serialVersionUID = 1L;
32  
33      /** Literal. */
34      private final String literal;
35  
36      /**
37       * Constructor.
38       * @param literal  the literal text, not null
39       */
40      LiteralPrinterParser(String literal) {
41          this.literal = literal;
42      }
43  
44      //-----------------------------------------------------------------------
45      public void print(MoneyPrintContext context, Appendable appendable, BigMoney money) throws IOException {
46          appendable.append(literal);
47      }
48  
49      public void parse(MoneyParseContext context) {
50          int endPos = context.getIndex() + literal.length();
51          if (endPos <= context.getTextLength() &&
52                  context.getTextSubstring(context.getIndex(), endPos).equals(literal)) {
53              context.setIndex(endPos);
54          } else {
55              context.setError();
56          }
57      }
58  
59      @Override
60      public String toString() {
61          return "'" + literal + "'";
62      }
63  
64  }