-
Notifications
You must be signed in to change notification settings - Fork 183
/
JettyServerImpl.java
979 lines (877 loc) · 32.6 KB
/
JettyServerImpl.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
/* Copyright 2007 Alin Dreghiciu.
*
* Licensed 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.ops4j.pax.web.service.jetty.internal;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EventListener;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.servlet.ServletException;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletMapping;
import org.eclipse.jetty.util.ArrayUtil;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.eclipse.jetty.xml.XmlConfiguration;
import org.ops4j.pax.swissbox.core.BundleClassLoader;
import org.ops4j.pax.swissbox.core.ContextClassLoaderUtils;
import org.ops4j.pax.web.service.spi.LifeCycle;
import org.ops4j.pax.web.service.spi.model.ContainerInitializerModel;
import org.ops4j.pax.web.service.spi.model.ContextModel;
import org.ops4j.pax.web.service.spi.model.ErrorPageModel;
import org.ops4j.pax.web.service.spi.model.EventListenerModel;
import org.ops4j.pax.web.service.spi.model.FilterModel;
import org.ops4j.pax.web.service.spi.model.ResourceModel;
import org.ops4j.pax.web.service.spi.model.SecurityConstraintMappingModel;
import org.ops4j.pax.web.service.spi.model.ServerModel;
import org.ops4j.pax.web.service.spi.model.ServletModel;
import org.ops4j.pax.web.service.spi.model.WelcomeFileModel;
import org.ops4j.pax.web.service.spi.util.ResourceDelegatingBundleClassLoader;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
import org.osgi.service.http.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class JettyServerImpl implements JettyServer {
private static final Logger LOG = LoggerFactory
.getLogger(JettyServerImpl.class);
private final JettyServerWrapper server;
private Bundle bundle;
private MBeanContainer mBeanContainer;
private Comparator<?> priorityComparator;
JettyServerImpl(final ServerModel serverModel, Bundle bundle) {
this(serverModel, bundle, null, null);
}
public JettyServerImpl(final ServerModel serverModel, Bundle bundle, Comparator<?> priorityComparator, ThreadPool threadPool) {
server = new JettyServerWrapper(serverModel, threadPool);
this.bundle = bundle;
this.priorityComparator = priorityComparator;
}
@Override
public void start() {
LOG.debug("Starting " + this);
try {
// PAXWEB-193 suggested we should open this up for external
// configuration
URL jettyResource = getServerConfigURL();
if (jettyResource == null) {
jettyResource = getClass().getResource("/jetty.xml");
}
File serverConfigurationFile = getServerConfigDir();
if (serverConfigurationFile != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("server configuration file location: "
+ serverConfigurationFile);
}
if (!serverConfigurationFile.isDirectory()
&& serverConfigurationFile.canRead()) {
if (LOG.isDebugEnabled()) {
LOG.debug("server configuration directory exists and is readable");
}
String fileName = serverConfigurationFile.getName();
if (fileName.equalsIgnoreCase("jetty.xml")) {
jettyResource = serverConfigurationFile.toURI().toURL();
} else {
LOG.warn("No configuration file found with name jetty.xml. Filename given: {}, will read this one instead. ", fileName);
jettyResource = serverConfigurationFile.toURI().toURL();
}
} else {
LOG.warn("server configuration file location is invalid");
}
}
if (jettyResource != null) {
ClassLoader loader = Thread.currentThread()
.getContextClassLoader();
try {
// first find XmlConfiguration class' CL to set it as TCCL when performing static
// initialization of XmlConfiguration in order to not leak
// org.eclipse.jetty.xml.XmlConfiguration.__factoryLoader.loader
ClassLoader jettyXmlCl = null;
for (Bundle b : bundle.getBundleContext().getBundles()) {
if ("org.eclipse.jetty.xml".equals(b.getSymbolicName())) {
jettyXmlCl = b.adapt(BundleWiring.class).getClassLoader();
break;
}
}
// TCCL to perform static initialization of XmlConfiguration
Thread.currentThread().setContextClassLoader(jettyXmlCl);
LOG.debug("Configure using resource " + jettyResource);
XmlConfiguration configuration = new XmlConfiguration(
jettyResource);
// TCCL to run configure (this is where objects defined in jetty.xml are created)
Thread.currentThread().setContextClassLoader(
getClass().getClassLoader());
// configuration.configure(m_server);
Method method = XmlConfiguration.class.getMethod(
"configure", Object.class);
method.invoke(configuration, server);
} finally {
Thread.currentThread().setContextClassLoader(loader);
}
}
// PAXWEB-568
//CHECKSTYLE:OFF
// Setup JMX
try {
Class.forName("javax.management.JMX");
Class.forName("org.eclipse.jetty.jmx.MBeanContainer");
mBeanContainer = new MBeanContainer(
ManagementFactory.getPlatformMBeanServer());
server.addBean(mBeanContainer);
} catch (Throwable t) {
// no jmx available just ignore it!
LOG.debug("No JMX available will keep going");
}
//CHECKSTYLE:ON
Connector[] connectors = server.getConnectors();
if (connectors != null) {
for (Connector connector : connectors) {
LOG.info(
"Pax Web available at [{}]:[{}]",
((ServerConnector) connector).getHost() == null ? "0.0.0.0"
: ((ServerConnector) connector).getHost(),
((ServerConnector) connector).getPort());
}
} else {
LOG.info("Pax Web is started with it's default configuration most likely it's listening on port 8181");
}
//CHECKSTYLE:OFF
} catch (Exception e) {
LOG.error("Exception while starting Jetty", e);
throw new RuntimeException("Exception while starting Jetty", e);
}
//CHECKSTYLE:ON
}
@Override
public void stop() {
LOG.debug("Stopping " + this);
try {
// Tear down JMX
try {
Class.forName("javax.management.JMX");
if (mBeanContainer != null) {
server.removeBean(mBeanContainer);
// see https://github.com/eclipse/jetty.project/issues/851
// please do not remove this line even after upgrading to fixed Jetty
// because mBeanContainer won't be destroyed anyway during server.destroy()
// (due to above removeBean())
mBeanContainer.destroy();
mBeanContainer = null;
}
} catch (Throwable t) {
// no jmx available just ignore it!
LOG.debug("No JMX available will keep going");
}
server.stop();
Handler[] childHandlers = server.getChildHandlers();
for (Handler handler : childHandlers) {
handler.stop();
}
// PAXWEB-1127 - stop qtp after stopping server, as we've started it manually
if (server.getThreadPool() instanceof org.eclipse.jetty.util.component.LifeCycle) {
((org.eclipse.jetty.util.component.LifeCycle) server.getThreadPool()).stop();
}
server.destroy();
//CHECKSTYLE:OFF
} catch (Exception e) {
LOG.error("Exception while stopping Jetty:", e);
}
//CHECKSTYLE:ON
}
@Override
public void addConnector(final Connector connector) {
LOG.info("Pax Web available at [{}]:[{}]",
((ServerConnector) connector).getHost() == null ? "0.0.0.0"
: ((ServerConnector) connector).getHost(),
((ServerConnector) connector).getPort());
server.addConnector(connector);
if (priorityComparator != null) {
Connector[] connectors = server.getConnectors();
@SuppressWarnings("unchecked")
Comparator<Connector> comparator = (Comparator<Connector>) priorityComparator;
Arrays.sort(connectors, comparator);
}
}
@Override
public Connector[] getConnectors() {
return server.getConnectors();
}
@Override
public void removeConnector(final Connector connector) {
LOG.info("Removing connection for [{}]:[{}]",
((ServerConnector) connector).getHost() == null ? "0.0.0.0"
: ((ServerConnector) connector).getHost(),
((ServerConnector) connector).getPort());
server.removeConnector(connector);
}
@Override
public void addHandler(Handler handler) {
HandlerCollection handlerCollection = server.getRootHandlerCollection();
handlerCollection.addHandler(handler);
if (priorityComparator != null) {
Handler[] handlers = handlerCollection.getHandlers();
@SuppressWarnings("unchecked")
Comparator<Handler> comparator = (Comparator<Handler>) priorityComparator;
Arrays.sort(handlers, comparator);
}
}
@Override
public Handler[] getHandlers() {
return server.getRootHandlerCollection().getHandlers();
}
@Override
public void removeHandler(Handler handler) {
server.getRootHandlerCollection().removeHandler(handler);
}
@Override
public void configureContext(final Map<String, Object> attributes,
final Integer sessionTimeout, final String sessionCookie,
final String sessionDomain, final String sessionPath,
final String sessionUrl, final Boolean sessionCookieHttpOnly,
final Boolean sessionCookieSecure, final String workerName,
final Boolean lazyLoad, final String storeDirectory,
final Integer maxAge, final Boolean showStacks) {
server.configureContext(attributes, sessionTimeout, sessionCookie,
sessionDomain, sessionPath, sessionUrl, sessionCookieHttpOnly,
sessionCookieSecure, workerName, lazyLoad, storeDirectory, maxAge, showStacks);
}
@Override
public LifeCycle getContext(final ContextModel model) {
final ServletContextHandler context = server.getOrCreateContext(model);
return new LifeCycle() {
@Override
public void start() throws Exception {
// PAXWEB-1084 - start qtp before starting first context
if (server.getThreadPool() instanceof org.eclipse.jetty.util.component.LifeCycle) {
((org.eclipse.jetty.util.component.LifeCycle) server.getThreadPool()).start();
}
// Fixfor PAXWEB-725
ClassLoader classLoader = context.getClassLoader();
List<Bundle> bundles = ((ResourceDelegatingBundleClassLoader) classLoader).getBundles();
BundleClassLoader parentClassLoader
= new BundleClassLoader(bundle);
ResourceDelegatingBundleClassLoader containerSpecificClassLoader = new ResourceDelegatingBundleClassLoader(bundles, parentClassLoader);
context.setClassLoader(containerSpecificClassLoader);
if (!context.isStarted()) {
context.start();
}
boolean hasDefault = false;
for (ServletMapping mapping : context.getServletHandler().getServletMappings()) {
if (mapping.isDefault()) {
hasDefault = true;
break;
}
}
if (!hasDefault) {
ResourceServlet servlet = new ResourceServlet(model.getHttpContext(), model.getContextName(), "/", "default");
ResourceModel resourceModel = new ResourceModel(model, servlet, "/", "default");
addServlet(resourceModel);
}
// Fixfor PAXWEB-751
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(
getClass().getClassLoader());
server.start();
// PAXWEB-1127: load org.eclipse.jetty.util.FutureCallback class, so it's there when we shutdown connectors
// to avoid NPE in org.apache.felix.framework.BundleWiringImpl.searchImports()
ServerConnector.class.getClassLoader().loadClass("org.eclipse.jetty.util.FutureCallback");
// load some other required classes
try {
QueuedThreadPool.class.getClassLoader().loadClass("org.eclipse.jetty.util.thread.QueuedThreadPool$1");
} catch (java.lang.Exception exception) {
}
try {
QueuedThreadPool.class.getClassLoader().loadClass("org.eclipse.jetty.util.thread.QueuedThreadPool$2");
} catch (java.lang.Exception exception) {
}
try {
QueuedThreadPool.class.getClassLoader().loadClass("org.eclipse.jetty.util.thread.QueuedThreadPool$3");
} catch (java.lang.Exception exception) {
}
} finally {
Thread.currentThread().setContextClassLoader(loader);
}
for (Connector connector : server.getConnectors()) {
if (connector.isStopped()) {
connector.start();
}
}
}
@Override
public void stop() throws Exception {
context.stop();
}
};
}
@Override
public synchronized void addServlet(final ServletModel model) {
LOG.debug("Adding servlet [" + model + "]");
final ServletMapping mapping = new ServletMapping();
mapping.setServletName(model.getName());
mapping.setPathSpecs(model.getUrlPatterns());
if (model instanceof ResourceModel
&& "default".equalsIgnoreCase(model.getName())) {
// this is a default resource
mapping.setDefault(true);
}
final ServletContextHandler context = server.getOrCreateContext(model);
final ServletHandler servletHandler = context.getServletHandler();
if (servletHandler == null) {
throw new IllegalStateException(
"Internal error: Cannot find the servlet holder");
}
final ServletHolder holder;
if (model.getServlet() == null) {
holder = new ServletHolder(model.getServletClass());
} else {
holder = new ServletHolder(model.getServlet());
}
holder.setName(model.getName());
if (model.getInitParams() != null) {
holder.setInitParameters(model.getInitParams());
}
if (model.getAsyncSupported() != null) {
holder.setAsyncSupported(model.getAsyncSupported());
}
if (model.getLoadOnStartup() != null) {
holder.setInitOrder(model.getLoadOnStartup());
}
if (model.getMultipartConfig() != null) {
holder.getRegistration().setMultipartConfig(model.getMultipartConfig());
}
// Jetty does not set the context class loader on adding the filters so
// we do that instead
try {
ContextClassLoaderUtils.doWithClassLoader(context.getClassLoader(),
new Callable<Void>() {
@Override
public Void call() {
servletHandler.addServlet(holder);
servletHandler.addServletMapping(mapping);
return null;
}
});
if (holder.isStarted()) {
// initialize servlet
holder.getServlet();
}
//CHECKSTYLE:OFF
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
LOG.error("Ignored exception during servlet registration", e);
}
//CHECKSTYLE:ON
}
@Override
public synchronized void removeServlet(final ServletModel model) {
LOG.debug("Removing servlet [" + model + "]");
// jetty does not provide a method for removing a servlet so we have to
// do it by our own
// the facts below are found by analyzing ServletHolder implementation
boolean removed = false;
final ServletContextHandler context = server.getContext(model
.getContextModel().getHttpContext());
if (context == null) {
return; // context is already removed so no need for deregistration
}
final ServletHandler servletHandler = context.getServletHandler();
final ServletHolder[] holders = servletHandler.getServlets();
if (holders != null) {
final ServletHolder holder = servletHandler.getServlet(model
.getName());
if (holder != null) {
servletHandler.setServlets(ArrayUtil.removeFromArray(holders, holder));
// we have to find the servlet mapping by hand :( as there is no
// method provided by jetty
// and the remove is done based on equals, that is not
// implemented by servletmapping
// so it is == based.
ServletMapping[] mappings = servletHandler.getServletMappings();
if (mappings != null) {
ServletMapping mapping = null;
for (ServletMapping item : mappings) {
if (holder.getName().equals(item.getServletName())) {
mapping = item;
break;
}
}
if (mapping != null) {
servletHandler
.setServletMappings(ArrayUtil.removeFromArray(mappings, mapping));
removed = true;
}
}
// if servlet is still started stop the servlet holder
// (=servlet.destroy()) as Jetty will not do that
LOG.debug("Stopping servlet in Holder");
try {
ContextClassLoaderUtils.doWithClassLoader(
context.getClassLoader(), new Callable<Void>() {
@Override
public Void call() throws Exception {
holder.stop();
return null;
}
});
//CHECKSTYLE:OFF
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
LOG.warn("Exception during unregistering of servlet ["
+ model + "]");
}
//CHECKSTYLE:ON
}
}
removeContext(model.getContextModel().getHttpContext());
if (!removed) {
throw new IllegalStateException(model + " was not found");
}
}
@Override
public synchronized void addEventListener(final EventListenerModel model) {
server.getOrCreateContext(model).addEventListener(
model.getEventListener());
}
@Override
public synchronized void removeEventListener(final EventListenerModel model) {
final ServletContextHandler context = server.getContext(model
.getContextModel().getHttpContext());
if (context == null) {
return; // Obviously context is already destroyed
}
final List<EventListener> listeners = new ArrayList<>(
Arrays.asList(context.getEventListeners()));
EventListener listener = model.getEventListener();
listeners.remove(listener);
context.setEventListeners(listeners.toArray(new EventListener[listeners
.size()]));
removeContext(model.getContextModel().getHttpContext());
}
@Override
public synchronized void removeContext(final HttpContext httpContext) {
server.removeContext(httpContext, false);
}
@Override
public synchronized void removeContext(HttpContext httpContext, boolean force) {
server.removeContext(httpContext, force);
}
@Override
public synchronized void addFilter(final FilterModel model) {
LOG.debug("Adding filter model [" + model + "]");
final FilterMapping mapping = new FilterMapping();
mapping.setFilterName(model.getName());
if (model.getUrlPatterns() != null && model.getUrlPatterns().length > 0) {
mapping.setPathSpecs(model.getUrlPatterns());
}
if (model.getServletNames() != null
&& model.getServletNames().length > 0) {
mapping.setServletNames(model.getServletNames());
}
// set-up dispatcher
int dispatcher = FilterMapping.DEFAULT;
for (String d : model.getDispatcher()) {
//dispatcher = FilterMapping.dispatch(baseRequest.getDispatcherType());
/*
DispatcherType type = DispatcherType.valueOf(d);
dispatcher |= FilterMapping.dispatch(type);
*/
if ("ALL".equalsIgnoreCase(d)) {
dispatcher |= FilterMapping.ALL;
} else if ("ASYNC".equalsIgnoreCase(d)) {
dispatcher |= FilterMapping.ASYNC;
} else if ("DEFAULT".equalsIgnoreCase(d)) {
dispatcher |= FilterMapping.DEFAULT;
} else if ("ERROR".equalsIgnoreCase(d)) {
dispatcher |= FilterMapping.ERROR;
} else if ("FORWARD".equalsIgnoreCase(d)) {
dispatcher |= FilterMapping.FORWARD;
} else if ("INCLUDE".equalsIgnoreCase(d)) {
dispatcher |= FilterMapping.INCLUDE;
} else if ("REQUEST".equalsIgnoreCase(d)) {
dispatcher |= FilterMapping.REQUEST;
}
}
mapping.setDispatches(dispatcher);
final ServletContextHandler context = server.getOrCreateContext(model);
final ServletHandler servletHandler = context.getServletHandler();
if (servletHandler == null) {
throw new IllegalStateException(
"Internal error: Cannot find the servlet holder");
}
final FilterHolder holder;
if (model.getFilter() == null) {
holder = new FilterHolder(model.getFilterClass());
} else {
holder = new FilterHolder(model.getFilter());
}
holder.setName(model.getName());
if (model.getInitParams() != null) {
holder.setInitParameters(model.getInitParams());
}
holder.setAsyncSupported(model.isAsyncSupported());
// Jetty does not set the context class loader on adding the filters so
// we do that instead
try {
ContextClassLoaderUtils.doWithClassLoader(context.getClassLoader(),
new Callable<Void>() {
@Override
public Void call() {
servletHandler.addFilter(holder, mapping);
return null;
}
});
//CHECKSTYLE:OFF
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
LOG.error("Ignored exception during filter registration", e);
}
//CHECKSTYLE:OFF
}
@Override
public synchronized void removeFilter(FilterModel model) {
LOG.debug("Removing filter model [" + model + "]");
final ServletContextHandler context = server.getContext(model
.getContextModel().getHttpContext());
if (context == null) {
return; // Obviously no context available anymore the server is
// already down
}
final ServletHandler servletHandler = context.getServletHandler();
// first remove filter mappings for the removed filter
final FilterMapping[] filterMappings = servletHandler
.getFilterMappings();
final List<FilterMapping> newFilterMappings = new ArrayList<>();
for (FilterMapping filterMapping : filterMappings) {
if (filterMapping.getFilterName().equals(model.getName())) {
if (newFilterMappings.isEmpty()) {
Collections.addAll(newFilterMappings, filterMappings);
}
newFilterMappings.remove(filterMapping);
}
}
// Jetty does not set the context class loader on adding the filters so
// we do that instead
try {
ContextClassLoaderUtils.doWithClassLoader(context.getClassLoader(),
new Callable<Void>() {
@Override
public Void call() {
servletHandler.setFilterMappings(newFilterMappings
.toArray(new FilterMapping[newFilterMappings
.size()]));
return null;
}
});
// CHECKSTYLE:OFF
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
LOG.error("Ignored exception during filter registration", e);
}
// CHECKSTYLE:OFF
// then remove the filter
final FilterHolder filterHolder = servletHandler.getFilter(model
.getName());
if (filterHolder == null) {
return; // The filter has already been removed so nothing do to anymore
}
final FilterHolder[] filterHolders = servletHandler.getFilters();
final FilterHolder[] newFilterHolders = ArrayUtil.removeFromArray(filterHolders, filterHolder);
servletHandler.setFilters(newFilterHolders);
// if filter is still started stop the filter (=filter.destroy()) as
// Jetty will not do that
if (filterHolder.isStarted()) {
try {
ContextClassLoaderUtils.doWithClassLoader(
context.getClassLoader(), new Callable<Void>() {
@Override
public Void call() throws Exception {
filterHolder.stop();
return null;
}
});
//CHECKSTYLE:OFF
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
LOG.warn("Exception during unregistering of filter ["
+ filterHolder.getFilter() + "]");
}
//CHECKSTYLE:ON
}
removeContext(model.getContextModel().getHttpContext());
}
@Override
public synchronized void addErrorPage(final ErrorPageModel model) {
final ServletContextHandler context = server.getOrCreateContext(model);
final ErrorPageErrorHandler errorPageHandler = (ErrorPageErrorHandler) context
.getErrorHandler();
if (errorPageHandler == null) {
throw new IllegalStateException(
"Internal error: Cannot find the error handler. Please report.");
}
try {
int code = Integer.parseInt(model.getError());
errorPageHandler.addErrorPage(code, model.getLocation());
} catch (NumberFormatException nfe) {
if (ErrorPageModel.ERROR_PAGE.equalsIgnoreCase(model.getError())) {
errorPageHandler.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, model.getLocation());
} else {
// 140.4.1 Error Pages
if ("4xx".equals(model.getError())) {
errorPageHandler
.addErrorPage(400, 499, model.getLocation());
} else if ("5xx".equals(model.getError())) {
errorPageHandler
.addErrorPage(500, 599, model.getLocation());
} else {
// OK, not a number must be a class then
errorPageHandler
.addErrorPage(model.getError(), model.getLocation());
}
}
}
}
@Override
public synchronized void removeErrorPage(final ErrorPageModel model) {
final ServletContextHandler context = server.getContext(model
.getContextModel().getHttpContext());
if (context == null) {
return;// Obviously context is already removed
}
final ErrorPageErrorHandler errorPageHandler = (ErrorPageErrorHandler) context
.getErrorHandler();
if (errorPageHandler == null) {
throw new IllegalStateException(
"Internal error: Cannot find the error handler. Please report.");
}
final Map<String, String> errorPages = errorPageHandler.getErrorPages();
if (errorPages != null) {
errorPages.remove(model.getError());
}
removeContext(model.getContextModel().getHttpContext());
}
// PAXWEB-123: try to register WelcomeFiles differently
@Override
public synchronized void addWelcomeFiles(final WelcomeFileModel model) {
final ServletContextHandler context = server
.getOrCreateContext(model);
context.setWelcomeFiles(model.getWelcomeFiles());
if (context.getServletHandler() == null || context.getServletHandler().getServletMappings() == null) {
return;
}
for (ServletMapping mapping : context.getServletHandler().getServletMappings()) {
ServletHolder servlet = context.getServletHandler().getServlet(mapping.getServletName());
try {
if (servlet.getServlet() instanceof ResourceServlet) {
LOG.debug("Reinitializing {} with new welcome files {}", servlet, Arrays.asList(model.getWelcomeFiles()));
servlet.getServlet().init(servlet.getServlet().getServletConfig());
}
} catch (ServletException e) {
LOG.warn("Problem reinitializing welcome files of default servlet", e);
}
}
}
@Override
public synchronized void removeWelcomeFiles(final WelcomeFileModel model) {
final ServletContextHandler context = server.getContext(model
.getContextModel().getHttpContext());
if (context == null) {
return;// Obviously context is already removed
}
String[] welcomeFiles = context.getWelcomeFiles();
List<String> welcomeFileList = new ArrayList<>(Arrays.asList(welcomeFiles));
welcomeFileList.removeAll(Arrays.asList(model.getWelcomeFiles()));
removeContext(model.getContextModel().getHttpContext());
}
// PAXWEB-123: done
// PAXWEB-210: create security constraints
@Override
public void addSecurityConstraintMappings(
final SecurityConstraintMappingModel model) {
final ServletContextHandler context = server.getOrCreateContext(model);
final SecurityHandler securityHandler = context.getSecurityHandler();
if (securityHandler == null) {
throw new IllegalStateException(
"Internal error: Cannot find the security handler. Please report.");
}
String mappingMethod = model.getMapping();
String constraintName = model.getConstraintName();
String url = model.getUrl();
String dataConstraint = model.getDataConstraint();
List<String> roles = model.getRoles();
boolean authentication = model.isAuthentication();
ConstraintMapping newConstraintMapping = new ConstraintMapping();
newConstraintMapping.setMethod(mappingMethod);
newConstraintMapping.setPathSpec(url);
Constraint constraint = new Constraint();
constraint.setAuthenticate(authentication);
constraint.setName(constraintName);
constraint.setRoles(roles.toArray(new String[roles.size()]));
if (dataConstraint == null || "NONE".equals(dataConstraint)) {
constraint.setDataConstraint(Constraint.DC_NONE);
} else if ("INTEGRAL".equals(dataConstraint)) {
constraint.setDataConstraint(Constraint.DC_INTEGRAL);
} else if ("CONFIDENTIAL".equals(dataConstraint)) {
constraint.setDataConstraint(Constraint.DC_CONFIDENTIAL);
} else {
LOG.warn("Unknown user-data-constraint:" + dataConstraint);
constraint.setDataConstraint(Constraint.DC_CONFIDENTIAL);
}
newConstraintMapping.setConstraint(constraint);
((ConstraintSecurityHandler) securityHandler)
.addConstraintMapping(newConstraintMapping);
}
@Override
public void addServletContainerInitializer(ContainerInitializerModel model) {
}
@Override
public void removeSecurityConstraintMappings(
final SecurityConstraintMappingModel model) {
final ServletContextHandler context = server.getContext(model
.getContextModel().getHttpContext());
if (context == null) {
return; // context already gone
}
final SecurityHandler securityHandler = context.getSecurityHandler();
if (securityHandler == null) {
throw new IllegalStateException(
"Internal error: Cannot find the security handler. Please report.");
}
List<ConstraintMapping> constraintMappings = ((ConstraintSecurityHandler) securityHandler)
.getConstraintMappings();
for (ConstraintMapping constraintMapping : constraintMappings) {
boolean urlMatch = constraintMapping.getPathSpec()
.equalsIgnoreCase(model.getUrl());
boolean methodMatch = (constraintMapping.getMethod() == null && model.getMapping() == null)
|| (constraintMapping.getMethod().equalsIgnoreCase(model.getMapping()));
if (urlMatch && methodMatch) {
constraintMappings.remove(constraintMapping);
}
}
removeContext(model.getContextModel().getHttpContext());
}
@SuppressWarnings("deprecation")
@Override
public void configureRequestLog(ConfigureRequestLogParameter configureRequestParameters) {
String directory = configureRequestParameters.dir;
RequestLogHandler requestLogHandler = new RequestLogHandler();
// TODO: Improve that to set the path of the LOG relative to
// $JETTY_HOME
if (directory == null || directory.isEmpty()) {
directory = "./logs/";
}
File file = new File(directory);
if (!file.exists()) {
file.mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
LOG.error("can't create NCSARequestLog", e);
}
}
LOG.info("NCSARequestlogging is using the following directory: {}",
file.getAbsolutePath());
if (!directory.endsWith("/")) {
directory += "/";
}
NCSARequestLog requestLog = new NCSARequestLog(directory + configureRequestParameters.format);
requestLog.setRetainDays(Integer.parseInt(configureRequestParameters.retainDays));
requestLog.setAppend(configureRequestParameters.append);
requestLog.setExtended(configureRequestParameters.extend);
requestLog.setLogDispatch(configureRequestParameters.dispatch);
requestLog.setLogTimeZone(configureRequestParameters.timeZone);
requestLog.setLogLatency(configureRequestParameters.logLatency);
requestLog.setLogCookies(configureRequestParameters.logCookies);
requestLog.setLogServer(configureRequestParameters.logServer);
requestLogHandler.setRequestLog(requestLog);
server.getRootHandlerCollection().addHandler(requestLogHandler);
}
@Override
public String toString() {
return JettyServerImpl.class.getSimpleName() + "{}";
}
@Override
public void setServerConfigDir(File serverConfigDir) {
server.setServerConfigDir(serverConfigDir);
}
@Override
public File getServerConfigDir() {
return server.getServerConfigDir();
}
@Override
public void setServerConfigURL(URL serverConfigURL) {
server.setServerConfigURL(serverConfigURL);
}
@Override
public URL getServerConfigURL() {
return server.getServerConfigURL();
}
@Override
public void setDefaultAuthMethod(String defaultAuthMethod) {
server.setDefaultAuthMethod(defaultAuthMethod);
}
@Override
public String getDefaultAuthMethod() {
return server.getDefaultAuthMethod();
}
@Override
public void setDefaultRealmName(String defaultRealmName) {
server.setDefaultRealmName(defaultRealmName);
}
@Override
public String getDefaultRealmName() {
return server.getDefaultRealmName();
}
@Override
public JettyServerWrapper getServer() {
return server;
}
}