1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package com.rapiddweller.benerator.primitive;
28
29 import com.rapiddweller.benerator.GeneratorContext;
30 import com.rapiddweller.benerator.IllegalGeneratorStateException;
31 import com.rapiddweller.benerator.distribution.Distribution;
32 import com.rapiddweller.benerator.util.LuhnUtil;
33 import com.rapiddweller.benerator.wrapper.NonNullGeneratorProxy;
34 import com.rapiddweller.common.StringUtil;
35
36
37
38
39
40
41
42
43 public class LuhnGenerator extends NonNullGeneratorProxy<String> {
44
45
46
47
48 protected String prefix;
49
50
51
52 protected int minLength;
53
54
55
56 protected int maxLength;
57
58
59
60 protected final int lengthGranularity;
61
62
63
64 protected final Distribution lengthDistribution;
65
66
67
68
69 public LuhnGenerator() {
70 this("", 16);
71 }
72
73
74
75
76
77
78
79 public LuhnGenerator(String prefix, int length) {
80 this(prefix, length, length, 1, null);
81 }
82
83
84
85
86
87
88
89
90
91
92 public LuhnGenerator(String prefix, int minLength, int maxLength, int lengthGranularity, Distribution lengthDistribution) {
93 super(String.class);
94 this.prefix = prefix;
95 this.minLength = minLength;
96 this.maxLength = maxLength;
97 this.lengthGranularity = 1;
98 this.lengthDistribution = lengthDistribution;
99 }
100
101
102
103
104
105
106 public void setPrefix(String prefix) {
107 this.prefix = prefix;
108 }
109
110
111
112
113
114
115 public void setMinLength(int minLength) {
116 this.minLength = minLength;
117 }
118
119
120
121
122
123
124 public void setMaxLength(int maxLength) {
125 this.maxLength = maxLength;
126 }
127
128 @Override
129 public synchronized void init(GeneratorContext context) {
130 super.setSource(new RandomVarLengthStringGenerator("\\d", minLength, maxLength, lengthGranularity, lengthDistribution));
131 super.init(context);
132 }
133
134 @Override
135 public String generate() throws IllegalGeneratorStateException {
136 String number = super.generate();
137 if (!StringUtil.isEmpty(prefix)) {
138 number = prefix + number.substring(prefix.length());
139 }
140 char checkDigit = LuhnUtil.requiredCheckDigit(number);
141 if (StringUtil.lastChar(number) == checkDigit) {
142 return number;
143 } else {
144 return number.substring(0, number.length() - 1) + checkDigit;
145 }
146 }
147
148 }