-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
BaseMainSupport.java
2309 lines (2085 loc) · 111 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.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
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.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.camel.CamelConfiguration;
import org.apache.camel.CamelContext;
import org.apache.camel.Component;
import org.apache.camel.Configuration;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.NoSuchLanguageException;
import org.apache.camel.PropertiesLookupListener;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.Service;
import org.apache.camel.StartupStep;
import org.apache.camel.console.DevConsole;
import org.apache.camel.console.DevConsoleRegistry;
import org.apache.camel.health.HealthCheck;
import org.apache.camel.health.HealthCheckRegistry;
import org.apache.camel.health.HealthCheckRepository;
import org.apache.camel.impl.debugger.DefaultBacklogDebugger;
import org.apache.camel.impl.engine.DefaultCompileStrategy;
import org.apache.camel.impl.engine.DefaultRoutesLoader;
import org.apache.camel.saga.CamelSagaService;
import org.apache.camel.spi.AutowiredLifecycleStrategy;
import org.apache.camel.spi.BacklogDebugger;
import org.apache.camel.spi.BacklogTracer;
import org.apache.camel.spi.CamelBeanPostProcessor;
import org.apache.camel.spi.CamelEvent;
import org.apache.camel.spi.CamelMetricsService;
import org.apache.camel.spi.CamelTracingService;
import org.apache.camel.spi.CompileStrategy;
import org.apache.camel.spi.ContextReloadStrategy;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.Language;
import org.apache.camel.spi.LifecycleStrategy;
import org.apache.camel.spi.PackageScanClassResolver;
import org.apache.camel.spi.PeriodTaskScheduler;
import org.apache.camel.spi.PropertiesComponent;
import org.apache.camel.spi.Registry;
import org.apache.camel.spi.RouteTemplateParameterSource;
import org.apache.camel.spi.RoutesLoader;
import org.apache.camel.spi.StartupStepRecorder;
import org.apache.camel.spi.SupervisingRouteController;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.DefaultContextReloadStrategy;
import org.apache.camel.support.LifecycleStrategySupport;
import org.apache.camel.support.PluginHelper;
import org.apache.camel.support.PropertyBindingSupport;
import org.apache.camel.support.ResourceHelper;
import org.apache.camel.support.SimpleEventNotifierSupport;
import org.apache.camel.support.jsse.KeyManagersParameters;
import org.apache.camel.support.jsse.KeyStoreParameters;
import org.apache.camel.support.jsse.SSLContextParameters;
import org.apache.camel.support.jsse.SSLContextServerParameters;
import org.apache.camel.support.jsse.TrustManagersParameters;
import org.apache.camel.support.scan.PackageScanHelper;
import org.apache.camel.support.service.BaseService;
import org.apache.camel.support.startup.BacklogStartupStepRecorder;
import org.apache.camel.support.startup.LoggingStartupStepRecorder;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.OrderedLocationProperties;
import org.apache.camel.util.OrderedProperties;
import org.apache.camel.util.SensitiveUtils;
import org.apache.camel.util.StringHelper;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.vault.VaultConfiguration;
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.util.LocationHelper.locationSummary;
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 {
private static final Logger LOG = LoggerFactory.getLogger(BaseMainSupport.class);
protected final List<MainListener> listeners = new ArrayList<>();
protected volatile CamelContext camelContext;
protected final MainConfigurationProperties mainConfigurationProperties = new MainConfigurationProperties();
protected final OrderedLocationProperties wildcardProperties = new OrderedLocationProperties();
protected RoutesCollector routesCollector = new DefaultRoutesCollector();
protected String propertyPlaceholderLocations;
protected String defaultPropertyPlaceholderLocation = MainConstants.DEFAULT_PROPERTY_PLACEHOLDER_LOCATION;
protected Properties initialProperties;
protected Properties overrideProperties;
protected boolean standalone = true;
protected final MainHelper helper;
protected BaseMainSupport() {
this.helper = new MainHelper();
}
protected BaseMainSupport(CamelContext camelContext) {
this.camelContext = camelContext;
this.helper = new MainHelper();
}
/**
* 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;
}
public Properties getInitialProperties() {
if (initialProperties == null) {
initialProperties = new OrderedProperties();
}
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 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
*/
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 loadCustomBeans(CamelContext camelContext) throws Exception {
// auto-detect custom beans via base package scanning
String basePackage = camelContext.getCamelContextExtension().getBasePackageScan();
if (basePackage != null) {
PackageScanHelper.registerBeans(camelContext, Set.of(basePackage));
}
}
protected void loadConfigurations(CamelContext camelContext) throws Exception {
// auto-detect camel configurations via base package scanning
String basePackage = camelContext.getCamelContextExtension().getBasePackageScan();
if (basePackage != null) {
PackageScanClassResolver pscr = PluginHelper.getPackageScanClassResolver(camelContext);
Set<Class<?>> found1 = pscr.findImplementations(CamelConfiguration.class, basePackage);
Set<Class<?>> found2 = pscr.findAnnotated(Configuration.class, basePackage);
Set<Class<?>> found = new LinkedHashSet<>();
found.addAll(found1);
found.addAll(found2);
for (Class<?> clazz : found) {
// lets use Camel's injector so the class has some support for dependency injection
Object config = camelContext.getInjector().newInstance(clazz);
if (config instanceof CamelConfiguration cc) {
LOG.debug("Discovered CamelConfiguration class: {}", cc);
mainConfigurationProperties.addConfiguration(cc);
}
}
}
if (mainConfigurationProperties.getConfigurationClasses() != null) {
String[] configClasses = mainConfigurationProperties.getConfigurationClasses().split(",");
for (String configClass : configClasses) {
Class<CamelConfiguration> configClazz
= camelContext.getClassResolver().resolveClass(configClass, CamelConfiguration.class);
// skip main classes
boolean mainClass = false;
try {
configClazz.getDeclaredMethod("main", String[].class);
mainClass = true;
} catch (NoSuchMethodException e) {
// ignore
}
if (!mainClass) {
// let's use Camel's injector so the class has some support for dependency injection
CamelConfiguration config = camelContext.getInjector().newInstance(configClazz);
mainConfigurationProperties.addConfiguration(config);
}
}
}
// lets use Camel's bean post processor on any existing configuration classes
// so the instance has some support for dependency injection
CamelBeanPostProcessor postProcessor = PluginHelper.getBeanPostProcessor(camelContext);
// discover configurations from the registry
Set<CamelConfiguration> registryConfigurations = camelContext.getRegistry().findByType(CamelConfiguration.class);
for (CamelConfiguration configuration : registryConfigurations) {
postProcessor.postProcessBeforeInitialization(configuration, configuration.getClass().getName());
postProcessor.postProcessAfterInitialization(configuration, configuration.getClass().getName());
}
// prepare the directly configured instances (from registry should have been post processed already)
for (Object configuration : mainConfigurationProperties.getConfigurations()) {
postProcessor.postProcessBeforeInitialization(configuration, configuration.getClass().getName());
postProcessor.postProcessAfterInitialization(configuration, configuration.getClass().getName());
}
// invoke configure on configurations
for (CamelConfiguration config : mainConfigurationProperties.getConfigurations()) {
config.configure(camelContext);
}
// invoke configure on configurations that are from registry
for (CamelConfiguration config : registryConfigurations) {
config.configure(camelContext);
}
}
protected void configurePropertiesService(CamelContext camelContext) throws Exception {
PropertiesComponent pc = camelContext.getPropertiesComponent();
if (pc.getLocations().isEmpty()) {
String locations = propertyPlaceholderLocations;
if (locations == null) {
locations
= MainHelper.lookupPropertyFromSysOrEnv(MainConstants.PROPERTY_PLACEHOLDER_LOCATION)
.orElse(defaultPropertyPlaceholderLocation);
}
if (locations != null) {
locations = locations.trim();
}
if (!Objects.equals(locations, "false")) {
pc.addLocation(locations);
if (MainConstants.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);
}
}
}
final Properties ip = tryLoadProperties(initialProperties, MainConstants.INITIAL_PROPERTIES_LOCATION, camelContext);
if (ip != null) {
pc.setInitialProperties(ip);
}
final Properties op = tryLoadProperties(overrideProperties, MainConstants.OVERRIDE_PROPERTIES_LOCATION, camelContext);
if (op != null) {
pc.setOverrideProperties(op);
}
}
private Properties tryLoadProperties(
Properties initialProperties, String initialPropertiesLocation, CamelContext camelContext)
throws IOException {
Properties ip = initialProperties;
if (ip == null || ip.isEmpty()) {
Optional<String> location = MainHelper.lookupPropertyFromSysOrEnv(initialPropertiesLocation);
if (location.isPresent()) {
try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, location.get())) {
ip = new Properties();
ip.load(is);
}
}
}
return ip;
}
protected void configureLifecycle(CamelContext camelContext) throws Exception {
}
private void scheduleRefresh(CamelContext camelContext, String key, long period) throws Exception {
final Optional<Runnable> task = PluginHelper.getPeriodTaskResolver(camelContext)
.newInstance(key, Runnable.class);
if (task.isPresent()) {
Runnable r = task.get();
if (LOG.isDebugEnabled()) {
LOG.debug("Scheduling: {} (period: {})", r, TimeUtils.printDuration(period, false));
}
if (camelContext.hasService(ContextReloadStrategy.class) == null) {
// refresh is enabled then we need to automatically enable context-reload as well
ContextReloadStrategy reloader = new DefaultContextReloadStrategy();
camelContext.addService(reloader);
}
PeriodTaskScheduler scheduler = PluginHelper.getPeriodTaskScheduler(camelContext);
scheduler.schedulePeriodTask(r, period);
}
}
protected void autoconfigure(CamelContext camelContext) throws Exception {
// gathers the properties (key=value) that was auto-configured
final OrderedLocationProperties autoConfiguredProperties = new OrderedLocationProperties();
// configure the profile with pre-configured settings
ProfileConfigurer.configure(camelContext, mainConfigurationProperties.getProfile(), mainConfigurationProperties);
// need to eager allow to auto-configure properties component
if (mainConfigurationProperties.isAutoConfigurationEnabled()) {
autoConfigurationFailFast(camelContext, autoConfiguredProperties);
autoConfigurationPropertiesComponent(camelContext, autoConfiguredProperties);
autoConfigurationSingleOption(camelContext, autoConfiguredProperties, "camel.main.routesIncludePattern",
value -> {
mainConfigurationProperties.setRoutesIncludePattern(value);
return null;
});
if (mainConfigurationProperties.isModeline()) {
camelContext.setModeline(true);
}
// eager load properties from modeline by scanning DSL sources and gather properties for auto configuration
// also load other non-route related configuration (e.g., beans)
modelineRoutes(camelContext);
autoConfigurationMainConfiguration(camelContext, mainConfigurationProperties, autoConfiguredProperties);
}
// configure from main configuration properties
doConfigureCamelContextFromMainConfiguration(camelContext, mainConfigurationProperties, autoConfiguredProperties);
// try to load custom beans/configuration classes via package scanning
configurePackageScan(camelContext);
loadCustomBeans(camelContext);
loadConfigurations(camelContext);
if (mainConfigurationProperties.isAutoConfigurationEnabled()) {
autoConfigurationFromProperties(camelContext, autoConfiguredProperties);
autowireWildcardProperties(camelContext);
// register properties reloader so we can auto-update if updated
camelContext.addService(new MainPropertiesReload(this));
}
// log summary of configurations
if (mainConfigurationProperties.isAutoConfigurationLogSummary() && !autoConfiguredProperties.isEmpty()) {
logConfigurationSummary(autoConfiguredProperties);
}
// we are now done with the main helper during bootstrap
helper.bootstrapDone();
}
private static void logConfigurationSummary(OrderedLocationProperties autoConfiguredProperties) {
// first log variables
doLogConfigurationSummary(autoConfiguredProperties, "Variables summary", (k) -> k.startsWith("camel.variable."));
// then log standard options
doLogConfigurationSummary(autoConfiguredProperties, "Auto-configuration summary", null);
}
private static void doLogConfigurationSummary(
OrderedLocationProperties autoConfiguredProperties, String title, Predicate<String> filter) {
boolean header = false;
List<String> toRemove = new ArrayList<>();
for (var entry : autoConfiguredProperties.entrySet()) {
String k = entry.getKey().toString();
if (filter == null || filter.test(k)) {
Object v = entry.getValue();
String loc = locationSummary(autoConfiguredProperties, k);
// tone down logging noise for our own internal configurations
boolean debug = loc.contains("[camel-main]");
if (debug && !LOG.isDebugEnabled()) {
continue;
}
if (!header) {
LOG.info(title);
header = true;
}
sensitiveAwareLogging(k, v, loc, debug);
toRemove.add(k);
}
}
toRemove.forEach(autoConfiguredProperties::remove);
}
protected void configureStartupRecorder(CamelContext camelContext) {
ExtendedCamelContext ecc = camelContext.getCamelContextExtension();
// 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."),
MainHelper::optionKey);
Object value = prop.remove("camel.main.startupRecorder");
if (ObjectHelper.isNotEmpty(value)) {
mainConfigurationProperties.setStartupRecorder(value.toString());
}
value = prop.remove("camel.main.startupRecorderRecording");
if (ObjectHelper.isNotEmpty(value)) {
mainConfigurationProperties.setStartupRecorderRecording("true".equalsIgnoreCase(value.toString()));
}
value = prop.remove("camel.main.startupRecorderProfile");
if (ObjectHelper.isNotEmpty(value)) {
mainConfigurationProperties.setStartupRecorderProfile(
CamelContextHelper.parseText(camelContext, value.toString()));
}
value = prop.remove("camel.main.startupRecorderDuration");
if (ObjectHelper.isNotEmpty(value)) {
mainConfigurationProperties.setStartupRecorderDuration(Long.parseLong(value.toString()));
}
value = prop.remove("camel.main.startupRecorderMaxDepth");
if (ObjectHelper.isNotEmpty(value)) {
mainConfigurationProperties.setStartupRecorderMaxDepth(Integer.parseInt(value.toString()));
}
if ("off".equals(mainConfigurationProperties.getStartupRecorder())
|| "false".equals(mainConfigurationProperties.getStartupRecorder())) {
ecc.getStartupStepRecorder().setEnabled(false);
} else if ("logging".equals(mainConfigurationProperties.getStartupRecorder())) {
if (!(ecc.getStartupStepRecorder() instanceof LoggingStartupStepRecorder)) {
ecc.setStartupStepRecorder(new LoggingStartupStepRecorder());
}
} else if ("backlog".equals(mainConfigurationProperties.getStartupRecorder())) {
if (!(ecc.getStartupStepRecorder() instanceof BacklogStartupStepRecorder)) {
ecc.setStartupStepRecorder(new BacklogStartupStepRecorder());
}
} 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 = ecc.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.getCamelContextExtension().setStartupStepRecorder(fr);
}
}
}
protected void configurePackageScan(CamelContext camelContext) {
if (mainConfigurationProperties.isBasePackageScanEnabled()) {
// only set the base package if enabled
String base = mainConfigurationProperties.getBasePackageScan();
String current = camelContext.getCamelContextExtension().getBasePackageScan();
if (base != null && !base.equals(current)) {
camelContext.getCamelContextExtension().setBasePackageScan(base);
LOG.info("Classpath scanning enabled from base package: {}", base);
}
}
}
protected void configureRoutesLoader(CamelContext camelContext) {
// use main based routes loader
ExtendedCamelContext ecc = camelContext.getCamelContextExtension();
// need to configure compile work dir as its used from routes loader when it discovered code to dynamic compile
if (mainConfigurationProperties.getCompileWorkDir() != null) {
CompileStrategy cs = camelContext.getCamelContextExtension().getContextPlugin(CompileStrategy.class);
if (cs == null) {
cs = new DefaultCompileStrategy();
ecc.addContextPlugin(CompileStrategy.class, cs);
}
cs.setWorkDir(mainConfigurationProperties.getCompileWorkDir());
}
RoutesLoader loader = new DefaultRoutesLoader();
loader.setIgnoreLoadingError(mainConfigurationProperties.isRoutesCollectorIgnoreLoadingError());
ecc.addContextPlugin(RoutesLoader.class, loader);
}
protected void modelineRoutes(CamelContext camelContext) throws Exception {
// then configure and add the routes
RoutesConfigurer configurer = doCommonRouteConfiguration(camelContext);
configurer.configureModeline(camelContext);
}
protected void configureRoutes(CamelContext camelContext) throws Exception {
RoutesConfigurer configurer = doCommonRouteConfiguration(camelContext);
configurer.configureRoutes(camelContext);
}
private RoutesConfigurer doCommonRouteConfiguration(CamelContext camelContext) {
// then configure and add the routes
RoutesConfigurer configurer = new RoutesConfigurer();
routesCollector.setIgnoreLoadingError(mainConfigurationProperties.isRoutesCollectorIgnoreLoadingError());
if (mainConfigurationProperties.isRoutesCollectorEnabled()) {
configurer.setRoutesCollector(routesCollector);
configurer.setIgnoreLoadingError(mainConfigurationProperties.isRoutesCollectorIgnoreLoadingError());
}
configurer.setBeanPostProcessor(PluginHelper.getBeanPostProcessor(camelContext));
configurer.setRoutesBuilders(mainConfigurationProperties.getRoutesBuilders());
configurer.setRoutesBuilderClasses(mainConfigurationProperties.getRoutesBuilderClasses());
if (mainConfigurationProperties.isBasePackageScanEnabled()) {
// only set the base package if enabled
configurer.setBasePackageScan(mainConfigurationProperties.getBasePackageScan());
}
configurer.setJavaRoutesExcludePattern(mainConfigurationProperties.getJavaRoutesExcludePattern());
configurer.setJavaRoutesIncludePattern(mainConfigurationProperties.getJavaRoutesIncludePattern());
configurer.setRoutesExcludePattern(mainConfigurationProperties.getRoutesExcludePattern());
configurer.setRoutesIncludePattern(mainConfigurationProperties.getRoutesIncludePattern());
return configurer;
}
/**
* A specialized {@link LifecycleStrategy} that can handle autowiring of Camel components, dataformats, languages.
*/
protected LifecycleStrategy createLifecycleStrategy(CamelContext camelContext) {
return new MainAutowiredLifecycleStrategy(camelContext);
}
protected void postProcessCamelContext(CamelContext camelContext) throws Exception {
// gathers the properties (key=value) that was used as property placeholders during bootstrap
final OrderedLocationProperties propertyPlaceholders = new OrderedLocationProperties();
// use the main autowired lifecycle strategy instead of the default
camelContext.getLifecycleStrategies().removeIf(s -> s instanceof AutowiredLifecycleStrategy);
camelContext.addLifecycleStrategy(createLifecycleStrategy(camelContext));
// setup properties
configurePropertiesService(camelContext);
// register listener on properties component so we can capture them
PropertiesComponent pc = camelContext.getPropertiesComponent();
pc.addPropertiesLookupListener(new PropertyPlaceholderListener(propertyPlaceholders));
// setup startup recorder before building context
configureStartupRecorder(camelContext);
// setup package scan
configurePackageScan(camelContext);
// configure to use our main routes loader
configureRoutesLoader(camelContext);
// ensure camel context is build
camelContext.build();
for (MainListener listener : listeners) {
listener.beforeInitialize(this);
}
// allow doing custom configuration before camel is started
for (MainListener listener : listeners) {
listener.beforeConfigure(this);
}
// we want to capture startup events for import tasks during main bootstrap
StartupStepRecorder recorder = camelContext.getCamelContextExtension().getStartupStepRecorder();
StartupStep step;
if (standalone) {
step = recorder.beginStep(BaseMainSupport.class, "autoconfigure", "Auto Configure");
autoconfigure(camelContext);
recorder.endStep(step);
}
configureLifecycle(camelContext);
if (standalone) {
step = recorder.beginStep(BaseMainSupport.class, "configureRoutes", "Collect Routes");
configureRoutes(camelContext);
recorder.endStep(step);
}
// after the routes are read (org.apache.camel.spi.RoutesBuilderLoader did their work), we may have
// new classes defined, so main implementations may have to reconfigure the registry using newly
// available bean definitions
postProcessCamelRegistry(camelContext, mainConfigurationProperties);
// allow doing custom configuration before camel is started
for (MainListener listener : listeners) {
listener.afterConfigure(this);
}
// we want to log the property placeholder summary after routes has been started,
// but before camel context logs that it has been started, so we need to use an event listener
if (standalone && mainConfigurationProperties.isAutoConfigurationLogSummary()) {
camelContext.getManagementStrategy().addEventNotifier(new SimpleEventNotifierSupport() {
@Override
public boolean isEnabled(CamelEvent event) {
return event instanceof CamelEvent.CamelContextRoutesStartedEvent;
}
@Override
public void notify(CamelEvent event) throws Exception {
// log summary of configurations
if (!propertyPlaceholders.isEmpty()) {
boolean header = true;
for (var entry : propertyPlaceholders.entrySet()) {
String k = entry.getKey().toString();
Object v = entry.getValue();
Object dv = propertyPlaceholders.getDefaultValue(k);
// skip logging configurations that are using default-value
// or a kamelet that uses templateId as a parameter
boolean same = ObjectHelper.equal(v, dv);
boolean skip = "templateId".equals(k);
if (!same && !skip) {
if (header) {
LOG.info("Property-placeholders summary");
header = false;
}
String loc = locationSummary(propertyPlaceholders, k);
if (SensitiveUtils.containsSensitive(k)) {
LOG.info(" {} {}=xxxxxx", loc, k);
} else {
LOG.info(" {} {}={}", loc, k, v);
}
}
}
}
}
});
}
}
protected void autoConfigurationFailFast(CamelContext camelContext, OrderedLocationProperties autoConfiguredProperties)
throws Exception {
// load properties
OrderedLocationProperties prop = (OrderedLocationProperties) camelContext.getPropertiesComponent()
.loadProperties(name -> name.startsWith("camel."), MainHelper::optionKey);
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 (ObjectHelper.isNotEmpty(envEnabled)) {
mainConfigurationProperties.setAutoConfigurationEnvironmentVariablesEnabled(
CamelContextHelper.parseBoolean(camelContext, envEnabled.toString()));
String loc = prop.getLocation("camel.main.autoConfigurationEnvironmentVariablesEnabled");
autoConfiguredProperties.put(loc, "camel.main.autoConfigurationEnvironmentVariablesEnabled",
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 (ObjectHelper.isNotEmpty(jvmEnabled)) {
mainConfigurationProperties.setAutoConfigurationSystemPropertiesEnabled(
CamelContextHelper.parseBoolean(camelContext, jvmEnabled.toString()));
String loc = prop.getLocation("camel.main.autoConfigurationSystemPropertiesEnabled");
autoConfiguredProperties.put(loc, "camel.autoConfigurationSystemPropertiesEnabled",
jvmEnabled.toString());
}
// load properties from ENV (override existing)
Properties propENV = null;
if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) {
propENV = MainHelper.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 = MainHelper.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
String loc = "ENV";
Object failFast = propENV != null ? propENV.remove("camel.main.autoconfigurationfailfast") : null;
if (ObjectHelper.isNotEmpty(propJVM)) {
Object val = propJVM.remove("camel.main.autoconfigurationfailfast");
if (ObjectHelper.isNotEmpty(val)) {
loc = "SYS";
failFast = val;
}
}
if (ObjectHelper.isNotEmpty(failFast)) {
mainConfigurationProperties
.setAutoConfigurationFailFast(CamelContextHelper.parseBoolean(camelContext, failFast.toString()));
autoConfiguredProperties.put(loc, "camel.main.autoConfigurationFailFast", failFast.toString());
} else {
loc = prop.getLocation("camel.main.autoConfigurationFailFast");
failFast = prop.remove("camel.main.autoConfigurationFailFast");
if (ObjectHelper.isNotEmpty(failFast)) {
mainConfigurationProperties
.setAutoConfigurationFailFast(CamelContextHelper.parseBoolean(camelContext, failFast.toString()));
autoConfiguredProperties.put(loc, "camel.main.autoConfigurationFailFast", failFast.toString());
}
}
}
protected void autoConfigurationSingleOption(
CamelContext camelContext, OrderedLocationProperties autoConfiguredProperties,
String optionName, Function<String, Object> setter) {
String lowerOptionName = optionName.toLowerCase(Locale.US);
// load properties
OrderedLocationProperties prop = (OrderedLocationProperties) camelContext.getPropertiesComponent()
.loadProperties(name -> name.startsWith("camel."), MainHelper::optionKey);
LOG.debug("Properties from Camel properties component:");
for (String key : prop.stringPropertyNames()) {
LOG.debug(" {}={}", key, prop.getProperty(key));
}
// load properties from ENV (override existing)
Properties propENV = null;
if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) {
propENV = MainHelper.loadEnvironmentVariablesAsProperties(new String[] { "camel.main." });
if (!propENV.isEmpty()) {
prop.putAll("ENV", 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 = MainHelper.loadJvmSystemPropertiesAsProperties(new String[] { "camel.main." });
if (!propJVM.isEmpty()) {
prop.putAll("SYS", propJVM);
LOG.debug("Properties from JVM system properties:");
for (String key : propJVM.stringPropertyNames()) {
LOG.debug(" {}={}", key, propJVM.getProperty(key));
}
}
}
// SYS and ENV take priority (ENV are in lower-case keys)
String loc = "ENV";
Object value = propENV != null ? propENV.remove(lowerOptionName) : null;
if (ObjectHelper.isNotEmpty(propJVM)) {
Object val = propJVM.remove(optionName);
if (ObjectHelper.isNotEmpty(val)) {
// SYS override ENV
loc = "SYS";
value = val;
}
}
if (ObjectHelper.isEmpty(value)) {
// then try properties
loc = prop.getLocation(optionName);
value = prop.remove(optionName);
}
if (ObjectHelper.isEmpty(value)) {
// fallback to initial properties
value = getInitialProperties().getProperty(optionName);
loc = "initial";
}
// set the option if we have a value
if (ObjectHelper.isNotEmpty(value)) {
String str = CamelContextHelper.parseText(camelContext, value.toString());
setter.apply(str);
autoConfiguredProperties.put(loc, optionName, value.toString());
}
}
/**
* Configures CamelContext from the {@link MainConfigurationProperties} properties.
*/
protected void doConfigureCamelContextFromMainConfiguration(
CamelContext camelContext, MainConfigurationProperties config,
OrderedLocationProperties autoConfiguredProperties)
throws Exception {
if (ObjectHelper.isNotEmpty(config.getFileConfigurations())) {
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);
// org.apache.camel.spring.boot.CamelAutoConfiguration (camel-spring-boot) also calls the methods
// on DefaultConfigurationConfigurer, but the CamelContext being configured is already
// org.apache.camel.spring.boot.SpringBootCamelContext, which has access to Spring's ApplicationContext.
// That's why DefaultConfigurationConfigurer.afterConfigure() can alter CamelContext using beans from
// Spring's ApplicationContext.
// so here, before configuring Camel Context, we can process the registry and let Main implementations
// decide how to do it
preProcessCamelRegistry(camelContext, config);
// lookup and configure SPI beans
DefaultConfigurationConfigurer.afterConfigure(camelContext);
// now configure context/resilience4j/rest with additional properties
OrderedLocationProperties prop = (OrderedLocationProperties) camelContext.getPropertiesComponent()
.loadProperties(name -> name.startsWith("camel."), MainHelper::optionKey);
// load properties from ENV (override existing)
if (mainConfigurationProperties.isAutoConfigurationEnvironmentVariablesEnabled()) {
Properties propENV
= MainHelper.loadEnvironmentVariablesAsProperties(new String[] { "camel.component.properties." });
if (!propENV.isEmpty()) {
prop.putAll("ENV", 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 = MainHelper.loadJvmSystemPropertiesAsProperties(new String[] { "camel.component.properties." });
if (!propJVM.isEmpty()) {
prop.putAll("SYS", propJVM);
LOG.debug("Properties from JVM system properties:");
for (String key : propJVM.stringPropertyNames()) {
LOG.debug(" {}={}", key, propJVM.getProperty(key));
}
}
}
OrderedLocationProperties contextProperties = new OrderedLocationProperties();
OrderedLocationProperties resilience4jProperties = new OrderedLocationProperties();
OrderedLocationProperties faultToleranceProperties = new OrderedLocationProperties();
OrderedLocationProperties restProperties = new OrderedLocationProperties();
OrderedLocationProperties vaultProperties = new OrderedLocationProperties();
OrderedLocationProperties threadPoolProperties = new OrderedLocationProperties();
OrderedLocationProperties healthProperties = new OrderedLocationProperties();
OrderedLocationProperties lraProperties = new OrderedLocationProperties();
OrderedLocationProperties otelProperties = new OrderedLocationProperties();
OrderedLocationProperties metricsProperties = new OrderedLocationProperties();
OrderedLocationProperties routeTemplateProperties = new OrderedLocationProperties();
OrderedLocationProperties variableProperties = new OrderedLocationProperties();
OrderedLocationProperties beansProperties = new OrderedLocationProperties();
OrderedLocationProperties devConsoleProperties = new OrderedLocationProperties();
OrderedLocationProperties globalOptions = new OrderedLocationProperties();
OrderedLocationProperties httpServerProperties = new OrderedLocationProperties();
OrderedLocationProperties sslProperties = new OrderedLocationProperties();
OrderedLocationProperties debuggerProperties = new OrderedLocationProperties();
OrderedLocationProperties tracerProperties = new OrderedLocationProperties();
OrderedLocationProperties routeControllerProperties = new OrderedLocationProperties();
for (String key : prop.stringPropertyNames()) {