/* * Copyright (c) 2014 the original author or authors * * 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 io.werval.util; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; /** * UUID based IdentityGenerator. * <p> * Generated identities have the following form: {@literal (PREFIX_)UUID_COUNT}. * <p> * {@literal PREFIX} is optional, see {@link #UUIDIdentityGenerator(java.lang.String)} * and {@link #UUIDIdentityGenerator(java.lang.String, int)}. * <p> * {@literal COUNT} can be left-padded with zeroes, see {@link #UUIDIdentityGenerator(int)} * and {@link #UUIDIdentityGenerator(java.lang.String, int)}. * <p> * Each instance holds a {@link UUID} and an {@link AtomicLong} based counter. * Identities are generated by concatenating the UUID and the counter. * The later is incremented along the way. */ public final class UUIDIdentityGenerator implements IdentityGenerator { private final int countLength; private final String prefix; private String prefixedUuid; private AtomicLong counter; public UUIDIdentityGenerator() { this( Strings.EMPTY, -1 ); } /** * Use this constructor to left-pad counter with zeroes. * * @param countLength Length of the COUNT part of the generated identities. * A negative value disable padding. */ public UUIDIdentityGenerator( int countLength ) { this( Strings.EMPTY, countLength ); } /** * Use this constructor to prefix the identities. * * @param prefix String to prepend to all generated identities */ public UUIDIdentityGenerator( String prefix ) { this( prefix, -1 ); } /** * Use this constructor to prefix the identities and left-pad the counter with zeroes. * * @param prefix String to prepend to all generated identities * @param countLength Length of the COUNT part of the generated identities. * A negative value disable padding. */ public UUIDIdentityGenerator( String prefix, int countLength ) { this.prefix = prefix; this.countLength = countLength; reset(); } @Override public String newIdentity() { if( countLength > 0 ) { String padFormat = "%0" + ( countLength ) + "d"; return prefixedUuid + String.format( padFormat, counter.getAndIncrement() ); } return prefixedUuid + counter.getAndIncrement(); } /** * Reset the identity UUID & counter. */ public synchronized void reset() { StringBuilder sb = new StringBuilder(); if( Strings.hasText( prefix ) ) { sb.append( prefix ).append( "_" ); } sb.append( UUID.randomUUID().toString() ).append( "_" ); prefixedUuid = sb.toString(); counter = new AtomicLong(); } }