-
Notifications
You must be signed in to change notification settings - Fork 8
/
Fluxtion.java
354 lines (322 loc) · 15.5 KB
/
Fluxtion.java
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package com.fluxtion.compiler;
import com.fluxtion.compiler.generation.EventProcessorFactory;
import com.fluxtion.compiler.generation.RuntimeConstants;
import com.fluxtion.runtime.EventProcessor;
import com.fluxtion.runtime.StaticEventProcessor;
import com.fluxtion.runtime.annotations.builder.Disabled;
import com.fluxtion.runtime.lifecycle.Lifecycle;
import com.fluxtion.runtime.partition.LambdaReflection.SerializableConsumer;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfoList;
import io.github.classgraph.ScanResult;
import lombok.SneakyThrows;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.util.Objects;
import java.util.concurrent.atomic.LongAdder;
/**
* Entry point for generating a {@link StaticEventProcessor}
*/
public interface Fluxtion {
/**
* Generates and compiles Java source code for a {@link StaticEventProcessor}. The compiled version only requires
* the Fluxtion runtime dependencies to operate and process events. The source code is only maintained in memory
* as a string and is not persisted,
*
* <p>
* {@link Lifecycle#init()} has not been called on the returned instance. The caller must invoke init before
* sending events to the processor using {@link StaticEventProcessor#onEvent(Object)}
*
* @param sepConfig the configuration used to build this {@link StaticEventProcessor}
* @return An uninitialized instance of a {@link StaticEventProcessor}
* @see EventProcessorConfig
*/
@SneakyThrows
static EventProcessor compile(SerializableConsumer<EventProcessorConfig> sepConfig) {
return EventProcessorFactory.compile(sepConfig);
}
static EventProcessor compile(Object... nodes) {
return compile(c -> {
for (int i = 0; i < nodes.length; i++) {
c.addNode(nodes[i]);
}
});
}
/**
* Compiles the SEP in memory and captures the output to a user supplied {@link Writer}
*
* @param sepConfig graph building config
* @param sourceWriter target source writer
* @return
*/
@SneakyThrows
static EventProcessor compile(SerializableConsumer<EventProcessorConfig> sepConfig, Writer sourceWriter) {
return EventProcessorFactory.compile(sepConfig, c -> {
c.setSourceWriter(sourceWriter);
c.setWriteSourceToFile(false);
c.setGenerateDescription(false);
c.setFormatSource(true);
});
}
@SneakyThrows
static EventProcessor compile(SerializableConsumer<EventProcessorConfig> sepConfig,
SerializableConsumer<FluxtionCompilerConfig> cfgBuilder) {
return EventProcessorFactory.compile(sepConfig, cfgBuilder);
}
@SneakyThrows
static EventProcessor compileAot(SerializableConsumer<EventProcessorConfig> cfgBuilder) {
String packageName = (cfgBuilder.getContainingClass().getCanonicalName() + "." + cfgBuilder.method().getName()).toLowerCase();
return compile(cfgBuilder, compilerCfg -> compilerCfg.setPackageName(packageName));
}
static EventProcessor compileAot(String packageName,
String className,
Object... nodes) {
return compileAot(c -> {
for (int i = 0; i < nodes.length; i++) {
c.addNode(nodes[i]);
}
}, packageName, className);
}
static EventProcessor compileAot(Object... nodes) {
return compileAot(c -> {
for (int i = 0; i < nodes.length; i++) {
c.addNode(nodes[i]);
}
});
}
@SneakyThrows
static EventProcessor compileAot(SerializableConsumer<EventProcessorConfig> cfgBuilder,
String packageName,
String className) {
return compile(cfgBuilder, compilerCfg -> {
compilerCfg.setPackageName(packageName.trim());
compilerCfg.setClassName(className.trim());
});
}
/**
* Generates an in memory version of a {@link StaticEventProcessor}. The in memory version is transient and requires
* the runtime and compiler Fluxtion libraries to operate.
* <p>
* {@link Lifecycle#init()} has not been called on the returned instance. The caller must invoke init before
* sending events to the processor using {@link StaticEventProcessor#onEvent(Object)}
*
* @param sepConfig the configuration used to build this {@link StaticEventProcessor}
* @return An uninitialized instance of a {@link StaticEventProcessor}
* @see EventProcessorConfig
*/
static EventProcessor interpret(SerializableConsumer<EventProcessorConfig> sepConfig) {
return EventProcessorFactory.interpreted(sepConfig);
}
static EventProcessor interpret(SerializableConsumer<EventProcessorConfig> sepConfig, boolean generateDescription) {
return EventProcessorFactory.interpreted(sepConfig, generateDescription);
}
static EventProcessor interpret(Object... nodes) {
return interpret(c -> {
for (int i = 0; i < nodes.length; i++) {
c.addNode(nodes[i]);
}
});
}
/**
* Generates and compiles Java source code for a {@link StaticEventProcessor}. The compiled version only requires
* the Fluxtion runtime dependencies to operate and process events.
* <p>
* {@link Lifecycle#init()} has not been called on the returned instance. The caller must invoke init before
* sending events to the processor using {@link StaticEventProcessor#onEvent(Object)}
* <p>
* The root node is injected into the graph. If the node has any injected dependencies these are added to the
* graph. If a custom builder for the root node exists this will called and additional nodes can be added to the
* graph in the factory method.
*
* @param rootNode the root node of this graph
* @return An uninitialized instance of a {@link StaticEventProcessor}
*/
@SneakyThrows
static EventProcessor compile(RootNodeConfig rootNode) {
return EventProcessorFactory.compile(rootNode);
}
@SneakyThrows
static EventProcessor compile(RootNodeConfig rootNode, SerializableConsumer<FluxtionCompilerConfig> cfgBuilder) {
return EventProcessorFactory.compile(rootNode, cfgBuilder);
}
@SneakyThrows
static EventProcessor compileAot(RootNodeConfig rootNode) {
String pkg = (rootNode.getRootClass().getCanonicalName() + "." + rootNode.getName()).toLowerCase();
return EventProcessorFactory.compile(rootNode, compilerCfg -> compilerCfg.setPackageName(pkg));
}
@SneakyThrows
static EventProcessor compileAot(RootNodeConfig rootNode, String packagePrefix) {
String pkg = (packagePrefix + "." + rootNode.getName()).toLowerCase();
return EventProcessorFactory.compile(rootNode, compilerCfg -> compilerCfg.setPackageName(pkg));
}
/**
* Generates an EventProcessor from a yaml document read from a supplied reader.
* <p>
* Format:
* <p>
* Example yaml output for a definition
* <pre>
* Yaml yaml = new Yaml();
* Map<String, Object> configMap = new HashMap<>();
* configMap.put("firstKey", 12);
* configMap.put("anotherKey", "my value");
* FluxtionCompilerConfig compilerConfig = new FluxtionCompilerConfig();
* compilerConfig.setPackageName("mypackage.whatever");
* DataDrivenGenerationConfig myRootConfig = new DataDrivenGenerationConfig("myRoot", MyRootClass.class.getCanonicalName(), configMap, compilerConfig);
* System.out.println("dumpAsMap:\n" + yaml.dumpAsMap(myRootConfig));
* </pre>
*
* <pre>
* rootClass: com.company.MyRootClass
* name: myRoot
* configMap:
* anotherKey: my value
* firstKey: 12
* compilerConfig:
* buildOutputDirectory: null
* className: null
* compileSource: true
* formatSource: false
* generateDescription: false
* outputDirectory: src/main/java/
* packageName: mypackage.whatever
* resourcesOutputDirectory: src/main/resources/
* templateSep: template/base/javaTemplate.vsl
* writeSourceToFile: false
* </pre>
*
* @param reader the source of the yaml document
* @return A compile EventProcessor
*/
@SneakyThrows
static EventProcessor compileFromReader(Reader reader) {
Yaml yaml = new Yaml();
DataDrivenGenerationConfig rootInjectedConfig = yaml.loadAs(reader, DataDrivenGenerationConfig.class);
String overrideOutputDirectory = System.getProperty(RuntimeConstants.OUTPUT_DIRECTORY);
if (overrideOutputDirectory != null && !overrideOutputDirectory.isEmpty()) {
rootInjectedConfig.getCompilerConfig().setOutputDirectory(overrideOutputDirectory);
}
String overrideResourceDirectory = System.getProperty(RuntimeConstants.RESOURCES_DIRECTORY);
if (overrideResourceDirectory != null && !overrideResourceDirectory.isEmpty()) {
rootInjectedConfig.getCompilerConfig().setResourcesOutputDirectory(overrideResourceDirectory);
}
if (rootInjectedConfig.getCompilerConfig().isInterpreted()) {
return interpret(rootInjectedConfig.getRootNodeConfig());
} else {
return EventProcessorFactory.compile(rootInjectedConfig.getEventProcessorConfig(), rootInjectedConfig.getCompilerConfig());
}
}
/**
* Generates an in memory version of a {@link StaticEventProcessor}. The in memory version is transient and requires
* the runtime and compiler Fluxtion libraries to operate.
* <p>
* {@link Lifecycle#init()} has not been called on the returned instance. The caller must invoke init before
* sending events to the processor using {@link StaticEventProcessor#onEvent(Object)}
* <p>
* The root node is injected into the graph. If the node has any injected dependencies these are added to the
* graph. If a custom builder for the root node exists this will called and additional nodes can be added to the
* graph in the factory method.
*
* @param rootNode the root node of this graph0
* @return An uninitialized instance of a {@link StaticEventProcessor}
*/
@SneakyThrows
static EventProcessor interpret(RootNodeConfig rootNode) {
return EventProcessorFactory.interpreted(rootNode);
}
@SneakyThrows
static EventProcessor interpret(RootNodeConfig rootNode, boolean generateDescription) {
return EventProcessorFactory.interpreted(rootNode, generateDescription);
}
/**
* Scans the supplied File resources for any classes that implement the {@link FluxtionGraphBuilder} interface
* and will generate an {@link EventProcessor} for any located builders.
* <p>
* Any builder marked with the {@link Disabled} annotation will be ignored
*
* @param files The locations to search for {@link FluxtionGraphBuilder} classes
* @return The number of processors generated
*/
static int scanAndCompileFluxtionBuilders(File... files) {
Objects.requireNonNull(files, "provide valid locations to search for fluxtion builders");
LongAdder generationCount = new LongAdder();
try (ScanResult scanResult = new ClassGraph()
.enableAllInfo()
.overrideClasspath(files)
.scan()) {
ClassInfoList builderList = scanResult
.getClassesImplementing(FluxtionGraphBuilder.class)
.exclude(scanResult.getClassesWithAnnotation(Disabled.class.getCanonicalName()));
builderList.forEach(c -> {
generationCount.increment();
System.out.println(generationCount.intValue() + ": invoking builder " + c.getName());
try {
final FluxtionGraphBuilder newInstance = (FluxtionGraphBuilder) c.loadClass().getDeclaredConstructor().newInstance();
compile(newInstance::buildGraph, newInstance::configureGeneration);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException e) {
throw new RuntimeException("cannot instantiate FluxtionGraphBuilder", e);
}
});
}
return generationCount.intValue();
}
/**
* Scans the supplied File resources for any classes that implement the {@link FluxtionGraphBuilder} interface
* and will generate an {@link EventProcessor} for any located builders.
* <p>
* Any builder marked with the {@link Disabled} annotation will be ignored
* <p>
* No compilations are carried out
*
* @param classLoader the classloader to be used for the generation
* @param files The locations to search for {@link FluxtionGraphBuilder} classes
* @return The number of processors generated
*/
static int scanAndGenerateFluxtionBuilders(ClassLoader classLoader, File... files) {
Objects.requireNonNull(files, "provide valid locations to search for fluxtion builders");
System.setProperty(RuntimeConstants.FLUXTION_NO_COMPILE, "true");
LongAdder generationCount = new LongAdder();
try (ScanResult scanResult = new ClassGraph()
.enableAllInfo()
.overrideClasspath(files)
.scan()) {
ClassInfoList builderList = scanResult
.getClassesImplementing(FluxtionGraphBuilder.class)
.exclude(scanResult.getClassesWithAnnotation(Disabled.class.getCanonicalName()));
builderList.forEach(c -> {
generationCount.increment();
System.out.println(generationCount.intValue() + ": invoking builder " + c.getName());
try {
final FluxtionGraphBuilder newInstance = (FluxtionGraphBuilder) classLoader.loadClass(c.getName()).getDeclaredConstructor().newInstance();
FluxtionCompilerConfigOverride override = new FluxtionCompilerConfigOverride(newInstance);
compile(newInstance::buildGraph, override::overrideClassPath);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException | ClassNotFoundException e) {
throw new RuntimeException("cannot instantiate FluxtionGraphBuilder", e);
}
});
}
return generationCount.intValue();
}
class FluxtionCompilerConfigOverride {
private final FluxtionGraphBuilder newInstance;
public FluxtionCompilerConfigOverride(FluxtionGraphBuilder newInstance) {
this.newInstance = newInstance;
}
public void overrideClassPath(FluxtionCompilerConfig cfgBuilder) {
newInstance.configureGeneration(cfgBuilder);
String overrideOutputDirectory = System.getProperty(RuntimeConstants.OUTPUT_DIRECTORY);
if (overrideOutputDirectory != null && !overrideOutputDirectory.isEmpty()) {
cfgBuilder.setOutputDirectory(overrideOutputDirectory);
}
String overrideResourceDirectory = System.getProperty(RuntimeConstants.RESOURCES_DIRECTORY);
if (overrideResourceDirectory != null && !overrideResourceDirectory.isEmpty()) {
cfgBuilder.setResourcesOutputDirectory(overrideResourceDirectory);
}
}
}
}