/
DefaultCamelContext.java
2191 lines (1892 loc) · 84.1 KB
/
DefaultCamelContext.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.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.naming.Context;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Endpoint;
import org.apache.camel.FailedToStartRouteException;
import org.apache.camel.IsSingleton;
import org.apache.camel.MultipleConsumersSupport;
import org.apache.camel.NoFactoryAvailableException;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.ResolveEndpointFailedException;
import org.apache.camel.Route;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.Service;
import org.apache.camel.ServiceStatus;
import org.apache.camel.ShutdownRoute;
import org.apache.camel.ShutdownRunningTask;
import org.apache.camel.StartupListener;
import org.apache.camel.SuspendableService;
import org.apache.camel.TypeConverter;
import org.apache.camel.VetoCamelContextStartException;
import org.apache.camel.builder.ErrorHandlerBuilder;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.converter.BaseTypeConverterRegistry;
import org.apache.camel.impl.converter.DefaultTypeConverter;
import org.apache.camel.impl.converter.LazyLoadingTypeConverter;
import org.apache.camel.management.DefaultManagementAgent;
import org.apache.camel.management.DefaultManagementLifecycleStrategy;
import org.apache.camel.management.DefaultManagementStrategy;
import org.apache.camel.management.JmxSystemPropertyKeys;
import org.apache.camel.management.ManagedManagementStrategy;
import org.apache.camel.model.DataFormatDefinition;
import org.apache.camel.model.RouteDefinition;
import org.apache.camel.processor.interceptor.Debug;
import org.apache.camel.processor.interceptor.Delayer;
import org.apache.camel.processor.interceptor.HandleFault;
import org.apache.camel.processor.interceptor.StreamCaching;
import org.apache.camel.processor.interceptor.Tracer;
import org.apache.camel.spi.CamelContextNameStrategy;
import org.apache.camel.spi.ClassResolver;
import org.apache.camel.spi.ComponentResolver;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.DataFormatResolver;
import org.apache.camel.spi.Debugger;
import org.apache.camel.spi.EndpointStrategy;
import org.apache.camel.spi.EventNotifier;
import org.apache.camel.spi.ExecutorServiceStrategy;
import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.FactoryFinderResolver;
import org.apache.camel.spi.InflightRepository;
import org.apache.camel.spi.Injector;
import org.apache.camel.spi.InterceptStrategy;
import org.apache.camel.spi.Language;
import org.apache.camel.spi.LanguageResolver;
import org.apache.camel.spi.LifecycleStrategy;
import org.apache.camel.spi.ManagementStrategy;
import org.apache.camel.spi.NodeIdFactory;
import org.apache.camel.spi.PackageScanClassResolver;
import org.apache.camel.spi.ProcessorFactory;
import org.apache.camel.spi.Registry;
import org.apache.camel.spi.RouteContext;
import org.apache.camel.spi.RouteStartupOrder;
import org.apache.camel.spi.ServicePool;
import org.apache.camel.spi.ShutdownStrategy;
import org.apache.camel.spi.TypeConverterRegistry;
import org.apache.camel.spi.UuidGenerator;
import org.apache.camel.util.CamelContextHelper;
import org.apache.camel.util.CastUtils;
import org.apache.camel.util.EndpointHelper;
import org.apache.camel.util.EventHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ReflectionInjector;
import org.apache.camel.util.ServiceHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.URISupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Represents the context used to configure routes and the policies to use.
*
* @version $Revision$
*/
public class DefaultCamelContext extends ServiceSupport implements CamelContext, SuspendableService {
private static final transient Log LOG = LogFactory.getLog(DefaultCamelContext.class);
private CamelContextNameStrategy nameStrategy = new DefaultCamelContextNameStrategy();
private ClassLoader applicationContextClassLoader;
private final Map<String, Endpoint> endpoints = new EndpointRegistry();
private final AtomicInteger endpointKeyCounter = new AtomicInteger();
private final List<EndpointStrategy> endpointStrategies = new ArrayList<EndpointStrategy>();
private final Map<String, Component> components = new HashMap<String, Component>();
private Set<Route> routes;
private final List<Service> servicesToClose = new ArrayList<Service>();
private final Set<StartupListener> startupListeners = new LinkedHashSet<StartupListener>();
private TypeConverter typeConverter;
private TypeConverterRegistry typeConverterRegistry;
private Injector injector;
private ComponentResolver componentResolver;
private boolean autoCreateComponents = true;
private LanguageResolver languageResolver = new DefaultLanguageResolver();
private final Map<String, Language> languages = new HashMap<String, Language>();
private Registry registry;
private List<LifecycleStrategy> lifecycleStrategies = new ArrayList<LifecycleStrategy>();
private ManagementStrategy managementStrategy;
private AtomicBoolean managementStrategyInitialized = new AtomicBoolean(false);
private final List<RouteDefinition> routeDefinitions = new ArrayList<RouteDefinition>();
private List<InterceptStrategy> interceptStrategies = new ArrayList<InterceptStrategy>();
// special flags to control the first startup which can are special
private volatile boolean firstStartDone;
private volatile boolean doNotStartRoutesOnFirstStart;
private Boolean autoStartup = Boolean.TRUE;
private Boolean trace = Boolean.FALSE;
private Boolean streamCache = Boolean.FALSE;
private Boolean handleFault = Boolean.FALSE;
private Boolean disableJMX = Boolean.FALSE;
private Boolean lazyLoadTypeConverters = Boolean.FALSE;
private Long delay;
private ErrorHandlerBuilder errorHandlerBuilder;
private Map<String, DataFormatDefinition> dataFormats = new HashMap<String, DataFormatDefinition>();
private DataFormatResolver dataFormatResolver = new DefaultDataFormatResolver();
private Map<String, String> properties = new HashMap<String, String>();
private FactoryFinderResolver factoryFinderResolver = new DefaultFactoryFinderResolver();
private FactoryFinder defaultFactoryFinder;
private final Map<String, FactoryFinder> factories = new HashMap<String, FactoryFinder>();
private final Map<String, RouteService> routeServices = new LinkedHashMap<String, RouteService>();
private final Map<String, RouteService> suspendedRouteServices = new LinkedHashMap<String, RouteService>();
private ClassResolver classResolver = new DefaultClassResolver();
private PackageScanClassResolver packageScanClassResolver;
// we use a capacity of 100 per endpoint, so for the same endpoint we have at most 100 producers in the pool
// so if we have 6 endpoints in the pool, we can have 6 x 100 producers in total
private ServicePool<Endpoint, Producer> producerServicePool = new SharedProducerServicePool(100);
private NodeIdFactory nodeIdFactory = new DefaultNodeIdFactory();
private ProcessorFactory processorFactory;
private InterceptStrategy defaultTracer;
private InflightRepository inflightRepository = new DefaultInflightRepository();
private final List<RouteStartupOrder> routeStartupOrder = new ArrayList<RouteStartupOrder>();
// start auto assigning route ids using numbering 1000 and upwards
private int defaultRouteStartupOrder = 1000;
private ShutdownStrategy shutdownStrategy = new DefaultShutdownStrategy(this);
private ShutdownRoute shutdownRoute = ShutdownRoute.Default;
private ShutdownRunningTask shutdownRunningTask = ShutdownRunningTask.CompleteCurrentTaskOnly;
private ExecutorServiceStrategy executorServiceStrategy = new DefaultExecutorServiceStrategy(this);
private Debugger debugger;
private UuidGenerator uuidGenerator = createDefaultUuidGenerator();
private final StopWatch stopWatch = new StopWatch(false);
private Date startDate;
public DefaultCamelContext() {
super();
// use WebSphere specific resolver if running on WebSphere
if (WebSpherePackageScanClassResolver.isWebSphereClassLoader(this.getClass().getClassLoader())) {
LOG.info("Using WebSphere specific PackageScanClassResolver");
packageScanClassResolver = new WebSpherePackageScanClassResolver("META-INF/services/org/apache/camel/TypeConverter");
} else {
packageScanClassResolver = new DefaultPackageScanClassResolver();
}
}
/**
* Creates the {@link CamelContext} using the given JNDI context as the registry
*
* @param jndiContext the JNDI context
*/
public DefaultCamelContext(Context jndiContext) {
this();
setJndiContext(jndiContext);
}
/**
* Creates the {@link CamelContext} using the given registry
*
* @param registry the registry
*/
public DefaultCamelContext(Registry registry) {
this();
setRegistry(registry);
}
public String getName() {
return getNameStrategy().getName();
}
/**
* Sets the name of the this context.
*
* @param name the name
*/
public void setName(String name) {
// use an explicit name strategy since an explicit name was provided to be used
this.nameStrategy = new ExplicitCamelContextNameStrategy(name);
}
public CamelContextNameStrategy getNameStrategy() {
return nameStrategy;
}
public void setNameStrategy(CamelContextNameStrategy nameStrategy) {
this.nameStrategy = nameStrategy;
}
public Component hasComponent(String componentName) {
return components.get(componentName);
}
public void addComponent(String componentName, final Component component) {
ObjectHelper.notNull(component, "component");
synchronized (components) {
if (components.containsKey(componentName)) {
throw new IllegalArgumentException("Cannot add component as its already previously added: " + componentName);
}
component.setCamelContext(this);
components.put(componentName, component);
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onComponentAdd(componentName, component);
}
}
}
public Component getComponent(String name) {
// synchronize the look up and auto create so that 2 threads can't
// concurrently auto create the same component.
synchronized (components) {
Component component = components.get(name);
if (component == null && autoCreateComponents) {
try {
component = getComponentResolver().resolveComponent(name, this);
if (component != null) {
addComponent(name, component);
if (isStarted() || isStarting()) {
// If the component is looked up after the context is started, lets start it up.
startServices(component);
}
}
} catch (Exception e) {
throw new RuntimeCamelException("Cannot auto create component: " + name, e);
}
}
return component;
}
}
public <T extends Component> T getComponent(String name, Class<T> componentType) {
Component component = getComponent(name);
if (componentType.isInstance(component)) {
return componentType.cast(component);
} else {
throw new IllegalArgumentException("The component is not of type: " + componentType + " but is: "
+ component);
}
}
public Component removeComponent(String componentName) {
synchronized (components) {
Component answer = components.remove(componentName);
if (answer != null) {
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onComponentRemove(componentName, answer);
}
}
return answer;
}
}
// Endpoint Management Methods
// -----------------------------------------------------------------------
public Collection<Endpoint> getEndpoints() {
synchronized (endpoints) {
return new ArrayList<Endpoint>(endpoints.values());
}
}
public Map<String, Endpoint> getEndpointMap() {
synchronized (endpoints) {
return new TreeMap<String, Endpoint>(endpoints);
}
}
public Endpoint hasEndpoint(String uri) {
// normalize uri so we can do endpoint hits with minor mistakes and parameters is not in the same order
try {
uri = URISupport.normalizeUri(uri);
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
synchronized (endpoints) {
return endpoints.get(uri);
}
}
public Endpoint addEndpoint(String uri, Endpoint endpoint) throws Exception {
Endpoint oldEndpoint;
synchronized (endpoints) {
startServices(endpoint);
oldEndpoint = endpoints.remove(uri);
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onEndpointAdd(endpoint);
}
addEndpointToRegistry(uri, endpoint);
if (oldEndpoint != null) {
stopServices(oldEndpoint);
}
}
return oldEndpoint;
}
public Collection<Endpoint> removeEndpoints(String uri) throws Exception {
Collection<Endpoint> answer = new ArrayList<Endpoint>();
Endpoint oldEndpoint = endpoints.remove(uri);
if (oldEndpoint != null) {
answer.add(oldEndpoint);
stopServices(oldEndpoint);
} else {
for (Map.Entry entry : endpoints.entrySet()) {
oldEndpoint = (Endpoint)entry.getValue();
if (EndpointHelper.matchEndpoint(oldEndpoint.getEndpointUri(), uri)) {
answer.add(oldEndpoint);
stopServices(oldEndpoint);
}
}
for (Endpoint endpoint : answer) {
endpoints.remove(endpoint.getEndpointUri());
}
}
// notify lifecycle its being removed
for (Endpoint endpoint : answer) {
for (LifecycleStrategy strategy : lifecycleStrategies) {
strategy.onEndpointRemove(endpoint);
}
}
return answer;
}
public Endpoint getEndpoint(String uri) {
ObjectHelper.notEmpty(uri, "uri");
if (LOG.isTraceEnabled()) {
LOG.trace("Getting endpoint with uri: " + uri);
}
// in case path has property placeholders then try to let property component resolve those
try {
uri = resolvePropertyPlaceholders(uri);
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
// normalize uri so we can do endpoint hits with minor mistakes and parameters is not in the same order
try {
uri = URISupport.normalizeUri(uri);
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
if (LOG.isTraceEnabled()) {
LOG.trace("Getting endpoint with normalized uri: " + uri);
}
Endpoint answer;
String scheme = null;
synchronized (endpoints) {
answer = endpoints.get(uri);
if (answer == null) {
try {
// Use the URI prefix to find the component.
String splitURI[] = ObjectHelper.splitOnCharacter(uri, ":", 2);
if (splitURI[1] != null) {
scheme = splitURI[0];
Component component = getComponent(scheme);
// Ask the component to resolve the endpoint.
if (component != null) {
// Have the component create the endpoint if it can.
answer = component.createEndpoint(uri);
if (answer != null && LOG.isDebugEnabled()) {
LOG.debug(uri + " converted to endpoint: " + answer + " by component: " + component);
}
}
}
if (answer == null) {
// no component then try in registry and elsewhere
answer = createEndpoint(uri);
}
if (answer != null) {
addService(answer);
answer = addEndpointToRegistry(uri, answer);
}
} catch (Exception e) {
throw new ResolveEndpointFailedException(uri, e);
}
}
}
// unknown scheme
if (answer == null && scheme != null) {
throw new ResolveEndpointFailedException(uri, "No component found with scheme: " + scheme);
}
return answer;
}
public <T extends Endpoint> T getEndpoint(String name, Class<T> endpointType) {
Endpoint endpoint = getEndpoint(name);
if (endpoint instanceof InterceptSendToEndpoint) {
endpoint = ((InterceptSendToEndpoint) endpoint).getDelegate();
}
if (endpointType.isInstance(endpoint)) {
return endpointType.cast(endpoint);
} else {
throw new IllegalArgumentException("The endpoint is not of type: " + endpointType + " but is: "
+ endpoint.getClass().getCanonicalName());
}
}
public void addRegisterEndpointCallback(EndpointStrategy strategy) {
if (!endpointStrategies.contains(strategy)) {
// let it be invoked for already registered endpoints so it can catch-up.
endpointStrategies.add(strategy);
for (Endpoint endpoint : getEndpoints()) {
Endpoint newEndpoint = strategy.registerEndpoint(endpoint.getEndpointUri(), endpoint);
if (newEndpoint != endpoint) {
endpoints.put(getEndpointKey(newEndpoint.getEndpointUri(), newEndpoint), newEndpoint);
}
}
}
}
/**
* Strategy to add the given endpoint to the internal endpoint registry
*
* @param uri uri of endpoint
* @param endpoint the endpoint to add
* @return the added endpoint
*/
protected Endpoint addEndpointToRegistry(String uri, Endpoint endpoint) {
for (EndpointStrategy strategy : endpointStrategies) {
endpoint = strategy.registerEndpoint(uri, endpoint);
}
endpoints.put(getEndpointKey(uri, endpoint), endpoint);
return endpoint;
}
// Route Management Methods
// -----------------------------------------------------------------------
/**
* Returns the order in which the route inputs was started.
* <p/>
* The order may not be according to the startupOrder defined on the route.
* For example a route could be started manually later, or new routes added at runtime.
*
* @return a list in the order how routes was started
*/
public List<RouteStartupOrder> getRouteStartupOrder() {
return routeStartupOrder;
}
public synchronized List<Route> getRoutes() {
if (routes == null) {
routes = new LinkedHashSet<Route>();
}
// lets return a copy of the collection as objects are removed later
// when services are stopped
return new ArrayList<Route>(routes);
}
public Route getRoute(String id) {
for (Route route : getRoutes()) {
if (route.getId().equals(id)) {
return route;
}
}
return null;
}
@Deprecated
public void setRoutes(List<Route> routes) {
throw new UnsupportedOperationException("Overriding existing routes is not supported yet, use addRouteCollection instead");
}
synchronized void removeRouteCollection(Collection<Route> routes) {
if (this.routes != null) {
this.routes.removeAll(routes);
}
}
synchronized void addRouteCollection(Collection<Route> routes) throws Exception {
if (this.routes == null) {
this.routes = new LinkedHashSet<Route>();
}
if (routes != null) {
this.routes.addAll(routes);
}
}
public void addRoutes(RoutesBuilder builder) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("Adding routes from builder: " + builder);
}
// lets now add the routes from the builder
builder.addRoutesToCamelContext(this);
}
public void addRouteDefinitions(Collection<RouteDefinition> routeDefinitions) throws Exception {
for (RouteDefinition routeDefinition : routeDefinitions) {
removeRouteDefinition(routeDefinition);
}
this.routeDefinitions.addAll(routeDefinitions);
if (shouldStartRoutes()) {
startRouteDefinitions(routeDefinitions);
}
}
public void addRouteDefinition(RouteDefinition routeDefinition) throws Exception {
addRouteDefinitions(Arrays.asList(routeDefinition));
}
/**
* Removes the route definition with the given key.
*
* @return true if one or more routes was removed
*/
protected boolean removeRouteDefinition(String key) {
boolean answer = false;
Iterator<RouteDefinition> iter = routeDefinitions.iterator();
while (iter.hasNext()) {
RouteDefinition route = iter.next();
if (route.idOrCreate(nodeIdFactory).equals(key)) {
iter.remove();
answer = true;
}
}
return answer;
}
public void removeRouteDefinitions(Collection<RouteDefinition> routeDefinitions) throws Exception {
this.routeDefinitions.removeAll(routeDefinitions);
for (RouteDefinition routeDefinition : routeDefinitions) {
removeRouteDefinition(routeDefinition);
}
}
public void removeRouteDefinition(RouteDefinition routeDefinition) throws Exception {
String id = routeDefinition.idOrCreate(nodeIdFactory);
stopRoute(id);
removeRoute(id);
}
public ServiceStatus getRouteStatus(String key) {
RouteService routeService = routeServices.get(key);
if (routeService != null) {
return routeService.getStatus();
}
return null;
}
public void startRoute(RouteDefinition route) throws Exception {
List<Route> routes = new ArrayList<Route>();
List<RouteContext> routeContexts = route.addRoutes(this, routes);
RouteService routeService = new RouteService(this, route, routeContexts, routes);
// must ensure route is prepared, before we can start it
route.prepare();
startRouteService(routeService, true);
}
public void stopRoute(RouteDefinition route) throws Exception {
stopRoute(route.idOrCreate(nodeIdFactory));
}
public synchronized void startRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
startRouteService(routeService, false);
}
}
public synchronized void resumeRoute(String routeId) throws Exception {
if (!routeSupportsSuspension(routeId)) {
// start route if suspension is not supported
startRoute(routeId);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
resumeRouteService(routeService);
}
}
public synchronized void stopRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes);
// must stop route service as well
routeService.setRemovingRoutes(false);
stopRouteService(routeService);
}
}
public synchronized void stopRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes, timeout, timeUnit);
// must stop route service as well
routeService.setRemovingRoutes(false);
stopRouteService(routeService);
}
}
public synchronized void shutdownRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes);
// must stop route service as well (and remove the routes from management)
routeService.setRemovingRoutes(true);
stopRouteService(routeService);
}
}
public synchronized void shutdownRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().shutdown(this, routes, timeout, timeUnit);
// must stop route service as well (and remove the routes from management)
routeService.setRemovingRoutes(true);
stopRouteService(routeService);
}
}
public synchronized boolean removeRoute(String routeId) throws Exception {
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
if (getRouteStatus(routeId).isStopped()) {
routeService.setRemovingRoutes(true);
shutdownRouteService(routeService);
removeRouteDefinition(routeId);
ServiceHelper.stopAndShutdownServices(routeService);
routeServices.remove(routeId);
return true;
} else {
return false;
}
}
return false;
}
public synchronized void suspendRoute(String routeId) throws Exception {
if (!routeSupportsSuspension(routeId)) {
// stop if we suspend is not supported
stopRoute(routeId);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().suspend(this, routes);
// must suspend route service as well
routeService.setRemovingRoutes(false);
suspendRouteService(routeService);
}
}
public synchronized void suspendRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception {
if (!routeSupportsSuspension(routeId)) {
stopRoute(routeId, timeout, timeUnit);
return;
}
RouteService routeService = routeServices.get(routeId);
if (routeService != null) {
List<RouteStartupOrder> routes = new ArrayList<RouteStartupOrder>(1);
RouteStartupOrder order = new DefaultRouteStartupOrder(1, routeService.getRoutes().iterator().next(), routeService);
routes.add(order);
getShutdownStrategy().suspend(this, routes, timeout, timeUnit);
// must suspend route service as well
routeService.setRemovingRoutes(false);
suspendRouteService(routeService);
}
}
public void addService(Object object) throws Exception {
if (object instanceof Service) {
Service service = (Service) object;
for (LifecycleStrategy strategy : lifecycleStrategies) {
if (service instanceof Endpoint) {
// use specialized endpint add
strategy.onEndpointAdd((Endpoint) service);
} else {
strategy.onServiceAdd(this, service, null);
}
}
// only add to services to close if its a singleton
// otherwise we could end up with a lot of endpoints (prototype scoped)
boolean singleton = true; // assume singleton by default
if (service instanceof IsSingleton) {
singleton = ((IsSingleton) service).isSingleton();
}
if (singleton) {
servicesToClose.add(service);
}
}
startServices(object);
}
public boolean hasService(Object object) {
if (object instanceof Service) {
Service service = (Service) object;
return servicesToClose.contains(service);
}
return false;
}
public void addStartupListener(StartupListener listener) throws Exception {
// either add to listener so we can invoke then later when CamelContext has been started
// or invoke the callback right now
if (isStarted()) {
listener.onCamelContextStarted(this, true);
} else {
startupListeners.add(listener);
}
}
// Helper methods
// -----------------------------------------------------------------------
public Language resolveLanguage(String language) {
Language answer;
synchronized (languages) {
answer = languages.get(language);
// check if the language is singleton, if so return the shared instance
if (answer instanceof IsSingleton) {
boolean singleton = ((IsSingleton) answer).isSingleton();
if (singleton) {
return answer;
}
}
// language not known or not singleton, then use resolver
answer = getLanguageResolver().resolveLanguage(language, this);
if (answer != null) {
languages.put(language, answer);
}
}
// no language resolved
return answer;
}
public String resolvePropertyPlaceholders(String text) throws Exception {
// do not parse uris that are designated for the properties component as it will handle that itself
if (text != null && !text.startsWith("properties:") && text.contains(PropertiesComponent.PREFIX_TOKEN)) {
// the uri contains property placeholders so lookup mandatory properties component and let it parse it
Component component = hasComponent("properties");
if (component == null) {
// then fallback to lookup the component
component = getRegistry().lookup("properties", Component.class);
}
if (component == null) {
throw new IllegalArgumentException("PropertiesComponent with name properties must be defined"
+ " in CamelContext to support property placeholders.");
}
// force component to be created and registered as a component
PropertiesComponent pc = getComponent("properties", PropertiesComponent.class);
// the parser will throw exception if property key was not found
String answer = pc.parseUri(text);
if (LOG.isDebugEnabled()) {
LOG.debug("Resolved text: " + text + " -> " + answer);
}
return answer;
}
// return original text as is
return text;
}
// Properties
// -----------------------------------------------------------------------
public TypeConverter getTypeConverter() {
if (typeConverter == null) {
synchronized (this) {
// we can synchronize on this as there is only one instance
// of the camel context (its the container)
typeConverter = createTypeConverter();
try {
addService(typeConverter);
} catch (Exception e) {
throw ObjectHelper.wrapRuntimeCamelException(e);
}
}
}
return typeConverter;
}
public void setTypeConverter(TypeConverter typeConverter) {
this.typeConverter = typeConverter;
}
public TypeConverterRegistry getTypeConverterRegistry() {
if (typeConverterRegistry == null) {
// init type converter as its lazy
if (typeConverter == null) {
getTypeConverter();
}
if (typeConverter instanceof TypeConverterRegistry) {
typeConverterRegistry = (TypeConverterRegistry) typeConverter;
}
}
return typeConverterRegistry;
}
public void setTypeConverterRegistry(TypeConverterRegistry typeConverterRegistry) {
this.typeConverterRegistry = typeConverterRegistry;
}
public Injector getInjector() {
if (injector == null) {
injector = createInjector();
}
return injector;
}
public void setInjector(Injector injector) {
this.injector = injector;
}
public ComponentResolver getComponentResolver() {
if (componentResolver == null) {
componentResolver = createComponentResolver();
}
return componentResolver;
}
public void setComponentResolver(ComponentResolver componentResolver) {
this.componentResolver = componentResolver;
}
public LanguageResolver getLanguageResolver() {
if (languageResolver == null) {
languageResolver = new DefaultLanguageResolver();
}
return languageResolver;
}
public void setLanguageResolver(LanguageResolver languageResolver) {
this.languageResolver = languageResolver;
}
public boolean isAutoCreateComponents() {
return autoCreateComponents;
}
public void setAutoCreateComponents(boolean autoCreateComponents) {
this.autoCreateComponents = autoCreateComponents;
}
public Registry getRegistry() {
if (registry == null) {
registry = createRegistry();
setRegistry(registry);
}
return registry;
}
/**
* Sets the registry to the given JNDI context
*
* @param jndiContext is the JNDI context to use as the registry
* @see #setRegistry(org.apache.camel.spi.Registry)
*/
public void setJndiContext(Context jndiContext) {
setRegistry(new JndiRegistry(jndiContext));
}
public void setRegistry(Registry registry) {
// wrap the registry so we always do propery placeholder lookups
if (!(registry instanceof PropertyPlaceholderDelegateRegistry)) {
registry = new PropertyPlaceholderDelegateRegistry(this, registry);
}
this.registry = registry;
}
public List<LifecycleStrategy> getLifecycleStrategies() {
return lifecycleStrategies;
}
public void setLifecycleStrategies(List<LifecycleStrategy> lifecycleStrategies) {
this.lifecycleStrategies = lifecycleStrategies;
}
public void addLifecycleStrategy(LifecycleStrategy lifecycleStrategy) {
this.lifecycleStrategies.add(lifecycleStrategy);
}
public List<RouteDefinition> getRouteDefinitions() {
return routeDefinitions;
}
public RouteDefinition getRouteDefinition(String id) {
for (RouteDefinition route : routeDefinitions) {
if (route.getId().equals(id)) {
return route;
}
}
return null;
}
public List<InterceptStrategy> getInterceptStrategies() {
return interceptStrategies;
}
public void setInterceptStrategies(List<InterceptStrategy> interceptStrategies) {
this.interceptStrategies = interceptStrategies;
}
public void addInterceptStrategy(InterceptStrategy interceptStrategy) {
getInterceptStrategies().add(interceptStrategy);
// for backwards compatible or if user add them here instead of the setXXX methods
if (interceptStrategy instanceof Tracer) {
setTracing(true);
} else if (interceptStrategy instanceof HandleFault) {
setHandleFault(true);
} else if (interceptStrategy instanceof StreamCaching) {