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.util;
28
29 import com.rapiddweller.benerator.Generator;
30 import com.rapiddweller.benerator.GeneratorContext;
31 import com.rapiddweller.benerator.GeneratorState;
32 import com.rapiddweller.benerator.IllegalGeneratorStateException;
33 import com.rapiddweller.benerator.wrapper.ProductWrapper;
34 import com.rapiddweller.common.BeanUtil;
35 import org.apache.logging.log4j.LogManager;
36 import org.apache.logging.log4j.Logger;
37
38
39
40
41
42
43
44
45
46 public abstract class AbstractGenerator<E> implements Generator<E> {
47
48
49
50
51 protected final Logger logger = LogManager.getLogger(getClass());
52 private final WrapperProvider<E> resultWrapperProvider;
53
54
55
56 protected GeneratorState state;
57
58
59
60 protected GeneratorContext context;
61
62
63
64
65 public AbstractGenerator() {
66 this.state = GeneratorState.CREATED;
67 this.resultWrapperProvider = new WrapperProvider<>();
68 }
69
70 @Override
71 public synchronized void init(GeneratorContext context) {
72 this.context = context;
73 this.state = GeneratorState.RUNNING;
74 }
75
76 @Override
77 public boolean wasInitialized() {
78 return (state != GeneratorState.CREATED);
79 }
80
81 @Override
82 public void reset() {
83 this.state = GeneratorState.RUNNING;
84 }
85
86 @Override
87 public void close() {
88 this.state = GeneratorState.CLOSED;
89 }
90
91
92
93
94
95
96 protected final void assertNotInitialized() {
97 if (state != GeneratorState.CREATED) {
98 if (state == GeneratorState.RUNNING) {
99 throw new IllegalGeneratorStateException("Trying to initialize generator a 2nd time: " + this);
100 } else {
101 throw new IllegalGeneratorStateException("Trying to initialize generator in '" + state + "' state: " + this);
102 }
103 }
104 }
105
106
107
108
109 protected final void assertInitialized() {
110 if (state == GeneratorState.CREATED) {
111 throw new IllegalGeneratorStateException("Generator has not been initialized: " + this);
112 }
113 if (state == GeneratorState.CLOSED) {
114 throw new IllegalGeneratorStateException("Generator has already been closed: " + this);
115 }
116 }
117
118
119
120
121
122
123 protected ProductWrapper<E> getResultWrapper() {
124 return resultWrapperProvider.get();
125 }
126
127
128
129 @Override
130 public String toString() {
131 return (state == GeneratorState.RUNNING ? BeanUtil.toString(this) : getClass().getSimpleName());
132 }
133
134 }