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.wrapper;
28
29 import com.rapiddweller.benerator.Generator;
30 import com.rapiddweller.benerator.GeneratorContext;
31 import com.rapiddweller.benerator.IllegalGeneratorStateException;
32 import com.rapiddweller.benerator.InvalidGeneratorSetupException;
33 import com.rapiddweller.benerator.util.AbstractGenerator;
34 import com.rapiddweller.common.IOUtil;
35 import com.rapiddweller.common.ThreadAware;
36 import com.rapiddweller.format.DataContainer;
37 import com.rapiddweller.format.DataIterator;
38 import com.rapiddweller.format.DataSource;
39 import com.rapiddweller.format.util.ThreadLocalDataContainer;
40
41
42
43
44
45
46
47
48
49 public class DataSourceGenerator<E> extends AbstractGenerator<E> {
50
51 private DataSource<E> source;
52 private DataIterator<E> iterator;
53 private final ThreadLocalDataContainer<E> container = new ThreadLocalDataContainer<>();
54
55
56
57
58
59
60 public DataSourceGenerator() {
61 this(null);
62 }
63
64
65
66
67
68
69 public DataSourceGenerator(DataSource<E> source) {
70 this.source = source;
71 this.iterator = null;
72 }
73
74
75
76
77
78
79
80
81 public DataSource<E> getSource() {
82 return source;
83 }
84
85
86
87
88
89
90 public void setSource(DataSource<E> source) {
91 if (this.source != null) {
92 throw new IllegalGeneratorStateException("Mutating an initialized generator");
93 }
94 this.source = source;
95 }
96
97
98
99 @Override
100 public boolean isParallelizable() {
101 return false;
102 }
103
104 @Override
105 public boolean isThreadSafe() {
106 return (source instanceof ThreadAware && ((ThreadAware) source).isThreadSafe());
107 }
108
109 @Override
110 public Class<E> getGeneratedType() {
111 return source.getType();
112 }
113
114 @Override
115 public void init(GeneratorContext context) {
116 if (source == null) {
117 throw new InvalidGeneratorSetupException("source", "is null");
118 }
119 super.init(context);
120 }
121
122 @Override
123 public ProductWrapper<E> generate(ProductWrapper<E> wrapper) {
124 try {
125 assertInitialized();
126 if (iterator == null) {
127 iterator = source.iterator();
128 }
129 DataContainer<E> tmp = iterator.next(container.get());
130 if (tmp == null) {
131 IOUtil.close(iterator);
132 return null;
133 }
134 return wrapper.wrap(tmp.getData());
135 } catch (Exception e) {
136 throw new IllegalGeneratorStateException("Generation failed: ", e);
137 }
138 }
139
140 @Override
141 public void reset() {
142 IOUtil.close(iterator);
143 iterator = null;
144 super.reset();
145 }
146
147 @Override
148 public void close() {
149 IOUtil.close(iterator);
150 super.close();
151 IOUtil.close(source);
152 }
153
154
155
156 @Override
157 public String toString() {
158 return getClass().getSimpleName() + "[" + source + ']';
159 }
160
161 }