/
BaseMainSupport.java
1365 lines (1241 loc) · 64.3 KB
/
BaseMainSupport.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.apache.camel.CamelContext;
import org.apache.camel.Component;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.NoSuchLanguageException;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.StartupStep;
import org.apache.camel.health.HealthCheck;
import org.apache.camel.health.HealthCheckConfiguration;
import org.apache.camel.health.HealthCheckRegistry;
import org.apache.camel.health.HealthCheckRepository;
import org.apache.camel.saga.CamelSagaService;
import org.apache.camel.spi.CamelBeanPostProcessor;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.Language;
import org.apache.camel.spi.PropertiesComponent;
import org.apache.camel.spi.RouteTemplateParameterSource;
import org.apache.camel.spi.StartupStepRecorder;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.LifecycleStrategySupport;
import org.apache.camel.support.PropertyBindingSupport;
import org.apache.camel.support.ResourceHelper;
import org.apache.camel.support.service.BaseService;
import org.apache.camel.support.startup.LoggingStartupStepRecorder;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.OrderedProperties;
import org.apache.camel.util.PropertiesHelper;
import org.apache.camel.util.SensitiveUtils;
import org.apache.camel.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.camel.main.MainHelper.computeProperties;
import static org.apache.camel.main.MainHelper.optionKey;
import static org.apache.camel.main.MainHelper.setPropertiesOnTarget;
import static org.apache.camel.main.MainHelper.validateOptionAndValue;
import static org.apache.camel.support.ObjectHelper.invokeMethod;
import static org.apache.camel.util.ReflectionHelper.findMethod;
import static org.apache.camel.util.StringHelper.matches;
/**
* Base class for main implementations to allow bootstrapping Camel in standalone mode.
*/
public abstract class BaseMainSupport extends BaseService {
public static final String DEFAULT_PROPERTY_PLACEHOLDER_LOCATION = "classpath:application.properties;optional=true";
public static final String INITIAL_PROPERTIES_LOCATION = "camel.main.initial-properties-location";
public static final String OVERRIDE_PROPERTIES_LOCATION = "camel.main.override-properties-location";
public static final String PROPERTY_PLACEHOLDER_LOCATION = "camel.main.property-placeholder-location";
private static final Logger LOG = LoggerFactory.getLogger(BaseMainSupport.class);
protected final List<MainListener> listeners = new ArrayList<>();
protected volatile CamelContext camelContext;
protected MainConfigurationProperties mainConfigurationProperties = new MainConfigurationProperties();
protected Properties wildcardProperties = new OrderedProperties();
protected RoutesCollector routesCollector = new DefaultRoutesCollector();
protected String propertyPlaceholderLocations;
protected String defaultPropertyPlaceholderLocation = DEFAULT_PROPERTY_PLACEHOLDER_LOCATION;
protected Properties initialProperties;
protected Properties overrideProperties;
private final MainHelper helper;
protected BaseMainSupport() {
helper = new MainHelper();
}
protected BaseMainSupport(CamelContext camelContext) {
this.camelContext = camelContext;
helper = new MainHelper();
}
private static CamelSagaService resolveLraSagaService(CamelContext camelContext) throws Exception {
// lookup in service registry first
Set<CamelSagaService> set = camelContext.getRegistry().findByType(CamelSagaService.class);
if (set.size() == 1) {
return set.iterator().next();
}
CamelSagaService answer = camelContext.adapt(ExtendedCamelContext.class).getBootstrapFactoryFinder()
.newInstance("lra-saga-service", CamelSagaService.class)
.orElseThrow(() -> new IllegalArgumentException(
"Cannot find LRASagaService on classpath. "
+ "Add camel-lra to classpath."));
// add as service so its discover by saga eip
camelContext.addService(answer, true, false);
return answer;
}
/**
* To configure options on Camel Main.
*/
public MainConfigurationProperties configure() {
return mainConfigurationProperties;
}
public RoutesCollector getRoutesCollector() {
return routesCollector;
}
/**
* To use a custom {@link RoutesCollector}.
*/
public void setRoutesCollector(RoutesCollector routesCollector) {
this.routesCollector = routesCollector;
}
public String getPropertyPlaceholderLocations() {
return propertyPlaceholderLocations;
}
/**
* A list of locations to add for loading properties. You can use comma to separate multiple locations.
*/
public void setPropertyPlaceholderLocations(String location) {
this.propertyPlaceholderLocations = location;
}
public String getDefaultPropertyPlaceholderLocation() {
return defaultPropertyPlaceholderLocation;
}
/**
* Set the default location for application properties if no locations have been set. If the value is set to "false"
* or empty, the default location is not taken into account.
* <p/>
* Default value is "classpath:application.properties;optional=true".
*/
public void setDefaultPropertyPlaceholderLocation(String defaultPropertyPlaceholderLocation) {
this.defaultPropertyPlaceholderLocation = defaultPropertyPlaceholderLocation;
}
@Deprecated
public boolean isAutoConfigurationEnabled() {
return mainConfigurationProperties.isAutoConfigurationEnabled();
}
/**
* Whether auto-configuration of components/dataformats/languages is enabled or not. When enabled the configuration
* parameters are loaded from the properties component and configured as defaults (similar to spring-boot
* auto-configuration). You can prefix the parameters in the properties file with: -
* camel.component.name.option1=value1 - camel.component.name.option2=value2 - camel.dataformat.name.option1=value1
* - camel.dataformat.name.option2=value2 - camel.language.name.option1=value1 - camel.language.name.option2=value2
* Where name is the name of the component, dataformat or language such as seda,direct,jaxb.
* <p/>
* The auto-configuration also works for any options on components that is a complex type (not standard Java type)
* and there has been an explicit single bean instance registered to the Camel registry via the
* {@link org.apache.camel.spi.Registry#bind(String, Object)} method or by using the
* {@link org.apache.camel.BindToRegistry} annotation style.
* <p/>
* This option is default enabled.
*
* @deprecated use {@link #configure()}
*/
@Deprecated
public void setAutoConfigurationEnabled(boolean autoConfigurationEnabled) {
mainConfigurationProperties.setAutoConfigurationEnabled(autoConfigurationEnabled);
}
public Properties getInitialProperties() {
return initialProperties;
}
/**
* Sets initial properties for the properties component, which will be used before any locations are resolved.
*/
public void setInitialProperties(Properties initialProperties) {
this.initialProperties = initialProperties;
}
/**
* Sets initial properties for the properties component, which will be used before any locations are resolved.
*/
public void setInitialProperties(Map<String, Object> initialProperties) {
this.initialProperties = new OrderedProperties();
this.initialProperties.putAll(initialProperties);
}
/**
* Adds a property (initial) for the properties component, which will be used before any locations are resolved.
*
* @param key the property key
* @param value the property value
* @see #addInitialProperty(String, String)
* @see #addOverrideProperty(String, String)
*/
public void addProperty(String key, String value) {
addInitialProperty(key, value);
}
/**
* Adds a initial property for the properties component, which will be used before any locations are resolved.
*
* @param key the property key
* @param value the property value
*/
public void addInitialProperty(String key, String value) {
if (initialProperties == null) {
initialProperties = new OrderedProperties();
}
initialProperties.setProperty(key, value);
}
public Properties getOverrideProperties() {
return overrideProperties;
}
/**
* Sets a special list of override properties that take precedence and will use first, if a property exist.
*/
public void setOverrideProperties(Properties overrideProperties) {
this.overrideProperties = overrideProperties;
}
/**
* Sets a special list of override properties that take precedence and will use first, if a property exist.
*/
public void setOverrideProperties(Map<String, Object> initialProperties) {
this.overrideProperties = new OrderedProperties();
this.overrideProperties.putAll(initialProperties);
}
/**
* Adds an override property that take precedence and will use first, if a property exist.
*
* @param key the property key
* @param value the property value
*/
public void addOverrideProperty(String key, String value) {
if (overrideProperties == null) {
overrideProperties = new OrderedProperties();
}
overrideProperties.setProperty(key, value);
}
public CamelContext getCamelContext() {
return camelContext;
}
/**
* Adds a {@link MainListener} to receive callbacks when the main is started or stopping
*
* @param listener the listener
*/
public void addMainListener(MainListener listener) {
listeners.add(listener);
}
/**
* Removes the {@link MainListener}
*
* @param listener the listener
*/
public void removeMainListener(MainListener listener) {
listeners.remove(listener);
}
protected void loadConfigurations(CamelContext camelContext) throws Exception {
// lets use Camel's bean post processor on any existing configuration classes
// so the instance has some support for dependency injection
CamelBeanPostProcessor postProcessor = camelContext.adapt(ExtendedCamelContext.class).getBeanPostProcessor();
for (Object configuration : mainConfigurationProperties.getConfigurations()) {
postProcessor.postProcessBeforeInitialization(configuration, configuration.getClass().getName());
postProcessor.postProcessAfterInitialization(configuration, configuration.getClass().getName());
}
if (mainConfigurationProperties.getConfigurationClasses() != null) {
String[] configClasses = mainConfigurationProperties.getConfigurationClasses().split(",");
for (String configClass : configClasses) {
Class<?> configClazz = camelContext.getClassResolver().resolveClass(configClass);
// lets use Camel's injector so the class has some support for dependency injection
Object config = camelContext.getInjector().newInstance(configClazz);
mainConfigurationProperties.addConfiguration(config);
}
}
for (Object config : mainConfigurationProperties.getConfigurations()) {
// invoke configure method if exists
Method method = findMethod(config.getClass(), "configure");
if (method != null) {
LOG.info("Calling configure method on configuration class: {}", config.getClass().getName());
invokeMethod(method, config);
} else {
Object arg = camelContext;
method = findMethod(config.getClass(), "configure", CamelContext.class);
if (method == null) {
method = findMethod(config.getClass(), "configure", Main.class);
arg = this;
}
if (method != null) {
LOG.info("Calling configure method on configuration class: {}", config.getClass().getName());
invokeMethod(method, config, arg);
}
}
}
}
protected void configurePropertiesService(CamelContext camelContext) throws Exception {
PropertiesComponent pc = camelContext.getPropertiesComponent();
if (pc.getLocations().isEmpty()) {
String locations = propertyPlaceholderLocations;
if (locations == null) {
locations
= helper.lookupPropertyFromSysOrEnv(PROPERTY_PLACEHOLDER_LOCATION)
.orElse(defaultPropertyPlaceholderLocation);
}
if (locations != null) {
locations = locations.trim();
}
if (!Objects.equals(locations, "false")) {
pc.addLocation(locations);
if (DEFAULT_PROPERTY_PLACEHOLDER_LOCATION.equals(locations)) {
LOG.debug("Using properties from: {}", locations);
} else {
// if not default location then log at INFO
LOG.info("Using properties from: {}", locations);
}
}
}
Properties ip = initialProperties;
if (ip == null || ip.isEmpty()) {
Optional<String> location = helper.lookupPropertyFromSysOrEnv(INITIAL_PROPERTIES_LOCATION);
if (location.isPresent()) {
try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, location.get())) {
ip = new Properties();
ip.load(is);
}
}
}
if (ip != null) {
pc.setInitialProperties(ip);
}
Properties op = overrideProperties;
if (op == null || op.isEmpty()) {
Optional<String> location = helper.lookupPropertyFromSysOrEnv(OVERRIDE_PROPERTIES_LOCATION);
if (location.isPresent()) {
try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, location.get())) {
op = new Properties();
op.load(is);
}
}
}
if (op != null) {
pc.setOverrideProperties(op);
}
}
protected void configureLifecycle(CamelContext camelContext) throws Exception {
}
protected void autoconfigure(CamelContext camelContext) throws Exception {
// gathers the properties (key=value) that was auto-configured
final Map<String, String> autoConfiguredProperties = new LinkedHashMap<>();
// need to eager allow to auto-configure properties component
if (mainConfigurationProperties.isAutoConfigurationEnabled()) {
autoConfigurationFailFast(camelContext, autoConfiguredProperties);
autoConfigurationPropertiesComponent(camelContext, autoConfiguredProperties);
autoConfigurationMainConfiguration(camelContext, mainConfigurationProperties, autoConfiguredProperties);
}
// configure from main configuration properties
doConfigureCamelContextFromMainConfiguration(camelContext, mainConfigurationProperties, autoConfiguredProperties);
// try to load configuration classes
loadConfigurations(camelContext);
if (mainConfigurationProperties.isAutoConfigurationEnabled()) {
autoConfigurationFromProperties(camelContext, autoConfiguredProperties);
autowireWildcardProperties(camelContext);
}
// tracing may be enabled by some other property (i.e. camel.context.tracer.exchange-formatter.show-headers)
if (camelContext.isTracing() && !mainConfigurationProperties.isTracing()) {
camelContext.setTracing(Boolean.FALSE);
}
// log summary of configurations
if (mainConfigurationProperties.isAutoConfigurationLogSummary() && !autoConfiguredProperties.isEmpty()) {
LOG.info("Auto-configuration summary");
autoConfiguredProperties.forEach((k, v) -> {
if (SensitiveUtils.containsSensitive(k)) {
LOG.info(" {}=xxxxxx", k);
} else {
LOG.info(" {}={}", k, v);
}
});
}
// we are now done with the main helper during bootstrap
helper.bootstrapDone();
}
protected void configureStartupRecorder(CamelContext camelContext) {
// we need to load these configurations early as they control the startup recorder when using camel-jfr
// and we want to start jfr recording as early as possible to also capture details during bootstrapping Camel
// load properties
Properties prop = camelContext.getPropertiesComponent().loadProperties(name -> name.startsWith("camel."));
Object value = prop.remove("camel.main.startupRecorder");
if (value == null) {
value = prop.remove("camel.main.startup-recorder");
}
if (value != null) {
mainConfigurationProperties.setStartupRecorder(value.toString());
}
value = prop.remove("camel.main.startupRecorderRecording");
if (value == null) {
value = prop.remove("camel.main.startup-recorder-recording");
}
if (value != null) {
mainConfigurationProperties.setStartupRecorderRecording("true".equalsIgnoreCase(value.toString()));
}
value = prop.remove("camel.main.startupRecorderProfile");
if (value == null) {
value = prop.remove("camel.main.startup-recorder-profile");
}
if (value != null) {
mainConfigurationProperties.setStartupRecorderProfile(
CamelContextHelper.parseText(camelContext, value.toString()));
}
value = prop.remove("camel.main.startupRecorderDuration");
if (value == null) {
value = prop.remove("camel.main.startup-recorder-duration");
}
if (value != null) {
mainConfigurationProperties.setStartupRecorderDuration(Long.parseLong(value.toString()));
}
value = prop.remove("camel.main.startupRecorderMaxDepth");
if (value == null) {
value = prop.remove("camel.main.startup-recorder-max-depth");
}
if (value != null) {
mainConfigurationProperties.setStartupRecorderMaxDepth(Integer.parseInt(value.toString()));
}
if ("off".equals(mainConfigurationProperties.getStartupRecorder())
|| "false".equals(mainConfigurationProperties.getStartupRecorder())) {
camelContext.adapt(ExtendedCamelContext.class).getStartupStepRecorder().setEnabled(false);
} else if ("logging".equals(mainConfigurationProperties.getStartupRecorder())) {
camelContext.adapt(ExtendedCamelContext.class).setStartupStepRecorder(new LoggingStartupStepRecorder());
} else if ("jfr".equals(mainConfigurationProperties.getStartupRecorder())
|| "java-flight-recorder".equals(mainConfigurationProperties.getStartupRecorder())
|| mainConfigurationProperties.getStartupRecorder() == null) {
// try to auto discover camel-jfr to use
StartupStepRecorder fr = camelContext.adapt(ExtendedCamelContext.class).getBootstrapFactoryFinder()
.newInstance(StartupStepRecorder.FACTORY, StartupStepRecorder.class).orElse(null);
if (fr != null) {
LOG.debug("Discovered startup recorder: {} from classpath", fr);
fr.setRecording(mainConfigurationProperties.isStartupRecorderRecording());
fr.setStartupRecorderDuration(mainConfigurationProperties.getStartupRecorderDuration());
fr.setRecordingProfile(mainConfigurationProperties.getStartupRecorderProfile());
fr.setMaxDepth(mainConfigurationProperties.getStartupRecorderMaxDepth());
camelContext.adapt(ExtendedCamelContext.class).setStartupStepRecorder(fr);
}
}
}
protected void configureRoutes(CamelContext camelContext) throws Exception {
// then configure and add the routes
RoutesConfigurer configurer = new RoutesConfigurer();
if (mainConfigurationProperties.isRoutesCollectorEnabled()) {
configurer.setRoutesCollector(routesCollector);
}
configurer.setBeanPostProcessor(camelContext.adapt(ExtendedCamelContext.class).getBeanPostProcessor());
configurer.setRoutesBuilders(mainConfigurationProperties.getRoutesBuilders());
configurer.setRoutesBuilderClasses(mainConfigurationProperties.getRoutesBuilderClasses());
configurer.setPackageScanRouteBuilders(mainConfigurationProperties.getPackageScanRouteBuilders());
configurer.setJavaRoutesExcludePattern(mainConfigurationProperties.getJavaRoutesExcludePattern());
configurer.setJavaRoutesIncludePattern(mainConfigurationProperties.getJavaRoutesIncludePattern());
configurer.setRoutesExcludePattern(mainConfigurationProperties.getRoutesExcludePattern());
configurer.setRoutesIncludePattern(mainConfigurationProperties.getRoutesIncludePattern());
configurer.configureRoutes(camelContext);
}
protected void postProcessCamelContext(CamelContext camelContext) throws Exception {
// setup properties
configurePropertiesService(camelContext);
// setup startup recorder before building context
configureStartupRecorder(camelContext);
// ensure camel is initialized
camelContext.build();
for (MainListener listener : listeners) {
listener.beforeInitialize(this);
}
// allow to do configuration before its started
for (MainListener listener : listeners) {
listener.beforeConfigure(this);
}
// we want to capture startup events for import tasks during main bootstrap
StartupStepRecorder recorder = camelContext.adapt(ExtendedCamelContext.class).getStartupStepRecorder();
StartupStep step = recorder.beginStep(BaseMainSupport.class, "autoconfigure", "Auto Configure");
autoconfigure(camelContext);
recorder.endStep(step);
configureLifecycle(camelContext);
step = recorder.beginStep(BaseMainSupport.class, "configureRoutes", "Collect Routes");
configureRoutes(camelContext);
recorder.endStep(step);
// allow to do configuration before its started
for (MainListener listener : listeners) {
listener.afterConfigure(this);
listener.configure(camelContext);
}
}
protected void autoConfigurationFailFast(CamelContext camelContext, Map<String, String> autoConfiguredProperties)
throws Exception {
// load properties
Properties prop = camelContext.getPropertiesComponent().loadProperties(name -> name.startsWith("camel."));
LOG.debug("Properties from Camel properties component:");
for (String key : prop.stringPropertyNames()) {
LOG.debug(" {}={}", key, prop.getProperty(key));
}
// special for environment-variable-enabled as we need to know this early before we set all the other options
Object envEnabled = prop.remove("camel.main.autoConfigurationEnvironmentVariablesEnabled");
if (envEnabled == null) {
envEnabled = prop.remove("camel.main.auto-configuration-environment-variables-enabled");
if (envEnabled != null) {
mainConfigurationProperties.setAutoConfigurationEnvironmentVariablesEnabled(
CamelContextHelper.parseBoolean(camelContext, envEnabled.toString()));
autoConfiguredProperties.put("camel.main.auto-configuration-environment-variables-enabled",
envEnabled.toString());
}
}
// special for system-properties-enabled as we need to know this early before we set all the other options
Object jvmEnabled = prop.remove("camel.main.autoConfigurationSystemPropertiesEnabled");
if (jvmEnabled == null) {
jvmEnabled = prop.remove("camel.main.auto-configuration-system-properties-enabled");
if (jvmEnabled != null) {
mainConfigurationProperties.setAutoConfigurationSystemPropertiesEnabled(
CamelContextHelper.parseBoolean(camelContext, jvmEnabled.toString()));
autoConfiguredProperties.put("camel.main.auto-configuration-system-properties-enabled",
jvmEnabled.toString());
}
}
// load properties from ENV (override existing)
Properties propENV = null;
if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) {
propENV = helper.loadEnvironmentVariablesAsProperties(new String[] { "camel.main." });
if (!propENV.isEmpty()) {
prop.putAll(propENV);
LOG.debug("Properties from OS environment variables:");
for (String key : propENV.stringPropertyNames()) {
LOG.debug(" {}={}", key, propENV.getProperty(key));
}
}
}
// load properties from JVM (override existing)
Properties propJVM = null;
if (mainConfigurationProperties.isAutoConfigurationSystemPropertiesEnabled()) {
propJVM = helper.loadJvmSystemPropertiesAsProperties(new String[] { "camel.main." });
if (!propJVM.isEmpty()) {
prop.putAll(propJVM);
LOG.debug("Properties from JVM system properties:");
for (String key : propJVM.stringPropertyNames()) {
LOG.debug(" {}={}", key, propJVM.getProperty(key));
}
}
}
// special for fail-fast as we need to know this early before we set all the other options
Object failFast = propENV != null ? propENV.remove("camel.main.autoconfigurationfailfast") : null;
if (propJVM != null) {
Object val = propJVM.remove("camel.main.autoconfigurationfailfast");
if (val != null) {
failFast = val;
}
}
if (failFast != null) {
mainConfigurationProperties
.setAutoConfigurationFailFast(CamelContextHelper.parseBoolean(camelContext, failFast.toString()));
} else {
failFast = prop.remove("camel.main.autoConfigurationFailFast");
if (failFast == null) {
failFast = prop.remove("camel.main.auto-configuration-fail-fast");
}
if (failFast != null) {
mainConfigurationProperties
.setAutoConfigurationFailFast(CamelContextHelper.parseBoolean(camelContext, failFast.toString()));
autoConfiguredProperties.put("camel.main.auto-configuration-fail-fast", failFast.toString());
}
}
}
/**
* Configures CamelContext from the {@link MainConfigurationProperties} properties.
*/
protected void doConfigureCamelContextFromMainConfiguration(
CamelContext camelContext, MainConfigurationProperties config,
Map<String, String> autoConfiguredProperties)
throws Exception {
if (config.getFileConfigurations() != null) {
String[] locs = config.getFileConfigurations().split(",");
for (String loc : locs) {
String path = FileUtil.onlyPath(loc);
if (path != null) {
String pattern = loc.length() > path.length() ? loc.substring(path.length() + 1) : null;
File[] files = new File(path).listFiles(f -> matches(pattern, f.getName()));
if (files != null) {
for (File file : files) {
Properties props = new Properties();
try (FileInputStream is = new FileInputStream(file)) {
props.load(is);
}
if (!props.isEmpty()) {
if (overrideProperties == null) {
// setup override properties on properties component
overrideProperties = new Properties();
PropertiesComponent pc = camelContext.getPropertiesComponent();
pc.setOverrideProperties(overrideProperties);
}
LOG.info("Loaded additional {} properties from file: {}", props.size(), file);
overrideProperties.putAll(props);
}
}
}
}
}
}
// configure the common/default options
DefaultConfigurationConfigurer.configure(camelContext, config);
// lookup and configure SPI beans
DefaultConfigurationConfigurer.afterConfigure(camelContext);
// now configure context/hystrix/resilience4j/rest with additional properties
Properties prop = camelContext.getPropertiesComponent().loadProperties(name -> name.startsWith("camel."));
// load properties from ENV (override existing)
if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) {
Properties propENV = helper.loadEnvironmentVariablesAsProperties(new String[] { "camel.component.properties." });
if (!propENV.isEmpty()) {
prop.putAll(propENV);
LOG.debug("Properties from OS environment variables:");
for (String key : propENV.stringPropertyNames()) {
LOG.debug(" {}={}", key, propENV.getProperty(key));
}
}
}
// load properties from JVM (override existing)
if (mainConfigurationProperties.isAutoConfigurationSystemPropertiesEnabled()) {
Properties propJVM = helper.loadJvmSystemPropertiesAsProperties(new String[] { "camel.component.properties." });
if (!propJVM.isEmpty()) {
prop.putAll(propJVM);
LOG.debug("Properties from JVM system properties:");
for (String key : propJVM.stringPropertyNames()) {
LOG.debug(" {}={}", key, propJVM.getProperty(key));
}
}
}
Map<String, Object> contextProperties = new LinkedHashMap<>();
Map<String, Object> hystrixProperties = new LinkedHashMap<>();
Map<String, Object> resilience4jProperties = new LinkedHashMap<>();
Map<String, Object> faultToleranceProperties = new LinkedHashMap<>();
Map<String, Object> restProperties = new LinkedHashMap<>();
Map<String, Object> threadPoolProperties = new LinkedHashMap<>();
Map<String, Object> healthProperties = new LinkedHashMap<>();
Map<String, Object> lraProperties = new LinkedHashMap<>();
Map<String, Object> routeTemplateProperties = new LinkedHashMap<>();
Map<String, Object> beansProperties = new LinkedHashMap<>();
for (String key : prop.stringPropertyNames()) {
if (key.startsWith("camel.context.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(14);
validateOptionAndValue(key, option, value);
contextProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.hystrix.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(14);
validateOptionAndValue(key, option, value);
hystrixProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.resilience4j.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(19);
validateOptionAndValue(key, option, value);
resilience4jProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.faulttolerance.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(21);
validateOptionAndValue(key, option, value);
faultToleranceProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.rest.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(11);
validateOptionAndValue(key, option, value);
restProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.threadpool.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(17);
validateOptionAndValue(key, option, value);
threadPoolProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.health.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(13);
validateOptionAndValue(key, option, value);
healthProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.lra.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(10);
validateOptionAndValue(key, option, value);
lraProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.route-template")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(20);
validateOptionAndValue(key, option, value);
routeTemplateProperties.put(optionKey(option), value);
} else if (key.startsWith("camel.beans.")) {
// grab the value
String value = prop.getProperty(key);
String option = key.substring(12);
validateOptionAndValue(key, option, value);
beansProperties.put(optionKey(option), value);
}
}
// create beans first as they may be used later
if (!beansProperties.isEmpty()) {
LOG.debug("Creating and binding beans to registry from loaded properties: {}", beansProperties.size());
bindBeansToRegistry(camelContext, beansProperties, "camel.beans.",
mainConfigurationProperties.isAutoConfigurationFailFast(),
mainConfigurationProperties.isAutoConfigurationLogSummary(), true, autoConfiguredProperties);
}
if (!contextProperties.isEmpty()) {
LOG.debug("Auto-configuring CamelContext from loaded properties: {}", contextProperties.size());
setPropertiesOnTarget(camelContext, camelContext, contextProperties, "camel.context.",
mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties);
}
if (!restProperties.isEmpty() || mainConfigurationProperties.hasRestConfiguration()) {
RestConfigurationProperties rest = mainConfigurationProperties.rest();
LOG.debug("Auto-configuring Rest DSL from loaded properties: {}", restProperties.size());
setPropertiesOnTarget(camelContext, rest, restProperties, "camel.rest.",
mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties);
camelContext.setRestConfiguration(rest);
}
if (!threadPoolProperties.isEmpty() || mainConfigurationProperties.hasThreadPoolConfiguration()) {
LOG.debug("Auto-configuring Thread Pool from loaded properties: {}", threadPoolProperties.size());
MainSupportModelConfigurer.setThreadPoolProperties(camelContext, mainConfigurationProperties, threadPoolProperties,
mainConfigurationProperties.isAutoConfigurationFailFast(), autoConfiguredProperties);
}
if (!healthProperties.isEmpty() || mainConfigurationProperties.hasHealthCheckConfiguration()) {
LOG.debug("Auto-configuring HealthCheck from loaded properties: {}", healthProperties.size());
setHealthCheckProperties(camelContext, healthProperties, mainConfigurationProperties.isAutoConfigurationFailFast(),
autoConfiguredProperties);
}
if (!routeTemplateProperties.isEmpty()) {
LOG.debug("Auto-configuring Route templates from loaded properties: {}", routeTemplateProperties.size());
setRouteTemplateProperties(camelContext, routeTemplateProperties,
mainConfigurationProperties.isAutoConfigurationFailFast(), autoConfiguredProperties);
}
if (!lraProperties.isEmpty() || mainConfigurationProperties.hasLraConfiguration()) {
LOG.debug("Auto-configuring Saga LRA from loaded properties: {}", lraProperties.size());
setLraCheckProperties(camelContext, lraProperties, mainConfigurationProperties.isAutoConfigurationFailFast(),
autoConfiguredProperties);
}
// configure which requires access to the model
MainSupportModelConfigurer.configureModelCamelContext(camelContext, mainConfigurationProperties,
autoConfiguredProperties, hystrixProperties, resilience4jProperties, faultToleranceProperties);
// log which options was not set
if (!beansProperties.isEmpty()) {
beansProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.beans.{}={}", k, v);
});
}
if (!contextProperties.isEmpty()) {
contextProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.context.{}={}", k, v);
});
}
if (!hystrixProperties.isEmpty()) {
hystrixProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.hystrix.{}={}", k, v);
});
}
if (!resilience4jProperties.isEmpty()) {
resilience4jProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.resilience4j.{}={}", k, v);
});
}
if (!faultToleranceProperties.isEmpty()) {
faultToleranceProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.faulttolerance.{}={}", k, v);
});
}
if (!restProperties.isEmpty()) {
restProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.rest.{}={}", k, v);
});
}
if (!threadPoolProperties.isEmpty()) {
threadPoolProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.threadpool.{}={}", k, v);
});
}
if (!healthProperties.isEmpty()) {
healthProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.health.{}={}", k, v);
});
}
if (!routeTemplateProperties.isEmpty()) {
routeTemplateProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.routetemplate.{}={}", k, v);
});
}
if (!lraProperties.isEmpty()) {
lraProperties.forEach((k, v) -> {
LOG.warn("Property not auto-configured: camel.lra.{}={}", k, v);
});
}
// and call after all properties are set
DefaultConfigurationConfigurer.afterPropertiesSet(camelContext);
}
private void setRouteTemplateProperties(
CamelContext camelContext, Map<String, Object> routeTemplateProperties,
boolean failIfNotSet, Map<String, String> autoConfiguredProperties)
throws Exception {
// store the route template parameters as a source and register it on the camel context
PropertiesRouteTemplateParametersSource source = new PropertiesRouteTemplateParametersSource();
for (Map.Entry<String, Object> entry : routeTemplateProperties.entrySet()) {
String id = StringHelper.between(entry.getKey(), "[", "]");
String key = StringHelper.after(entry.getKey(), "].");
source.addParameter(id, key, entry.getValue());
}
camelContext.getRegistry().bind("CamelMainRouteTemplateParametersSource", RouteTemplateParameterSource.class, source);
// lets sort by keys
Map<String, Object> sorted = new TreeMap<>(routeTemplateProperties);
sorted.forEach((k, v) -> {
autoConfiguredProperties.put("camel.route-template" + k, v.toString());
});
routeTemplateProperties.clear();
}
private void setHealthCheckProperties(
CamelContext camelContext, Map<String, Object> healthCheckProperties,
boolean failIfNotSet, Map<String, String> autoConfiguredProperties)
throws Exception {
HealthCheckRegistry hcr = camelContext.getExtension(HealthCheckRegistry.class);
if (hcr == null) {
LOG.warn("Cannot find HealthCheckRegistry from classpath. Add camel-health to classpath.");
return;
}
HealthConfigurationProperties health = mainConfigurationProperties.health();
// extract all config to know their parent ids so we can set the values afterwards
Map<String, Object> hcConfig = PropertiesHelper.extractProperties(healthCheckProperties, "config", false);
Map<String, HealthCheckConfigurationProperties> hcConfigs = new HashMap<>();
// build set of configuration objects
for (Map.Entry<String, Object> entry : hcConfig.entrySet()) {
String parent = StringHelper.between(entry.getKey(), "[", "]");
if (parent != null) {
HealthCheckConfigurationProperties hcp = hcConfigs.get(parent);
if (hcp == null) {
hcp = new HealthCheckConfigurationProperties();
hcConfigs.put(parent, hcp);
}
}
}
if (health.getConfig() != null) {
health.getConfig().putAll(hcConfigs);
} else {
health.setConfig(hcConfigs);
}
setPropertiesOnTarget(camelContext, health, healthCheckProperties, "camel.health.",
mainConfigurationProperties.isAutoConfigurationFailFast(), true, autoConfiguredProperties);
if (health.getEnabled() != null) {
hcr.setEnabled(health.getEnabled());
}
// context is enabled by default
if (hcr.isEnabled() && (!health.getConfig().containsKey("context") || health.getContextEnabled() != null)) {
HealthCheck hc = (HealthCheck) hcr.resolveById("context");
if (hc != null) {
if (health.getContextEnabled() != null) {
hc.getConfiguration().setEnabled(health.getContextEnabled());
}
hcr.register(hc);
}
}
// routes is enabled by default
if (hcr.isEnabled() && (!health.getConfig().containsKey("routes") || health.getRoutesEnabled() != null)) {
HealthCheckRepository hc = hcr.getRepository("routes").orElse((HealthCheckRepository) hcr.resolveById("routes"));
if (hc != null) {
if (health.getRoutesEnabled() != null) {
hc.setEnabled(health.getRoutesEnabled());
}
hcr.register(hc);
}
}
// registry is enabled by default
if (hcr.isEnabled() && (!health.getConfig().containsKey("registry") || health.getRegistryEnabled() != null)) {
hcr.getRepository("registry").ifPresent(h -> {
if (health.getRegistryEnabled() != null) {
h.setEnabled(health.getRegistryEnabled());
}
});
}
// configure health checks configurations
for (String id : health.getConfig().keySet()) {
HealthCheckConfiguration hcc = health.getConfig().get(id);
String parent = hcc.getParent();
// lookup health check by id
Object hc = hcr.getCheck(parent).orElse(null);
if (hc == null) {
hc = hcr.resolveById(parent);
if (hc == null) {
LOG.warn("Cannot resolve HealthCheck with id: " + parent + " from classpath.");
continue;
}
hcr.register(hc);
if (hc instanceof HealthCheck) {
((HealthCheck) hc).getConfiguration().setParent(hcc.getParent());
((HealthCheck) hc).getConfiguration().setEnabled(hcc.isEnabled());
((HealthCheck) hc).getConfiguration().setFailureThreshold(hcc.getFailureThreshold());
((HealthCheck) hc).getConfiguration().setInterval(hcc.getInterval());
} else if (hc instanceof HealthCheckRepository) {
((HealthCheckRepository) hc).setEnabled(hcc.isEnabled());
((HealthCheckRepository) hc).addConfiguration(id, hcc);
}
}
}
}
private void setLraCheckProperties(
CamelContext camelContext, Map<String, Object> lraProperties,
boolean failIfNotSet, Map<String, String> autoConfiguredProperties)
throws Exception {