1 19 20 package org.apache.avalon.excalibur.datasource.ids; 21 22 import java.math.BigDecimal ; 23 24 import org.apache.avalon.framework.logger.AbstractLogEnabled; 25 import org.apache.avalon.framework.thread.ThreadSafe; 26 27 32 public abstract class AbstractIdGenerator 33 extends AbstractLogEnabled 34 implements IdGenerator, ThreadSafe 35 { 36 private static final BigDecimal BIG_DECIMAL_MAX_LONG = new BigDecimal ( Long.MAX_VALUE ); 37 38 41 private Object m_semaphore = new Object (); 42 43 46 private boolean m_useBigDecimals; 47 48 51 public AbstractIdGenerator() 52 { 53 } 54 55 58 66 protected abstract BigDecimal getNextBigDecimalIdInner() 67 throws IdException; 68 69 77 protected abstract long getNextLongIdInner() 78 throws IdException; 79 80 88 protected final void setUseBigDecimals( boolean useBigDecimals ) 89 { 90 m_useBigDecimals = useBigDecimals; 91 } 92 93 96 protected final boolean isUsingBigDecimals() 97 { 98 return m_useBigDecimals; 99 } 100 101 106 protected final long getNextLongIdChecked( long maxId ) 107 throws IdException 108 { 109 long nextId; 110 if( m_useBigDecimals ) 111 { 112 BigDecimal bd; 114 synchronized( m_semaphore ) 115 { 116 bd = getNextBigDecimalIdInner(); 117 } 118 119 if( bd.compareTo( BIG_DECIMAL_MAX_LONG ) > 0 ) 121 { 122 String msg = "Unable to provide an id. The next id would " + 123 "be greater than the id data type allows."; 124 getLogger().error( msg ); 125 throw new IdException( msg ); 126 } 127 nextId = bd.longValue(); 128 } 129 else 130 { 131 synchronized( m_semaphore ) 133 { 134 nextId = getNextLongIdInner(); 135 } 136 } 137 138 if( nextId > maxId ) 140 { 141 String msg = "Unable to provide an id. The next id would " + 142 "be greater than the id data type allows."; 143 getLogger().error( msg ); 144 throw new IdException( msg ); 145 } 146 147 return nextId; 148 } 149 150 153 158 public final BigDecimal getNextBigDecimalId() 159 throws IdException 160 { 161 BigDecimal bd; 162 if( m_useBigDecimals ) 163 { 164 synchronized( m_semaphore ) 166 { 167 bd = getNextBigDecimalIdInner(); 168 } 169 } 170 else 171 { 172 synchronized( m_semaphore ) 174 { 175 bd = new BigDecimal ( getNextLongIdInner() ); 176 } 177 } 178 179 return bd; 180 } 181 182 189 public final long getNextLongId() 190 throws IdException 191 { 192 return getNextLongIdChecked( Long.MAX_VALUE ); 193 } 194 195 202 public final int getNextIntegerId() 203 throws IdException 204 { 205 return (int)getNextLongIdChecked( Integer.MAX_VALUE ); 206 } 207 208 215 public final short getNextShortId() 216 throws IdException 217 { 218 return (short)getNextLongIdChecked( Short.MAX_VALUE ); 219 } 220 221 228 public final byte getNextByteId() 229 throws IdException 230 { 231 return (byte)getNextLongIdChecked( Byte.MAX_VALUE ); 232 } 233 } 234 235 | Popular Tags |