View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.id.serial;
18  
19  /**
20   * <code>PrefixedNumericGenerator</code> is an Identifier Generator
21   * that generates an incrementing number with a prefix as a String object.
22   *
23   * <p>If the <code>wrap</code> argument passed to the constructor is set to
24   * <code>true</code>, the sequence will wrap, returning negative values when
25   * {@link Long#MAX_VALUE} reached; otherwise an {@link IllegalStateException}
26   * will be thrown.</p>
27   *
28   * @author Commons-Id team
29   * @version $Id$
30   */
31  public class PrefixedNumericGenerator extends NumericGenerator {
32  
33      /** Prefix. */
34      private final String prefix;
35  
36  
37      /**
38       * Create a new prefixed numeric generator with the specified prefix.
39       *
40       * @param prefix prefix, must not be null
41       * @param wrap should the factory wrap when it reaches the maximum
42       *  long value (or throw an exception)
43       * @param initialValue the initial long value to start at
44       * @throws NullPointerException if prefix is <code>null</code>
45       */
46      public PrefixedNumericGenerator(String prefix, boolean wrap, long initialValue) {
47          super(wrap, initialValue);
48  
49          if (prefix == null) {
50              throw new NullPointerException("prefix must not be null");
51          }
52          this.prefix = prefix;
53      }
54  
55  
56      /**
57       * Return the prefix for this prefixed numeric generator.
58       *
59       * @return the prefix for this prefixed numeric generator
60       */
61      public String getPrefix() {
62          return prefix;
63      }
64  
65      public long maxLength() {
66          return super.maxLength() + prefix.length();
67      }
68  
69      public long minLength() {
70          return super.minLength() + prefix.length();
71      }
72  
73      public String nextStringIdentifier() {
74          StringBuffer sb = new StringBuffer(prefix);
75          sb.append(super.nextStringIdentifier());
76          return sb.toString();
77      }
78  }