-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
JettyHttpComponent.java
1359 lines (1204 loc) · 57.4 KB
/
JettyHttpComponent.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.component.jetty;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.management.MBeanServer;
import javax.servlet.Filter;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.camel.CamelContext;
import org.apache.camel.Consumer;
import org.apache.camel.Endpoint;
import org.apache.camel.Processor;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.http.common.CamelServlet;
import org.apache.camel.http.common.HttpBinding;
import org.apache.camel.http.common.HttpCommonComponent;
import org.apache.camel.http.common.HttpCommonEndpoint;
import org.apache.camel.http.common.HttpConfiguration;
import org.apache.camel.http.common.HttpConsumer;
import org.apache.camel.http.common.HttpRestServletResolveConsumerStrategy;
import org.apache.camel.http.common.UrlRewrite;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.spi.ManagementAgent;
import org.apache.camel.spi.ManagementStrategy;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.RestApiConsumerFactory;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.RestConsumerFactory;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.HostUtils;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.URISupport;
import org.apache.camel.util.UnsafeUriCharactersEncoder;
import org.apache.camel.util.jsse.SSLContextParameters;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.server.AbstractConnector;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.eclipse.jetty.servlets.MultiPartFilter;
import org.eclipse.jetty.util.component.Container;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An HttpComponent which starts an embedded Jetty for to handle consuming from
* the http endpoints.
*
* @version
*/
public abstract class JettyHttpComponent extends HttpCommonComponent implements RestConsumerFactory, RestApiConsumerFactory {
public static final String TMP_DIR = "CamelJettyTempDir";
protected static final HashMap<String, ConnectorRef> CONNECTORS = new HashMap<String, ConnectorRef>();
private static final Logger LOG = LoggerFactory.getLogger(JettyHttpComponent.class);
private static final String JETTY_SSL_KEYSTORE = "org.eclipse.jetty.ssl.keystore";
private static final String JETTY_SSL_KEYPASSWORD = "org.eclipse.jetty.ssl.keypassword";
private static final String JETTY_SSL_PASSWORD = "org.eclipse.jetty.ssl.password";
protected String sslKeyPassword;
protected String sslPassword;
protected String sslKeystore;
protected Map<Integer, Connector> sslSocketConnectors;
protected Map<Integer, Connector> socketConnectors;
protected Map<String, Object> sslSocketConnectorProperties;
protected Map<String, Object> socketConnectorProperties;
protected Integer httpClientMinThreads;
protected Integer httpClientMaxThreads;
protected Integer minThreads;
protected Integer maxThreads;
protected ThreadPool threadPool;
protected MBeanContainer mbContainer;
protected boolean enableJmx;
protected JettyHttpBinding jettyHttpBinding;
protected Long continuationTimeout;
protected boolean useContinuation = true;
protected SSLContextParameters sslContextParameters;
protected Integer requestBufferSize;
protected Integer requestHeaderSize;
protected Integer responseBufferSize;
protected Integer responseHeaderSize;
protected String proxyHost;
protected ErrorHandler errorHandler;
private Integer proxyPort;
public JettyHttpComponent() {
super(JettyHttpEndpoint.class);
}
class ConnectorRef {
Server server;
Connector connector;
CamelServlet servlet;
int refCount;
public ConnectorRef(Server server, Connector connector, CamelServlet servlet) {
this.server = server;
this.connector = connector;
this.servlet = servlet;
increment();
}
public int increment() {
return ++refCount;
}
public int decrement() {
return --refCount;
}
public int getRefCount() {
return refCount;
}
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
// must extract well known parameters before we create the endpoint
List<Handler> handlerList = resolveAndRemoveReferenceListParameter(parameters, "handlers", Handler.class);
HttpBinding binding = resolveAndRemoveReferenceParameter(parameters, "httpBindingRef", HttpBinding.class);
JettyHttpBinding jettyBinding = resolveAndRemoveReferenceParameter(parameters, "jettyHttpBindingRef", JettyHttpBinding.class);
Boolean throwExceptionOnFailure = getAndRemoveParameter(parameters, "throwExceptionOnFailure", Boolean.class);
Boolean transferException = getAndRemoveParameter(parameters, "transferException", Boolean.class);
Boolean bridgeEndpoint = getAndRemoveParameter(parameters, "bridgeEndpoint", Boolean.class);
Boolean matchOnUriPrefix = getAndRemoveParameter(parameters, "matchOnUriPrefix", Boolean.class);
Boolean enableJmx = getAndRemoveParameter(parameters, "enableJmx", Boolean.class);
Boolean enableMultipartFilter = getAndRemoveParameter(parameters, "enableMultipartFilter",
Boolean.class, true);
Filter multipartFilter = resolveAndRemoveReferenceParameter(parameters, "multipartFilterRef", Filter.class);
List<Filter> filters = resolveAndRemoveReferenceListParameter(parameters, "filtersRef", Filter.class);
Boolean enableCors = getAndRemoveParameter(parameters, "enableCORS", Boolean.class, false);
Long continuationTimeout = getAndRemoveParameter(parameters, "continuationTimeout", Long.class);
Boolean useContinuation = getAndRemoveParameter(parameters, "useContinuation", Boolean.class);
HeaderFilterStrategy headerFilterStrategy = resolveAndRemoveReferenceParameter(parameters, "headerFilterStrategy", HeaderFilterStrategy.class);
UrlRewrite urlRewrite = resolveAndRemoveReferenceParameter(parameters, "urlRewrite", UrlRewrite.class);
SSLContextParameters sslContextParameters = resolveAndRemoveReferenceParameter(parameters, "sslContextParametersRef", SSLContextParameters.class);
SSLContextParameters ssl = sslContextParameters != null ? sslContextParameters : this.sslContextParameters;
String proxyHost = getAndRemoveParameter(parameters, "proxyHost", String.class, getProxyHost());
Integer proxyPort = getAndRemoveParameter(parameters, "proxyPort", Integer.class, getProxyPort());
Integer responseBufferSize = getAndRemoveParameter(parameters, "responseBufferSize", Integer.class, getResponseBufferSize());
Integer httpClientMinThreads = getAndRemoveParameter(parameters, "httpClientMinThreads", Integer.class, this.httpClientMinThreads);
Integer httpClientMaxThreads = getAndRemoveParameter(parameters, "httpClientMaxThreads", Integer.class, this.httpClientMaxThreads);
// extract httpClient. parameters
Map<String, Object> httpClientParameters = IntrospectionSupport.extractProperties(parameters, "httpClient.");
String address = remaining;
URI addressUri = new URI(UnsafeUriCharactersEncoder.encodeHttpURI(address));
URI endpointUri = URISupport.createRemainingURI(addressUri, parameters);
// need to keep the httpMethodRestrict parameter for the endpointUri
String httpMethodRestrict = getAndRemoveParameter(parameters, "httpMethodRestrict", String.class);
// restructure uri to be based on the parameters left as we dont want to include the Camel internal options
URI httpUri = URISupport.createRemainingURI(addressUri, parameters);
// create endpoint after all known parameters have been extracted from parameters
// include component scheme in the uri
String scheme = ObjectHelper.before(uri, ":");
endpointUri = new URI(scheme + ":" + endpointUri);
JettyHttpEndpoint endpoint = createEndpoint(endpointUri, httpUri);
if (headerFilterStrategy != null) {
endpoint.setHeaderFilterStrategy(headerFilterStrategy);
} else {
setEndpointHeaderFilterStrategy(endpoint);
}
if (proxyHost != null) {
endpoint.setProxyHost(proxyHost);
endpoint.setProxyPort(proxyPort);
}
if (urlRewrite != null) {
// let CamelContext deal with the lifecycle of the url rewrite
// this ensures its being shutdown when Camel shutdown etc.
getCamelContext().addService(urlRewrite);
endpoint.setUrlRewrite(urlRewrite);
}
// setup the proxy host and proxy port
if (httpClientParameters != null && !httpClientParameters.isEmpty()) {
endpoint.setHttpClientParameters(httpClientParameters);
}
if (handlerList.size() > 0) {
endpoint.setHandlers(handlerList);
}
// prefer to use endpoint configured over component configured
if (binding == null) {
// fallback to component configured
binding = getHttpBinding();
}
if (binding != null) {
endpoint.setBinding(binding);
}
// prefer to use endpoint configured over component configured
if (jettyBinding == null) {
// fallback to component configured
jettyBinding = getJettyHttpBinding();
}
if (jettyBinding != null) {
endpoint.setJettyBinding(jettyBinding);
}
// should we use an exception for failed error codes?
if (throwExceptionOnFailure != null) {
endpoint.setThrowExceptionOnFailure(throwExceptionOnFailure);
}
// should we transfer exception as serialized object
if (transferException != null) {
endpoint.setTransferException(transferException);
}
if (bridgeEndpoint != null) {
endpoint.setBridgeEndpoint(bridgeEndpoint);
}
if (matchOnUriPrefix != null) {
endpoint.setMatchOnUriPrefix(matchOnUriPrefix);
}
if (enableJmx != null) {
endpoint.setEnableJmx(enableJmx);
} else {
// set this option based on setting of JettyHttpComponent
endpoint.setEnableJmx(isEnableJmx());
}
endpoint.setEnableMultipartFilter(enableMultipartFilter);
if (multipartFilter != null) {
endpoint.setMultipartFilter(multipartFilter);
endpoint.setEnableMultipartFilter(true);
}
if (enableCors) {
if (filters == null) {
filters = new ArrayList<Filter>(1);
}
filters.add(new CrossOriginFilter());
}
if (filters != null) {
endpoint.setFilters(filters);
}
if (continuationTimeout != null) {
endpoint.setContinuationTimeout(continuationTimeout);
}
if (useContinuation != null) {
endpoint.setUseContinuation(useContinuation);
}
if (httpMethodRestrict != null) {
endpoint.setHttpMethodRestrict(httpMethodRestrict);
}
if (ssl != null) {
endpoint.setSslContextParameters(ssl);
}
if (responseBufferSize != null) {
endpoint.setResponseBufferSize(responseBufferSize);
}
if (httpClientMinThreads != null) {
endpoint.setHttpClientMinThreads(httpClientMinThreads);
}
if (httpClientMaxThreads != null) {
endpoint.setHttpClientMaxThreads(httpClientMaxThreads);
}
setProperties(endpoint, parameters);
return endpoint;
}
protected abstract JettyHttpEndpoint createEndpoint(URI endpointUri, URI httpUri) throws URISyntaxException;
/**
* Connects the URL specified on the endpoint to the specified processor.
*/
@Override
public void connect(HttpConsumer consumer) throws Exception {
// Make sure that there is a connector for the requested endpoint.
JettyHttpEndpoint endpoint = (JettyHttpEndpoint)consumer.getEndpoint();
String connectorKey = getConnectorKey(endpoint);
synchronized (CONNECTORS) {
ConnectorRef connectorRef = CONNECTORS.get(connectorKey);
if (connectorRef == null) {
Server server = createServer();
Connector connector = getConnector(server, endpoint);
if ("localhost".equalsIgnoreCase(endpoint.getHttpUri().getHost())) {
LOG.warn("You use localhost interface! It means that no external connections will be available."
+ " Don't you want to use 0.0.0.0 instead (all network interfaces)? " + endpoint);
}
if (endpoint.isEnableJmx()) {
enableJmx(server);
}
server.addConnector(connector);
connectorRef = new ConnectorRef(server, connector, createServletForConnector(server, connector, endpoint.getHandlers(), endpoint));
// must enable session before we start
if (endpoint.isSessionSupport()) {
enableSessionSupport(connectorRef.server, connectorKey);
}
connectorRef.server.start();
CONNECTORS.put(connectorKey, connectorRef);
} else {
if (endpoint.getHandlers() != null && !endpoint.getHandlers().isEmpty()) {
// As the server is started, we need to stop the server for a while to add the new handler
connectorRef.server.stop();
addJettyHandlers(connectorRef.server, endpoint.getHandlers());
connectorRef.server.start();
}
// ref track the connector
connectorRef.increment();
}
// check the session support
if (endpoint.isSessionSupport()) {
enableSessionSupport(connectorRef.server, connectorKey);
}
if (endpoint.isEnableMultipartFilter()) {
enableMultipartFilter(endpoint, connectorRef.server, connectorKey);
}
if (endpoint.getFilters() != null && endpoint.getFilters().size() > 0) {
setFilters(endpoint, connectorRef.server, connectorKey);
}
connectorRef.servlet.connect(consumer);
}
}
private void enableJmx(Server server) {
MBeanContainer containerToRegister = getMbContainer();
if (containerToRegister != null) {
LOG.info("Jetty JMX Extensions is enabled");
addServerMBean(server);
// Since we may have many Servers running, don't tie the MBeanContainer
// to a Server lifecycle or we end up closing it while it is still in use.
//server.addBean(mbContainer);
}
}
private void enableSessionSupport(Server server, String connectorKey) throws Exception {
ServletContextHandler context = server.getChildHandlerByClass(ServletContextHandler.class);
if (context.getSessionHandler() == null) {
SessionHandler sessionHandler = new SessionHandler();
if (context.isStarted()) {
throw new IllegalStateException("Server has already been started. Cannot enabled sessionSupport on " + connectorKey);
} else {
context.setSessionHandler(sessionHandler);
}
}
}
private void setFilters(JettyHttpEndpoint endpoint, Server server, String connectorKey) {
ServletContextHandler context = server.getChildHandlerByClass(ServletContextHandler.class);
List<Filter> filters = endpoint.getFilters();
for (Filter filter : filters) {
FilterHolder filterHolder = new FilterHolder();
filterHolder.setFilter(new CamelFilterWrapper(filter));
String pathSpec = endpoint.getPath();
if (pathSpec == null || "".equals(pathSpec)) {
pathSpec = "/";
}
if (endpoint.isMatchOnUriPrefix()) {
pathSpec = pathSpec.endsWith("/") ? pathSpec + "*" : pathSpec + "/*";
}
addFilter(context, filterHolder, pathSpec);
}
}
private void addFilter(ServletContextHandler context, FilterHolder filterHolder, String pathSpec) {
context.getServletHandler().addFilterWithMapping(filterHolder, pathSpec, 0);
}
private void enableMultipartFilter(HttpCommonEndpoint endpoint, Server server, String connectorKey) throws Exception {
ServletContextHandler context = server.getChildHandlerByClass(ServletContextHandler.class);
CamelContext camelContext = this.getCamelContext();
FilterHolder filterHolder = new FilterHolder();
filterHolder.setInitParameter("deleteFiles", "true");
if (ObjectHelper.isNotEmpty(camelContext.getProperty(TMP_DIR))) {
File file = new File(camelContext.getProperty(TMP_DIR));
if (!file.isDirectory()) {
throw new RuntimeCamelException(
"The temp file directory of camel-jetty is not exists, please recheck it with directory name :"
+ camelContext.getProperties().get(TMP_DIR));
}
context.setAttribute("javax.servlet.context.tempdir", file);
}
// if a filter ref was provided, use it.
Filter filter = ((JettyHttpEndpoint) endpoint).getMultipartFilter();
if (filter == null) {
// if no filter ref was provided, use the default filter
filter = new MultiPartFilter();
}
filterHolder.setFilter(new CamelFilterWrapper(filter));
String pathSpec = endpoint.getPath();
if (pathSpec == null || "".equals(pathSpec)) {
pathSpec = "/";
}
if (endpoint.isMatchOnUriPrefix()) {
pathSpec = pathSpec.endsWith("/") ? pathSpec + "*" : pathSpec + "/*";
}
addFilter(context, filterHolder, pathSpec);
LOG.debug("using multipart filter implementation " + filter.getClass().getName() + " for path " + pathSpec);
}
/**
* Disconnects the URL specified on the endpoint from the specified processor.
*/
@Override
public void disconnect(HttpConsumer consumer) throws Exception {
// If the connector is not needed anymore then stop it
HttpCommonEndpoint endpoint = consumer.getEndpoint();
String connectorKey = getConnectorKey(endpoint);
synchronized (CONNECTORS) {
ConnectorRef connectorRef = CONNECTORS.get(connectorKey);
if (connectorRef != null) {
connectorRef.servlet.disconnect(consumer);
if (connectorRef.decrement() == 0) {
connectorRef.server.removeConnector(connectorRef.connector);
connectorRef.connector.stop();
connectorRef.server.stop();
CONNECTORS.remove(connectorKey);
// Camel controls the lifecycle of these entities so remove the
// registered MBeans when Camel is done with the managed objects.
if (mbContainer != null) {
this.removeServerMBean(connectorRef.server);
//mbContainer.removeBean(connectorRef.connector);
}
}
}
}
}
private String getConnectorKey(HttpCommonEndpoint endpoint) {
return endpoint.getProtocol() + ":" + endpoint.getHttpUri().getHost() + ":" + endpoint.getPort();
}
// Properties
// -------------------------------------------------------------------------
public String getSslKeyPassword() {
return sslKeyPassword;
}
/**
* The key password, which is used to access the certificate's key entry in the keystore (this is the same password that is supplied to the keystore command's -keypass option).
*/
@Metadata(description = "The key password, which is used to access the certificate's key entry in the keystore "
+ "(this is the same password that is supplied to the keystore command's -keypass option).")
public void setSslKeyPassword(String sslKeyPassword) {
this.sslKeyPassword = sslKeyPassword;
}
public String getSslPassword() {
return sslPassword;
}
/**
* The ssl password, which is required to access the keystore file (this is the same password that is supplied to the keystore command's -storepass option).
*/
@Metadata(description = "The ssl password, which is required to access the keystore file (this is the same password that is supplied to the keystore command's -storepass option).")
public void setSslPassword(String sslPassword) {
this.sslPassword = sslPassword;
}
/**
* Specifies the location of the Java keystore file, which contains the Jetty server's own X.509 certificate in a key entry.
*/
@Metadata(description = "Specifies the location of the Java keystore file, which contains the Jetty server's own X.509 certificate in a key entry.")
public void setKeystore(String sslKeystore) {
this.sslKeystore = sslKeystore;
}
public String getKeystore() {
return sslKeystore;
}
public ErrorHandler getErrorHandler() {
return errorHandler;
}
/**
* This option is used to set the ErrorHandler that Jetty server uses.
*/
@Metadata(description = "This option is used to set the ErrorHandler that Jetty server uses.")
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
protected Connector getConnector(Server server, JettyHttpEndpoint endpoint) {
Connector connector;
if ("https".equals(endpoint.getProtocol())) {
connector = getSslSocketConnector(server, endpoint);
} else {
connector = getSocketConnector(server, endpoint);
}
return connector;
}
protected Connector getSocketConnector(Server server, JettyHttpEndpoint endpoint) {
Connector answer = null;
if (socketConnectors != null) {
answer = socketConnectors.get(endpoint.getPort());
}
if (answer == null) {
answer = createConnector(server, endpoint);
}
return answer;
}
protected Connector getSslSocketConnector(Server server, JettyHttpEndpoint endpoint) {
Connector answer = null;
if (sslSocketConnectors != null) {
answer = sslSocketConnectors.get(endpoint.getPort());
}
if (answer == null) {
answer = createConnector(server, endpoint);
}
return answer;
}
protected Connector createConnector(Server server, JettyHttpEndpoint endpoint) {
// now we just use the SelectChannelConnector as the default connector
SslContextFactory sslcf = null;
// Note that this was set on the endpoint when it was constructed. It was
// either explicitly set at the component or on the endpoint, but either way,
// the value is already set. We therefore do not need to look at the component
// level SSLContextParameters again in this method.
SSLContextParameters endpointSslContextParameters = endpoint.getSslContextParameters();
if (endpointSslContextParameters != null) {
try {
sslcf = createSslContextFactory(endpointSslContextParameters);
} catch (Exception e) {
throw new RuntimeCamelException(e);
}
} else if ("https".equals(endpoint.getProtocol())) {
sslcf = new SslContextFactory();
String keystoreProperty = System.getProperty(JETTY_SSL_KEYSTORE);
if (keystoreProperty != null) {
sslcf.setKeyStorePath(keystoreProperty);
} else if (sslKeystore != null) {
sslcf.setKeyStorePath(sslKeystore);
}
String keystorePassword = System.getProperty(JETTY_SSL_KEYPASSWORD);
if (keystorePassword != null) {
sslcf.setKeyManagerPassword(keystorePassword);
} else if (sslKeyPassword != null) {
sslcf.setKeyManagerPassword(sslKeyPassword);
}
String password = System.getProperty(JETTY_SSL_PASSWORD);
if (password != null) {
sslcf.setKeyStorePassword(password);
} else if (sslPassword != null) {
sslcf.setKeyStorePassword(sslPassword);
}
}
return createConnectorJettyInternal(server, endpoint, sslcf);
}
protected abstract AbstractConnector createConnectorJettyInternal(Server server, JettyHttpEndpoint endpoint, SslContextFactory sslcf);
private SslContextFactory createSslContextFactory(SSLContextParameters ssl) throws GeneralSecurityException, IOException {
SslContextFactory answer = new SslContextFactory();
if (ssl != null) {
answer.setSslContext(ssl.createSSLContext());
}
return answer;
}
protected boolean checkSSLContextFactoryConfig(Object instance) {
try {
Method method = instance.getClass().getMethod("checkConfig");
return (Boolean)method.invoke(instance);
} catch (NoSuchMethodException ex) {
// ignore
} catch (IllegalArgumentException e) {
// ignore
} catch (IllegalAccessException e) {
// ignore
} catch (InvocationTargetException e) {
// ignore
}
return false;
}
public Map<Integer, Connector> getSslSocketConnectors() {
return sslSocketConnectors;
}
/**
* A map which contains per port number specific SSL connectors.
*/
@Metadata(description = "A map which contains per port number specific SSL connectors.")
public void setSslSocketConnectors(Map <Integer, Connector> connectors) {
sslSocketConnectors = connectors;
}
/**
* A map which contains per port number specific HTTP connectors. Uses the same principle as sslSocketConnectors.
*/
@Metadata(description = "A map which contains per port number specific HTTP connectors. Uses the same principle as sslSocketConnectors.")
public void setSocketConnectors(Map<Integer, Connector> socketConnectors) {
this.socketConnectors = socketConnectors;
}
/**
* Creates a new {@link HttpClient} and configures its proxy/thread pool and SSL based on this
* component settings.
*
* @param endpoint the instance of JettyHttpEndpoint
* @param minThreads optional minimum number of threads in client thread pool
* @param maxThreads optional maximum number of threads in client thread pool
* @param ssl option SSL parameters
*/
public CamelHttpClient createHttpClient(JettyHttpEndpoint endpoint, Integer minThreads, Integer maxThreads, SSLContextParameters ssl) throws Exception {
SslContextFactory sslContextFactory = createSslContextFactory(ssl);
CamelHttpClient httpClient = createCamelHttpClient(sslContextFactory);
CamelContext context = endpoint.getCamelContext();
if (context != null
&& ObjectHelper.isNotEmpty(context.getProperty("http.proxyHost"))
&& ObjectHelper.isNotEmpty(context.getProperty("http.proxyPort"))) {
String host = context.getProperty("http.proxyHost");
int port = Integer.parseInt(context.getProperty("http.proxyPort"));
LOG.debug("CamelContext properties http.proxyHost and http.proxyPort detected. Using http proxy host: {} port: {}", host, port);
httpClient.setProxy(host, port);
}
if (ObjectHelper.isNotEmpty(endpoint.getProxyHost()) && endpoint.getProxyPort() > 0) {
String host = endpoint.getProxyHost();
int port = endpoint.getProxyPort();
LOG.debug("proxyHost and proxyPort options detected. Using http proxy host: {} port: {}", host, port);
httpClient.setProxy(host, port);
}
// must have both min and max
if (minThreads != null || maxThreads != null) {
// must have both options
if (minThreads == null || maxThreads == null) {
throw new IllegalArgumentException("Both min and max thread pool sizes must be provided.");
}
// use QueueThreadPool as the default bounded is deprecated (see SMXCOMP-157)
QueuedThreadPool qtp = new QueuedThreadPool();
qtp.setMinThreads(minThreads.intValue());
qtp.setMaxThreads(maxThreads.intValue());
// and we want to use daemon threads
qtp.setDaemon(true);
// let the thread names indicate they are from the client
qtp.setName("CamelJettyClient(" + ObjectHelper.getIdentityHashCode(httpClient) + ")");
httpClient.setThreadPoolOrExecutor(qtp);
}
if (LOG.isDebugEnabled()) {
if (minThreads != null) {
LOG.debug("Created HttpClient with thread pool {}-{} -> {}", new Object[]{minThreads, maxThreads, httpClient});
} else {
LOG.debug("Created HttpClient with default thread pool size -> {}", httpClient);
}
}
return httpClient;
}
protected abstract CamelHttpClient createCamelHttpClient(SslContextFactory sslContextFactory);
public Integer getHttpClientMinThreads() {
return httpClientMinThreads;
}
/**
* To set a value for minimum number of threads in HttpClient thread pool. Notice that both a min and max size must be configured.
*/
@Metadata(description = "To set a value for minimum number of threads in HttpClient thread pool. Notice that both a min and max size must be configured.")
public void setHttpClientMinThreads(Integer httpClientMinThreads) {
this.httpClientMinThreads = httpClientMinThreads;
}
public Integer getHttpClientMaxThreads() {
return httpClientMaxThreads;
}
/**
* To set a value for maximum number of threads in HttpClient thread pool. Notice that both a min and max size must be configured.
*/
@Metadata(description = "To set a value for maximum number of threads in HttpClient thread pool. Notice that both a min and max size must be configured.")
public void setHttpClientMaxThreads(Integer httpClientMaxThreads) {
this.httpClientMaxThreads = httpClientMaxThreads;
}
public Integer getMinThreads() {
return minThreads;
}
/**
* To set a value for minimum number of threads in server thread pool. Notice that both a min and max size must be configured.
*/
@Metadata(description = "To set a value for minimum number of threads in server thread pool. Notice that both a min and max size must be configured.")
public void setMinThreads(Integer minThreads) {
this.minThreads = minThreads;
}
public Integer getMaxThreads() {
return maxThreads;
}
/**
* To set a value for maximum number of threads in server thread pool. Notice that both a min and max size must be configured.
*/
@Metadata(description = "To set a value for maximum number of threads in server thread pool. Notice that both a min and max size must be configured.")
public void setMaxThreads(Integer maxThreads) {
this.maxThreads = maxThreads;
}
public ThreadPool getThreadPool() {
return threadPool;
}
/**
* To use a custom thread pool for the server. This option should only be used in special circumstances.
*/
@Metadata(description = "To use a custom thread pool for the server. This option should only be used in special circumstances.")
public void setThreadPool(ThreadPool threadPool) {
this.threadPool = threadPool;
}
public boolean isEnableJmx() {
return enableJmx;
}
/**
* If this option is true, Jetty JMX support will be enabled for this endpoint.
*/
@Metadata(description = "If this option is true, Jetty JMX support will be enabled for this endpoint.")
public void setEnableJmx(boolean enableJmx) {
this.enableJmx = enableJmx;
}
public JettyHttpBinding getJettyHttpBinding() {
return jettyHttpBinding;
}
/**
* To use a custom org.apache.camel.component.jetty.JettyHttpBinding, which are used to customize how a response should be written for the producer.
*/
@Metadata(description = "To use a custom org.apache.camel.component.jetty.JettyHttpBinding, which are used to customize how a response should be written for the producer.")
public void setJettyHttpBinding(JettyHttpBinding jettyHttpBinding) {
this.jettyHttpBinding = jettyHttpBinding;
}
/**
* Not to be used - use JettyHttpBinding instead.
*/
@Override
@Metadata(description = "Not to be used - use JettyHttpBinding instead.")
public void setHttpBinding(HttpBinding httpBinding) {
throw new IllegalArgumentException("Not to be used - use JettyHttpBinding instead.");
}
/**
* Jetty component does not use HttpConfiguration.
*/
@Override
@Metadata(description = "Jetty component does not use HttpConfiguration.")
public void setHttpConfiguration(HttpConfiguration httpConfiguration) {
throw new IllegalArgumentException("Jetty component does not use HttpConfiguration.");
}
public synchronized MBeanContainer getMbContainer() {
// If null, provide the default implementation.
if (mbContainer == null) {
MBeanServer mbs = null;
final ManagementStrategy mStrategy = this.getCamelContext().getManagementStrategy();
final ManagementAgent mAgent = mStrategy.getManagementAgent();
if (mAgent != null) {
mbs = mAgent.getMBeanServer();
}
if (mbs != null) {
mbContainer = new MBeanContainer(mbs);
startMbContainer();
} else {
LOG.warn("JMX disabled in CamelContext. Jetty JMX extensions will remain disabled.");
}
}
return this.mbContainer;
}
/**
* To use a existing configured org.eclipse.jetty.jmx.MBeanContainer if JMX is enabled that Jetty uses for registering mbeans.
*/
@Metadata(description = "To use a existing configured org.eclipse.jetty.jmx.MBeanContainer if JMX is enabled that Jetty uses for registering mbeans.")
public void setMbContainer(MBeanContainer mbContainer) {
this.mbContainer = mbContainer;
}
public Map<String, Object> getSslSocketConnectorProperties() {
return sslSocketConnectorProperties;
}
/**
* A map which contains general SSL connector properties.
*/
@Metadata(description = "A map which contains general SSL connector properties.")
public void setSslSocketConnectorProperties(Map<String, Object> sslSocketConnectorProperties) {
this.sslSocketConnectorProperties = sslSocketConnectorProperties;
}
public Map<String, Object> getSocketConnectorProperties() {
return socketConnectorProperties;
}
/**
* A map which contains general HTTP connector properties. Uses the same principle as sslSocketConnectorProperties.
*/
@Metadata(description = "A map which contains general HTTP connector properties. Uses the same principle as sslSocketConnectorProperties.")
public void setSocketConnectorProperties(Map<String, Object> socketConnectorProperties) {
this.socketConnectorProperties = socketConnectorProperties;
}
public void addSocketConnectorProperty(String key, Object value) {
if (socketConnectorProperties == null) {
socketConnectorProperties = new HashMap<String, Object>();
}
socketConnectorProperties.put(key, value);
}
public void addSslSocketConnectorProperty(String key, Object value) {
if (sslSocketConnectorProperties == null) {
sslSocketConnectorProperties = new HashMap<String, Object>();
}
sslSocketConnectorProperties.put(key, value);
}
public Long getContinuationTimeout() {
return continuationTimeout;
}
/**
* Allows to set a timeout in millis when using Jetty as consumer (server).
* By default Jetty uses 30000. You can use a value of <= 0 to never expire.
* If a timeout occurs then the request will be expired and Jetty will return back a http error 503 to the client.
* This option is only in use when using Jetty with the Asynchronous Routing Engine.
*/
@Metadata(description = "Allows to set a timeout in millis when using Jetty as consumer (server)."
+ " By default Jetty uses 30000. You can use a value of <= 0 to never expire."
+ " If a timeout occurs then the request will be expired and Jetty will return back a http error 503 to the client."
+ " This option is only in use when using Jetty with the Asynchronous Routing Engine.")
public void setContinuationTimeout(Long continuationTimeout) {
this.continuationTimeout = continuationTimeout;
}
public boolean isUseContinuation() {
return useContinuation;
}
/**
* Whether or not to use Jetty continuations for the Jetty Server.
*/
@Metadata(description = "Whether or not to use Jetty continuations for the Jetty Server.")
public void setUseContinuation(boolean useContinuation) {
this.useContinuation = useContinuation;
}
public SSLContextParameters getSslContextParameters() {
return sslContextParameters;
}
/**
* To configure security using SSLContextParameters
*/
@Metadata(description = "To configure security using SSLContextParameters")
public void setSslContextParameters(SSLContextParameters sslContextParameters) {
this.sslContextParameters = sslContextParameters;
}
public Integer getResponseBufferSize() {
return responseBufferSize;
}
/**
* Allows to configure a custom value of the response buffer size on the Jetty connectors.
*/
@Metadata(description = "Allows to configure a custom value of the response buffer size on the Jetty connectors.")
public void setResponseBufferSize(Integer responseBufferSize) {
this.responseBufferSize = responseBufferSize;
}
public Integer getRequestBufferSize() {
return requestBufferSize;
}
/**
* Allows to configure a custom value of the request buffer size on the Jetty connectors.
*/
@Metadata(description = "Allows to configure a custom value of the request buffer size on the Jetty connectors.")
public void setRequestBufferSize(Integer requestBufferSize) {
this.requestBufferSize = requestBufferSize;
}
public Integer getRequestHeaderSize() {
return requestHeaderSize;
}
/**
* Allows to configure a custom value of the request header size on the Jetty connectors.
*/
@Metadata(description = "Allows to configure a custom value of the request header size on the Jetty connectors.")
public void setRequestHeaderSize(Integer requestHeaderSize) {
this.requestHeaderSize = requestHeaderSize;
}
public Integer getResponseHeaderSize() {
return responseHeaderSize;
}
/**
* Allows to configure a custom value of the response header size on the Jetty connectors.
*/
@Metadata(description = "Allows to configure a custom value of the response header size on the Jetty connectors.")
public void setResponseHeaderSize(Integer responseHeaderSize) {
this.responseHeaderSize = responseHeaderSize;
}
public String getProxyHost() {
return proxyHost;
}
/**
* To use a http proxy to configure the hostname.
*/
@Metadata(description = "To use a http proxy to configure the hostname.")
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public Integer getProxyPort() {
return proxyPort;
}
/**
* To use a http proxy to configure the port number.
*/
@Metadata(description = "To use a http proxy to configure the port number.")
public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
}