TimeBasedAlphanumericIdentifierGenerator.java

  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. /*
  18.  * Modificato da Link.it (https://link.it) per supportare le seguenti funzionalità:
  19.  * - Generazione ID all'interno delle interfacce di OpenSPCoop2
  20.  * - Gestione caratteri massimi per numeri e cifre
  21.  * - Possibilità di utilizzare lowerCase e/o upperCase
  22.  *
  23.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  24.  */
  25. package org.openspcoop2.utils.id.apache.serial;

  26. import java.io.Serializable;
  27. import java.util.Arrays;
  28. import java.util.Calendar;
  29. import java.util.TimeZone;

  30. import org.openspcoop2.utils.id.apache.AbstractStringIdentifierGenerator;


  31. /**
  32.  * <code>TimeBasedAlphanumericIdentifierGenerator</code> is an identifier generator that generates
  33.  * an alphanumeric identifier in base 36 as a String object from the current UTC time and an
  34.  * internal counter.
  35.  * <p>
  36.  * The generator guarantees that all generated ids have an increasing natural sort order (even if
  37.  * the time internally has an overflow). The implementation additionally guarantees, that all
  38.  * instances within the same process do generate unique ids. All generated ids have the same length
  39.  * (padding with 0's on the left), which is determined by the maximum size of a long value and the
  40.  * <code>postfixSize</code> parameter passed to the constructor.
  41.  * </p>
  42.  * <p>
  43.  * Note: To ensure unique ids that are created within the same millisecond (or maximum time
  44.  * resolution of the system), the implementation uses an internal counter. The maximum value of this
  45.  * counter is determined by the <code>postfixSize</code> parameter i.e. the largest value that can
  46.  * be represented in base 36. If the counter exceeds this value, an IllegalStateException is thrown.
  47.  * </p>
  48.  * <p>
  49.  * Note: The uniqueness of the generated ids cannot be guaranteed if the system performs time shifts
  50.  * of more than a second, that affect the running processes.
  51.  * </p>.
  52.  *
  53.  * Author of the original commons apache code:
  54.  * @author Commons-Id team
  55.  * @version $Id$
  56.  *
  57.  * Authors of the Link.it modification to the code:
  58.  * @author $Author$
  59.  * @version $Rev$, $Date$
  60.  */
  61. public class TimeBasedAlphanumericIdentifierGenerator extends AbstractStringIdentifierGenerator
  62.         implements Serializable {

  63.     /**
  64.      * <code>serialVersionUID</code> is the serializable UID for the binary version of the class.
  65.      */
  66.     private static final long serialVersionUID = 20060116L;
  67.     /**
  68.      * <code>padding</code> an array of '0' for improved padding performance.
  69.      */
  70.     private static final char[] padding;
  71.     static {
  72.         padding = new char[MAX_LONG_ALPHANUMERIC_VALUE_LENGTH];
  73.         Arrays.fill(padding, '0');
  74.     }
  75.     /**
  76.      * <code>UTC</code> is the UTC {@link TimeZone} instance.
  77.      */
  78.     private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
  79.     /**
  80.      * <code>last</code> is the marker, when the counter was resetted the last time.
  81.      */
  82.     private static long last = 0;
  83.     /**
  84.      * <code>counter</code> counts the number of generated identifiers since the last reset.
  85.      */
  86.     private static long counter = 0;
  87.     /**
  88.      * <code>postfixSize</code> size of the postfix, that contains the padded counter in base 36.
  89.      */
  90.     private final int postfixSize;
  91.     private final long offset;
  92.    
  93.     /**
  94.      * Construct a TimeBasedAlphanumericIdentifierGenerator with a defined size of the postfix and
  95.      * an offset for the time value. The offset can be used to manipulate the representation of the
  96.      * time value in the generated id. If a TimeBasedAlphanumericIdentifierGenerator is constructed
  97.      * with an offset of the current number of milliseconds since 1st Jan 1970 the first generated
  98.      * id in the same millisecond will have an id consisting of a sequence of '0' characters.
  99.      *
  100.      * @param postfixSize the size of the postfix
  101.      * @param offset the offset taken into account for the time value
  102.      * @throws IllegalArgumentException if <code>postfixSize</code> is negative or exceeds the
  103.      *             maximum size for representing {@link Long#MAX_VALUE} in base 36
  104.      */
  105.     public TimeBasedAlphanumericIdentifierGenerator(final int postfixSize, final long offset) {
  106.         if (postfixSize < 0 || postfixSize > MAX_LONG_ALPHANUMERIC_VALUE_LENGTH) {
  107.             throw new IllegalArgumentException("Invalid size for postfix");
  108.         }
  109.         this.postfixSize = postfixSize;
  110.         this.offset = offset;
  111.     }

  112.     /**
  113.      * Construct a TimeBasedAlphanumericIdentifierGenerator with a defined size of the postfix.
  114.      *
  115.      * @param postfixSize the size of the postfix defining the maximum number of possible ids
  116.      *            generated within the same millisecond (depending on the time resolution of the
  117.      *            running system)
  118.      * @throws IllegalArgumentException if <code>postfixSize</code> is negative or exceeds the
  119.      *             maximum size for representing {@link Long#MAX_VALUE} in base 36
  120.      */
  121.     public TimeBasedAlphanumericIdentifierGenerator(final int postfixSize) {
  122.         this(postfixSize, 0);
  123.     }

  124.     /**
  125.      * Construct a TimeBasedAlphanumericIdentifierGenerator with a default size of the postfix of 3.
  126.      */
  127.     public TimeBasedAlphanumericIdentifierGenerator() {
  128.         this(3);
  129.     }

  130.     @Override
  131.     public long maxLength() {
  132.         return ((long)MAX_LONG_ALPHANUMERIC_VALUE_LENGTH) + ((long)this.postfixSize);
  133.     }

  134.     @Override
  135.     public long minLength() {
  136.         return maxLength();
  137.     }

  138.     private static void updateLast(long now) {
  139.         last = now;
  140.     }
  141.     private static void resetCounter() {
  142.         counter = 0;
  143.     }
  144.     private static void incrementCounter() {
  145.         ++counter;
  146.     }
  147.    
  148.     @Override
  149.     public String nextStringIdentifier() throws MaxReachedException {
  150.         long now;
  151.         synchronized (this) {
  152.             now = Calendar.getInstance(UTC).getTime().getTime(); // JDK 1.3 compatibility
  153.             final long diff = now - last;
  154.             // external time correction of more than a second or overflow
  155.             if (diff > 0 || diff < -1000) {
  156.                 updateLast(now);
  157.                 resetCounter();
  158.             } else {
  159.                 if (diff != 0) {
  160.                     now = last; // ignore time shift
  161.                 }
  162.                 incrementCounter();
  163.             }
  164.         }
  165.         final String postfix = counter > 0
  166.                                           ? Long.toString(counter, ALPHA_NUMERIC_CHARSET_SIZE) : "";
  167.         if (postfix.length() > this.postfixSize) {
  168.             throw new MaxReachedException(
  169.                     "The maximum number of identifiers in this millisecond has been reached");
  170.         }
  171.         // ensure, that no negative value is used and values stay increasing
  172.         long base = now - this.offset;
  173.         long value = base < 0 ? base + Long.MAX_VALUE + 1 : base;
  174.         final String time = Long.toString(value, ALPHA_NUMERIC_CHARSET_SIZE);
  175.         final char[] buffer = new char[MAX_LONG_ALPHANUMERIC_VALUE_LENGTH + this.postfixSize];
  176.         int i = 0;
  177.         int maxPad = MAX_LONG_ALPHANUMERIC_VALUE_LENGTH - time.length();
  178.         if (maxPad > 0) {
  179.             System.arraycopy(padding, 0, buffer, 0, maxPad);
  180.         }
  181.         System.arraycopy(time.toCharArray(), 0, buffer, maxPad, time.length());
  182.         if (base < 0) {
  183.             // Representation of Long.MAX_VALUE starts with '1', negative 'base' means higher value
  184.             // in time
  185.             buffer[0] += 2;
  186.         }
  187.         i += time.length() + maxPad;
  188.         if (this.postfixSize > 0) {
  189.             maxPad = this.postfixSize - postfix.length();
  190.             if (maxPad > 0) {
  191.                 System.arraycopy(padding, 0, buffer, i, maxPad);
  192.                 i += maxPad;
  193.             }
  194.             System.arraycopy(postfix.toCharArray(), 0, buffer, i, postfix.length());
  195.         }
  196.         return new String(buffer);
  197.     }

  198.     /**
  199.      * Retrieve the number of milliseconds since 1st Jan 1970 that were the base for the given id.
  200.      *
  201.      * @param id the id to use
  202.      * @param offset the offset used to create the id
  203.      * @return the number of milliseconds
  204.      * @throws IllegalArgumentException if <code>id</code> is not a valid id from this type of
  205.      *             generator
  206.      */
  207.     public long getMillisecondsFromId(final Object id, final long offset) {
  208.         if (id instanceof String && id.toString().length() >= MAX_LONG_ALPHANUMERIC_VALUE_LENGTH) {
  209.             final char[] buffer = new char[MAX_LONG_ALPHANUMERIC_VALUE_LENGTH];
  210.             System.arraycopy(
  211.                     id.toString().toCharArray(), 0, buffer, 0, MAX_LONG_ALPHANUMERIC_VALUE_LENGTH);
  212.             final boolean overflow = buffer[0] > '1';
  213.             if (overflow) {
  214.                 buffer[0] -= 2;
  215.             }
  216.             long value = Long.parseLong(new String(buffer), ALPHA_NUMERIC_CHARSET_SIZE);
  217.             if (overflow) {
  218.                 value -= Long.MAX_VALUE + 1;
  219.             }
  220.             return value + offset;
  221.         }
  222.         throw new IllegalArgumentException("'" + id + "' is not an id from this generator");
  223.     }
  224. }