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