2 package org.collectionspace.services.id.part;
4 import java.util.Random;
6 import org.slf4j.Logger;
7 import org.slf4j.LoggerFactory;
9 // Returns a evenly-distributed, pseudorandom number from within a
10 // default or supplied range of integer values.
12 public class JavaRandomNumberIDPartAlgorithm implements IDPartAlgorithm {
14 // @TODO Verify whether this simple singleton pattern is
15 // achieving the goal of using a single instance of the random
18 // @TODO Check whether we might need to store a serialization
19 // of this class, once instantiated, between invocations, and
20 // load the class from its serialized state, to reduce the
23 // @TODO Look into whether we may have some user stories or use cases
24 // that require the use of java.security.SecureRandom, rather than
28 LoggerFactory.getLogger(JavaRandomNumberIDPartAlgorithm.class);
30 // Starting with Java 5, the default instantiation of Random()
31 // sets the seed "to a value very likely to be distinct from any
32 // other invocation of this constructor."
33 private static Random r = new Random();
35 public final static int DEFAULT_MAX_VALUE = Integer.MAX_VALUE - 1;
36 public final static int DEFAULT_MIN_VALUE = 0;
38 private int maxValue = DEFAULT_MAX_VALUE;
39 private int minValue = DEFAULT_MIN_VALUE;
41 public JavaRandomNumberIDPartAlgorithm() {
44 // Throws IllegalArgumentException
45 public JavaRandomNumberIDPartAlgorithm(int maxVal) {
48 } catch (IllegalArgumentException e) {
53 // Throws IllegalArgumentException
54 public JavaRandomNumberIDPartAlgorithm(int maxVal, int minVal) {
59 private void setMaxValue(int maxVal) {
60 if (0 < maxVal && maxVal < DEFAULT_MAX_VALUE) {
61 this.maxValue = maxVal;
64 "Invalid maximum value for random number. " +
65 "Must be between 1 and " +
66 Integer.toString(DEFAULT_MAX_VALUE - 1) + ".";
68 throw new IllegalArgumentException(msg);
72 private void setMinValue(int minVal) {
73 if (DEFAULT_MIN_VALUE <= minVal && minVal < this.maxValue) {
74 this.minValue = minVal;
77 "Invalid minimum value for random number. " +
78 "Must be between 0 and " +
79 Integer.toString(this.maxValue - 1) + ".";
81 throw new IllegalArgumentException(msg);
86 public String generateID(){
87 // Returns an evenly distributed random value between 0
88 // and the maximum value.
89 // See http://mindprod.com/jgloss/pseudorandom.html
91 // Note: Random.nextInt() returns a pseudorandom number
92 // between 0 and n-1 inclusive, not a number between 0 and n.
94 Integer.toString(r.nextInt(
95 this.maxValue - this.minValue + 1) + this.minValue);