1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.betwixt.io.id;
17
18 import java.util.Random;
19
20 /*** <p>Generates <code>ID</code>'s at random.
21 * The random number source is <code>java.util.Random</code>.</p>
22 *
23 * <p>Random <code>ID</code>'s are very useful if you're inserting
24 * elements created by <code>Betwixt</code> into a stream with existing
25 * elements.
26 * Using random <code>ID</code>'s should reduce the danger of collision
27 * with existing element <code>ID</code>'s.</p>
28 *
29 * <p>This class can generate positive-only ids (the default)
30 * or it can generate a mix of negative and postive ones.
31 * This behaviour can be set by {@link #setPositiveIds}
32 * or by using the {@link #RandomIDGenerator(boolean onlyPositiveIds)}
33 * constructor.</p>
34 *
35 * @author <a href="mailto:rdonkin@apache.org">Robert Burrell Donkin</a>
36 * @version $Revision: 1.7 $
37 */
38 public final class RandomIDGenerator extends AbstractIDGenerator {
39
40 /*** Use simple java.util.Random as the source for our numbers */
41 private Random random = new Random();
42 /*** Should only positive id's be generated? */
43 private boolean onlyPositiveIds = true;
44
45 /***
46 * Constructor sets the <code>PositiveIds</code> property to <code>true</code>.
47 */
48 public RandomIDGenerator() {}
49
50 /***
51 * Constructor sets <code>PositiveIds</code> property.
52 *
53 * @param onlyPositiveIds set <code>PositiveIds</code> property to this value
54 */
55 public RandomIDGenerator(boolean onlyPositiveIds) {
56 setPositiveIds(onlyPositiveIds);
57 }
58
59 /***
60 * <p>Generates a random <code>ID</code><p>
61 *
62 * <p>If the <code>PositiveIds</code> property is true,
63 * then this method will recursively call itself if the random
64 * <code>ID</code> is less than zero.</p>
65 *
66 * @return a random integer (converted to a string)
67 */
68 public String nextIdImpl() {
69 int next = random.nextInt();
70 if (onlyPositiveIds && next<0) {
71
72 return nextIdImpl();
73 }
74 return Integer.toString(next);
75 }
76
77 /***
78 * Gets whether only positive <code>ID</code>'s should be generated
79 *
80 * @return whether only positive IDs should be generated
81 */
82 public boolean getPositiveIds() {
83 return onlyPositiveIds;
84 }
85
86 /***
87 * Sets whether only positive <code>ID</code>'s should be generated
88 *
89 * @param onlyPositiveIds pass true if only positive IDs should be generated
90 */
91 public void setPositiveIds(boolean onlyPositiveIds) {
92 this.onlyPositiveIds = onlyPositiveIds;
93 }
94 }