forked from apache/camel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bind.java
513 lines (455 loc) · 21.2 KB
/
Bind.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dsl.jbang.core.commands;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.apache.camel.dsl.jbang.core.common.JSonHelper;
import org.apache.camel.dsl.jbang.core.common.YamlHelper;
import org.apache.camel.github.GitHubResourceResolver;
import org.apache.camel.impl.engine.DefaultResourceResolvers;
import org.apache.camel.spi.Resource;
import org.apache.camel.spi.ResourceResolver;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.json.Jsoner;
import org.snakeyaml.engine.v2.api.LoadSettings;
import org.snakeyaml.engine.v2.api.YamlUnicodeReader;
import org.snakeyaml.engine.v2.composer.Composer;
import org.snakeyaml.engine.v2.nodes.Node;
import org.snakeyaml.engine.v2.parser.Parser;
import org.snakeyaml.engine.v2.parser.ParserImpl;
import org.snakeyaml.engine.v2.scanner.StreamReader;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import static org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.asStringSet;
import static org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.asText;
import static org.apache.camel.dsl.yaml.common.YamlDeserializerSupport.nodeAt;
@Command(name = "bind", description = "Bind source and sink Kamelets as a new Camel integration",
sortOptions = false)
public class Bind extends CamelCommand {
@CommandLine.Parameters(description = "Name of binding file to be saved", arity = "1",
paramLabel = "<file>", parameterConsumer = FileConsumer.class)
Path filePath; // Defined only for file path completion; the field never used
String file;
@CommandLine.Option(names = { "--source" }, description = "Source (from) such as a Kamelet or Camel endpoint uri",
required = true)
String source;
@CommandLine.Option(names = { "--step" }, description = "Optional steps such as a Kamelet or Camel endpoint uri")
String[] steps;
@CommandLine.Option(names = { "--sink" }, description = "Sink (to) such as a Kamelet or Camel endpoint uri",
required = true)
String sink;
@CommandLine.Option(names = { "--error-handler" },
description = "Add error handler (none|log|sink:<endpoint>). Sink endpoints are expected in the format \"[[apigroup/]version:]kind:[namespace/]name\", plain Camel URIs or Kamelet name.")
String errorHandler;
@CommandLine.Option(names = { "--property" },
description = "Adds a pipe property in the form of [source|sink|step-<n>].<key>=<value> where <n> is the step number starting from 1",
arity = "0")
String[] properties;
@CommandLine.Option(names = { "--output" },
defaultValue = "file",
description = "Output format generated by this command (supports: file, yaml or json).")
String output;
private final TemplateProvider templateProvider;
public Bind(CamelJBangMain main) {
this(main, new TemplateProvider() {
});
}
public Bind(CamelJBangMain main, TemplateProvider templateProvider) {
super(main);
this.templateProvider = templateProvider;
}
/**
* Helper class provides access to the templates that construct the Pipe resource. Subclasses may overwrite the
* provider to inject their own templates.
*/
public interface TemplateProvider {
default InputStream getPipeTemplate(String in, String out) {
return Bind.class.getClassLoader().getResourceAsStream("templates/pipe-" + in + "-" + out + ".yaml.tmpl");
}
default InputStream getStepTemplate(String stepType) {
return Bind.class.getClassLoader().getResourceAsStream("templates/step-%s.yaml.tmpl".formatted(stepType));
}
default InputStream getErrorHandlerTemplate(String type) {
return Bind.class.getClassLoader()
.getResourceAsStream("templates/error-handler-%s.yaml.tmpl".formatted(type));
}
}
@Override
public Integer doCall() throws Exception {
String pipe = constructPipe();
if (pipe.isEmpty()) {
printer().println("Failed to construct Pipe resource");
return -1;
}
return dumpPipe(pipe);
}
public String constructPipe() throws Exception {
// the pipe source and sink can either be a kamelet or an uri
String in = "kamelet";
String out = "kamelet";
String sourceEndpoint = source;
String sinkEndpoint = sink;
Map<String, Object> sourceUriProperties = new HashMap<>();
Map<String, Object> sinkUriProperties = new HashMap<>();
if (source.contains(":")) {
in = "uri";
if (source.contains("?")) {
sourceEndpoint = StringHelper.before(source, "?");
String query = StringHelper.after(source, "?");
if (query != null) {
sourceUriProperties = URISupport.parseQuery(query, true);
}
}
}
if (sink.contains(":")) {
out = "uri";
if (sink.contains("?")) {
sinkEndpoint = StringHelper.before(sink, "?");
String query = StringHelper.after(sink, "?");
if (query != null) {
sinkUriProperties = URISupport.parseQuery(query, true);
}
}
}
InputStream is = templateProvider.getPipeTemplate(in, out);
String context = IOHelper.loadText(is);
IOHelper.close(is);
String stepsContext = "";
if (steps != null) {
StringBuilder sb = new StringBuilder("\n steps:\n");
for (int i = 0; i < steps.length; i++) {
String step = steps[i];
boolean uri = step.contains(":");
String text;
String stepType;
Map<String, Object> stepProperties = getProperties("step-%d".formatted(i + 1));
if (uri) {
stepType = "uri";
if (step.contains("?")) {
String query = StringHelper.after(step, "?");
step = StringHelper.before(step, "?");
if (query != null) {
stepProperties.putAll(URISupport.parseQuery(query, true));
}
}
} else {
stepType = "kamelet";
stepProperties = kameletProperties(step, stepProperties);
}
is = templateProvider.getStepTemplate(stepType);
text = IOHelper.loadText(is);
IOHelper.close(is);
text = text.replaceFirst("\\{\\{ \\.Name }}", step);
if (i == steps.length - 1) {
text = text.replaceFirst("\\{\\{ \\.StepProperties }}\n", asEndpointProperties(stepProperties));
} else {
text = text.replaceFirst("\\{\\{ \\.StepProperties }}", asEndpointProperties(stepProperties));
}
sb.append(text);
}
stepsContext = sb.toString();
}
String errorHandlerContext = "";
if (errorHandler != null) {
StringBuilder sb = new StringBuilder("\n errorHandler:\n");
Map<String, Object> errorHandlerParameters = getProperties("error-handler");
String[] errorHandlerTokens = errorHandler.split(":", 2);
String errorHandlerType = errorHandlerTokens[0];
String errorHandlerSpec;
switch (errorHandlerType) {
case "sink":
if (errorHandlerTokens.length != 2) {
printer().println(
"Invalid error handler syntax. Type 'sink' needs an endpoint configuration (ie sink:endpointUri)");
// Error abort Pipe construction
return "";
}
String endpoint = errorHandlerTokens[1];
String sinkType;
Map<String, Object> errorHandlerSinkProperties = getProperties("error-handler.sink");
// remove sink properties from error handler parameters
errorHandlerSinkProperties.keySet().stream()
.map(key -> "sink." + key)
.filter(errorHandlerParameters::containsKey)
.forEach(errorHandlerParameters::remove);
if (endpoint.contains(":")) {
sinkType = "uri";
if (endpoint.contains("?")) {
String query = StringHelper.after(endpoint, "?");
endpoint = StringHelper.before(endpoint, "?");
if (query != null) {
errorHandlerSinkProperties.putAll(URISupport.parseQuery(query, true));
}
}
} else {
sinkType = "kamelet";
errorHandlerSinkProperties = kameletProperties(endpoint, errorHandlerSinkProperties);
}
is = templateProvider.getErrorHandlerTemplate("sink-" + sinkType);
errorHandlerSpec = IOHelper.loadText(is);
IOHelper.close(is);
errorHandlerSpec = errorHandlerSpec.replaceFirst("\\{\\{ \\.Name }}", endpoint);
errorHandlerSpec = errorHandlerSpec.replaceFirst("\\{\\{ \\.ErrorHandlerProperties }}",
asEndpointProperties(errorHandlerSinkProperties, 4));
errorHandlerSpec = errorHandlerSpec.replaceFirst("\\{\\{ \\.ErrorHandlerParameter }}",
asErrorHandlerParameters(errorHandlerParameters));
break;
case "log":
is = templateProvider.getErrorHandlerTemplate("log");
errorHandlerSpec = IOHelper.loadText(is);
IOHelper.close(is);
errorHandlerSpec = errorHandlerSpec.replaceFirst("\\{\\{ \\.ErrorHandlerParameter }}",
asErrorHandlerParameters(errorHandlerParameters));
break;
default:
errorHandlerSpec = " none: {}";
}
sb.append(errorHandlerSpec);
errorHandlerContext = sb.toString();
}
String name = FileUtil.onlyName(file, false);
context = context.replaceFirst("\\{\\{ \\.Name }}", name);
context = context.replaceFirst("\\{\\{ \\.Source }}", sourceEndpoint);
context = context.replaceFirst("\\{\\{ \\.Sink }}", sinkEndpoint);
context = context.replaceFirst("\\{\\{ \\.Steps }}", stepsContext);
context = context.replaceFirst("\\{\\{ \\.ErrorHandler }}", errorHandlerContext);
Map<String, Object> sourceProperties = getProperties("source");
if ("kamelet".equals(in)) {
sourceProperties = kameletProperties(sourceEndpoint, sourceProperties);
} else {
sourceProperties.putAll(sourceUriProperties);
}
context = context.replaceFirst("\\{\\{ \\.SourceProperties }}\n", asEndpointProperties(sourceProperties));
Map<String, Object> sinkProperties = getProperties("sink");
if ("kamelet".equals(out)) {
sinkProperties = kameletProperties(sinkEndpoint, sinkProperties);
} else {
sinkProperties.putAll(sinkUriProperties);
}
context = context.replaceFirst("\\{\\{ \\.SinkProperties }}\n", asEndpointProperties(sinkProperties));
return context;
}
public int dumpPipe(String pipe) throws Exception {
switch (output) {
case "file":
if (file.endsWith(".yaml")) {
IOHelper.writeText(pipe, new FileOutputStream(file, false));
} else if (file.endsWith(".json")) {
IOHelper.writeText(Jsoner.serialize(YamlHelper.yaml().loadAs(pipe, Map.class)),
new FileOutputStream(file, false));
} else {
IOHelper.writeText(pipe, new FileOutputStream(file + ".yaml", false));
}
break;
case "yaml":
printer().println(pipe);
break;
case "json":
printer().println(JSonHelper.prettyPrint(Jsoner.serialize(YamlHelper.yaml().loadAs(pipe, Map.class)), 2)
.replaceAll("\\\\/", "/"));
break;
default:
printer().printf("Unsupported output format '%s' (supported: file, yaml, json)%n", output);
return -1;
}
return 0;
}
/**
* Creates YAML snippet representing the error handler parameters section.
*
* @param props the properties to set as error handler parameters.
*/
private String asErrorHandlerParameters(Map<String, Object> props) {
if (props.isEmpty()) {
return "parameters: {}";
}
StringBuilder sb = new StringBuilder();
sb.append("parameters:\n");
for (Map.Entry<String, Object> propertyEntry : props.entrySet()) {
sb.append(" ").append(propertyEntry.getKey()).append(": ").append(propertyEntry.getValue()).append("\n");
}
return sb.toString().trim();
}
/**
* Creates YAML snippet representing the endpoint properties section.
*
* @param props the properties to set as endpoint properties.
* @return
*/
private String asEndpointProperties(Map<String, Object> props) {
return asEndpointProperties(props, 0);
}
/**
* Creates YAML snippet representing the endpoint properties section.
*
* @param props the properties to set as endpoint properties.
* @param additionalIndent optional number of additional spaces used as indentation.
* @return
*/
private String asEndpointProperties(Map<String, Object> props, int additionalIndent) {
StringBuilder sb = new StringBuilder();
if (props.isEmpty()) {
// create a dummy placeholder, so it is easier to add new properties manually
return sb.append("#properties:\n ").append(" ".repeat(additionalIndent)).append("#key: \"value\"").toString();
}
sb.append("properties:\n");
for (Map.Entry<String, Object> propertyEntry : props.entrySet()) {
sb.append(" ").append(" ".repeat(additionalIndent)).append(propertyEntry.getKey()).append(": ")
.append(propertyEntry.getValue()).append("\n");
}
return sb.toString().trim();
}
/**
* Extracts properties from given property arguments. Filter properties by given prefix. This way each component in
* pipe (source, sink, errorHandler, step[1-n]) can have its individual properties.
*
* @param keyPrefix
* @return
*/
private Map<String, Object> getProperties(String keyPrefix) {
Map<String, Object> props = new HashMap<>();
if (properties != null) {
for (String propertyExpression : properties) {
if (propertyExpression.startsWith(keyPrefix + ".")) {
String[] keyValue = propertyExpression.split("=", 2);
if (keyValue.length != 2) {
printer().printf(
"property '%s' does not follow format [source|sink|error-handler|step-<n>].<key>=<value>%n",
propertyExpression);
continue;
}
props.put(keyValue[0].substring(keyPrefix.length() + 1), keyValue[1]);
}
}
}
return props;
}
/**
* Get required properties from Kamelet specification and add those to the given user properties if not already set.
* In case a required property is not present in the provided user properties the value is either set to the example
* coming from the Kamelet specification or to a placeholder value for users to fill in manually. Property values do
* already have quotes when the type is String.
*
* @param kamelet
* @return
* @throws Exception
*/
protected Map<String, Object> kameletProperties(String kamelet, Map<String, Object> userProperties) throws Exception {
Map<String, Object> endpointProperties = new HashMap<>();
InputStream is;
String loc;
Resource res;
// try local disk first before GitHub
ResourceResolver resolver = new DefaultResourceResolvers.FileResolver();
try {
res = resolver.resolve("file:" + kamelet + ".kamelet.yaml");
} finally {
resolver.close();
}
if (res.exists()) {
is = res.getInputStream();
loc = res.getLocation();
} else {
resolver = new GitHubResourceResolver();
try {
res = resolver.resolve(
"github:apache:camel-kamelets:main:kamelets/" + kamelet + ".kamelet.yaml");
} finally {
resolver.close();
}
loc = res.getLocation();
URL u = new URL(loc);
is = u.openStream();
}
if (is != null) {
try {
LoadSettings local = LoadSettings.builder().setLabel(loc).build();
final StreamReader reader = new StreamReader(local, new YamlUnicodeReader(is));
final Parser parser = new ParserImpl(local, reader);
final Composer composer = new Composer(local, parser);
Node root = composer.getSingleNode().orElse(null);
if (root != null) {
Set<String> required = asStringSet(nodeAt(root, "/spec/definition/required"));
if (required != null && !required.isEmpty()) {
for (String req : required) {
if (!userProperties.containsKey(req)) {
String type = asText(nodeAt(root, "/spec/definition/properties/" + req + "/type"));
String example = asText(nodeAt(root, "/spec/definition/properties/" + req + "/example"));
StringBuilder vb = new StringBuilder();
if (example != null) {
if ("string".equals(type)) {
vb.append("\"");
}
vb.append(example);
if ("string".equals(type)) {
vb.append("\"");
}
} else {
vb.append("\"value\"");
}
endpointProperties.put(req, vb.toString());
}
}
}
}
IOHelper.close(is);
} catch (Exception e) {
System.err.println("Error parsing Kamelet: " + loc + " due to: " + e.getMessage());
}
} else {
System.err.println("Kamelet not found on github: " + kamelet);
}
endpointProperties.putAll(userProperties);
return endpointProperties;
}
static class FileConsumer extends ParameterConsumer<Bind> {
@Override
protected void doConsumeParameters(Stack<String> args, Bind cmd) {
cmd.file = args.pop();
}
}
public void setFile(String file) {
this.file = file;
}
public void setSource(String source) {
this.source = source;
}
public void setSink(String sink) {
this.sink = sink;
}
public void setSteps(String[] steps) {
this.steps = steps;
}
public void setProperties(String[] properties) {
this.properties = properties;
}
public void setErrorHandler(String errorHandler) {
this.errorHandler = errorHandler;
}
public void setOutput(String output) {
this.output = output;
}
}