-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
ContextHandler.java
3095 lines (2735 loc) · 100 KB
/
ContextHandler.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
//
// ========================================================================
// Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.server.handler;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspConfigDescriptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionIdListener;
import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.server.ClassLoaderDump;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Dispatcher;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.HandlerContainer;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.AttributesMap;
import org.eclipse.jetty.util.Index;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.component.DumpableCollection;
import org.eclipse.jetty.util.component.Graceful;
import org.eclipse.jetty.util.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ContextHandler.
*
* <p>
* This handler wraps a call to handle by setting the context and servlet path, plus setting the context classloader.
* </p>
* <p>
* If the context init parameter {@code org.eclipse.jetty.server.context.ManagedAttributes} is set to a comma separated list of names, then they are treated as
* context attribute names, which if set as attributes are passed to the servers Container so that they may be managed with JMX.
* </p>
* <p>
* The maximum size of a form that can be processed by this context is controlled by the system properties {@code org.eclipse.jetty.server.Request.maxFormKeys} and
* {@code org.eclipse.jetty.server.Request.maxFormContentSize}. These can also be configured with {@link #setMaxFormContentSize(int)} and {@link #setMaxFormKeys(int)}
* </p>
* <p>
* The executor is made available via a context attributed {@code org.eclipse.jetty.server.Executor}.
* </p>
* <p>
* By default, the context is created with alias checkers for {@link AllowSymLinkAliasChecker} (unix only) and {@link ApproveNonExistentDirectoryAliases}. If
* these alias checkers are not required, then {@link #clearAliasChecks()} or {@link #setAliasChecks(List)} should be called.
* </p>
*/
@ManagedObject("URI Context")
public class ContextHandler extends ScopedHandler implements Attributes, Graceful
{
public static final int SERVLET_MAJOR_VERSION = 4;
public static final int SERVLET_MINOR_VERSION = 0;
public static final Class<?>[] SERVLET_LISTENER_TYPES =
{
ServletContextListener.class,
ServletContextAttributeListener.class,
ServletRequestListener.class,
ServletRequestAttributeListener.class,
HttpSessionIdListener.class,
HttpSessionListener.class,
HttpSessionAttributeListener.class
};
public static final int DEFAULT_LISTENER_TYPE_INDEX = 1;
public static final int EXTENDED_LISTENER_TYPE_INDEX = 0;
private static final String UNIMPLEMENTED_USE_SERVLET_CONTEXT_HANDLER = "Unimplemented {} - use org.eclipse.jetty.servlet.ServletContextHandler";
private static final Logger LOG = LoggerFactory.getLogger(ContextHandler.class);
private static final ThreadLocal<Context> __context = new ThreadLocal<>();
private static String __serverInfo = "jetty/" + Server.getVersion();
public static final String MANAGED_ATTRIBUTES = "org.eclipse.jetty.server.context.ManagedAttributes";
public static final String MAX_FORM_KEYS_KEY = "org.eclipse.jetty.server.Request.maxFormKeys";
public static final String MAX_FORM_CONTENT_SIZE_KEY = "org.eclipse.jetty.server.Request.maxFormContentSize";
public static final int DEFAULT_MAX_FORM_KEYS = 1000;
public static final int DEFAULT_MAX_FORM_CONTENT_SIZE = 200000;
/**
* Get the current ServletContext implementation.
*
* @return ServletContext implementation
*/
public static Context getCurrentContext()
{
return __context.get();
}
public static ContextHandler getContextHandler(ServletContext context)
{
if (context instanceof ContextHandler.Context)
return ((ContextHandler.Context)context).getContextHandler();
Context c = getCurrentContext();
if (c != null)
return c.getContextHandler();
return null;
}
public static String getServerInfo()
{
return __serverInfo;
}
public static void setServerInfo(String serverInfo)
{
__serverInfo = serverInfo;
}
public enum ContextStatus
{
NOTSET,
INITIALIZED,
DESTROYED
}
/**
* The type of protected target match
* @see #_protectedTargets
*/
private enum ProtectedTargetType
{
EXACT,
PREFIX
}
protected ContextStatus _contextStatus = ContextStatus.NOTSET;
protected Context _scontext;
private final AttributesMap _attributes;
private final Map<String, String> _initParams;
private ClassLoader _classLoader;
private boolean _contextPathDefault = true;
private String _defaultRequestCharacterEncoding;
private String _defaultResponseCharacterEncoding;
private String _contextPath = "/";
private String _contextPathEncoded = "/";
private String _displayName;
private long _stopTimeout;
private Resource _baseResource;
private MimeTypes _mimeTypes;
private Map<String, String> _localeEncodingMap;
private String[] _welcomeFiles;
private ErrorHandler _errorHandler;
private String[] _vhosts; // Host name portion, matching _vconnectors array
private boolean[] _vhostswildcard;
private String[] _vconnectors; // connector portion, matching _vhosts array
private Logger _logger;
private boolean _allowNullPathInfo;
private int _maxFormKeys = Integer.getInteger(MAX_FORM_KEYS_KEY, DEFAULT_MAX_FORM_KEYS);
private int _maxFormContentSize = Integer.getInteger(MAX_FORM_CONTENT_SIZE_KEY, DEFAULT_MAX_FORM_CONTENT_SIZE);
private boolean _compactPath = false;
private boolean _usingSecurityManager = System.getSecurityManager() != null;
private final List<EventListener> _programmaticListeners = new CopyOnWriteArrayList<>();
private final List<ServletContextListener> _servletContextListeners = new CopyOnWriteArrayList<>();
private final List<ServletContextListener> _destroyServletContextListeners = new ArrayList<>();
private final List<ServletContextAttributeListener> _servletContextAttributeListeners = new CopyOnWriteArrayList<>();
private final List<ServletRequestListener> _servletRequestListeners = new CopyOnWriteArrayList<>();
private final List<ServletRequestAttributeListener> _servletRequestAttributeListeners = new CopyOnWriteArrayList<>();
private final List<ContextScopeListener> _contextListeners = new CopyOnWriteArrayList<>();
private final Set<EventListener> _durableListeners = new HashSet<>();
private Index<ProtectedTargetType> _protectedTargets = Index.empty(false);
private final CopyOnWriteArrayList<AliasCheck> _aliasChecks = new CopyOnWriteArrayList<>();
public enum Availability
{
STOPPED, // stopped and can't be made unavailable nor shutdown
STARTING, // starting inside of doStart. It may go to any of the next states.
AVAILABLE, // running normally
UNAVAILABLE, // Either a startup error or explicit call to setAvailable(false)
SHUTDOWN, // graceful shutdown
}
private final AtomicReference<Availability> _availability = new AtomicReference<>(Availability.STOPPED);
public ContextHandler()
{
this(null, null, null);
}
protected ContextHandler(Context context)
{
this(context, null, null);
}
public ContextHandler(String contextPath)
{
this(null, null, contextPath);
}
public ContextHandler(HandlerContainer parent, String contextPath)
{
this(null, parent, contextPath);
}
protected ContextHandler(Context context, HandlerContainer parent, String contextPath)
{
_scontext = context == null ? new Context() : context;
_attributes = new AttributesMap();
_initParams = new HashMap<>();
addAliasCheck(new ApproveNonExistentDirectoryAliases());
if (File.separatorChar == '/')
addAliasCheck(new AllowSymLinkAliasChecker());
if (contextPath != null)
setContextPath(contextPath);
if (parent instanceof HandlerWrapper)
((HandlerWrapper)parent).setHandler(this);
else if (parent instanceof HandlerCollection)
((HandlerCollection)parent).addHandler(this);
}
@Override
public void dump(Appendable out, String indent) throws IOException
{
dumpObjects(out, indent,
new ClassLoaderDump(getClassLoader()),
new DumpableCollection("handler attributes " + this, ((AttributesMap)getAttributes()).getAttributeEntrySet()),
new DumpableCollection("context attributes " + this, ((Context)getServletContext()).getAttributeEntrySet()),
new DumpableCollection("initparams " + this, getInitParams().entrySet()));
}
public Context getServletContext()
{
return _scontext;
}
/**
* @return the allowNullPathInfo true if /context is not redirected to /context/
*/
@ManagedAttribute("Checks if the /context is not redirected to /context/")
public boolean getAllowNullPathInfo()
{
return _allowNullPathInfo;
}
/**
* @param allowNullPathInfo true if /context is not redirected to /context/
*/
public void setAllowNullPathInfo(boolean allowNullPathInfo)
{
_allowNullPathInfo = allowNullPathInfo;
}
@Override
public void setServer(Server server)
{
super.setServer(server);
if (_errorHandler != null)
_errorHandler.setServer(server);
}
public boolean isUsingSecurityManager()
{
return _usingSecurityManager;
}
public void setUsingSecurityManager(boolean usingSecurityManager)
{
if (usingSecurityManager && System.getSecurityManager() == null)
throw new IllegalStateException("No security manager");
_usingSecurityManager = usingSecurityManager;
}
/**
* Set the virtual hosts for the context. Only requests that have a matching host header or fully qualified URL will be passed to that context with a
* virtual host name. A context with no virtual host names or a null virtual host name is available to all requests that are not served by a context with a
* matching virtual host name.
*
* @param vhosts Array of virtual hosts that this context responds to. A null/empty array means any hostname is acceptable. Host names may be String
* representation of IP addresses. Host names may start with '*.' to wildcard one level of names. Hosts and wildcard hosts may be followed with
* '@connectorname', in which case they will match only if the the {@link Connector#getName()} for the request also matches. If an entry is just
* '@connectorname' it will match any host if that connector was used. Note - In previous versions if one or more connectorname only entries existed
* and non of the connectors matched the handler would not match regardless of any hostname entries. If there is one or more connectorname only
* entries and one or more host only entries but no hostname and connector entries we assume the old behavior and will log a warning. The warning
* can be removed by removing the host entries that were previously being ignored, or modifying to include a hostname and connectorname entry.
*/
public void setVirtualHosts(String[] vhosts)
{
if (vhosts == null)
{
_vhosts = vhosts;
}
else
{
boolean hostMatch = false;
boolean connectorHostMatch = false;
_vhosts = new String[vhosts.length];
_vconnectors = new String[vhosts.length];
_vhostswildcard = new boolean[vhosts.length];
ArrayList<Integer> connectorOnlyIndexes = null;
for (int i = 0; i < vhosts.length; i++)
{
boolean connectorMatch = false;
_vhosts[i] = vhosts[i];
if (vhosts[i] == null)
continue;
int connectorIndex = _vhosts[i].indexOf('@');
if (connectorIndex >= 0)
{
connectorMatch = true;
_vconnectors[i] = _vhosts[i].substring(connectorIndex + 1);
_vhosts[i] = _vhosts[i].substring(0, connectorIndex);
if (connectorIndex == 0)
{
if (connectorOnlyIndexes == null)
connectorOnlyIndexes = new ArrayList<>();
connectorOnlyIndexes.add(i);
}
}
if (_vhosts[i].startsWith("*."))
{
_vhosts[i] = _vhosts[i].substring(1);
_vhostswildcard[i] = true;
}
if (_vhosts[i].isEmpty())
_vhosts[i] = null;
else
{
hostMatch = true;
connectorHostMatch = connectorHostMatch || connectorMatch;
}
_vhosts[i] = normalizeHostname(_vhosts[i]);
}
if (connectorOnlyIndexes != null && hostMatch && !connectorHostMatch)
{
LOG.warn(
"ContextHandler {} has a connector only entry e.g. \"@connector\" and one or more host only entries. \n" +
"The host entries will be ignored to match legacy behavior. To clear this warning remove the host entries or update to us at least one host@connector syntax entry that will match a host for an specific connector",
Arrays.asList(vhosts));
String[] filteredHosts = new String[connectorOnlyIndexes.size()];
for (int i = 0; i < connectorOnlyIndexes.size(); i++)
{
filteredHosts[i] = vhosts[connectorOnlyIndexes.get(i)];
}
setVirtualHosts(filteredHosts);
}
}
}
/**
* Either set virtual hosts or add to an existing set of virtual hosts.
*
* @param virtualHosts Array of virtual hosts that this context responds to. A null/empty array means any hostname is acceptable. Host names may be String
* representation of IP addresses. Host names may start with '*.' to wildcard one level of names. Hosts and wildcard hosts may be followed with
* '@connectorname', in which case they will match only if the the {@link Connector#getName()} for the request also matches. If an entry is just
* '@connectorname' it will match any host if that connector was used. Note - In previous versions if one or more connectorname only entries existed
* and non of the connectors matched the handler would not match regardless of any hostname entries. If there is one or more connectorname only
* entries and one or more host only entries but no hostname and connector entries we assume the old behavior and will log a warning. The warning
* can be removed by removing the host entries that were previously being ignored, or modifying to include a hostname and connectorname entry.
*/
public void addVirtualHosts(String[] virtualHosts)
{
if (virtualHosts == null || virtualHosts.length == 0) // since this is add, we don't null the old ones
return;
if (_vhosts == null)
{
setVirtualHosts(virtualHosts);
}
else
{
Set<String> currentVirtualHosts = new HashSet<>(Arrays.asList(getVirtualHosts()));
for (String vh : virtualHosts)
{
currentVirtualHosts.add(normalizeHostname(vh));
}
setVirtualHosts(currentVirtualHosts.toArray(new String[0]));
}
}
/**
* Removes an array of virtual host entries, if this removes all entries the _vhosts will be set to null
*
* @param virtualHosts Array of virtual hosts that this context responds to. A null/empty array means any hostname is acceptable. Host names may be String
* representation of IP addresses. Host names may start with '*.' to wildcard one level of names. Hosts and wildcard hosts may be followed with
* '@connectorname', in which case they will match only if the the {@link Connector#getName()} for the request also matches. If an entry is just
* '@connectorname' it will match any host if that connector was used. Note - In previous versions if one or more connectorname only entries existed
* and non of the connectors matched the handler would not match regardless of any hostname entries. If there is one or more connectorname only
* entries and one or more host only entries but no hostname and connector entries we assume the old behavior and will log a warning. The warning
* can be removed by removing the host entries that were previously being ignored, or modifying to include a hostname and connectorname entry.
*/
public void removeVirtualHosts(String[] virtualHosts)
{
if (virtualHosts == null || virtualHosts.length == 0 || _vhosts == null || _vhosts.length == 0)
return; // do nothing
Set<String> existingVirtualHosts = new HashSet<>(Arrays.asList(getVirtualHosts()));
for (String vh : virtualHosts)
{
existingVirtualHosts.remove(normalizeHostname(vh));
}
if (existingVirtualHosts.isEmpty())
setVirtualHosts(null); // if we ended up removing them all, just null out _vhosts
else
setVirtualHosts(existingVirtualHosts.toArray(new String[0]));
}
/**
* Get the virtual hosts for the context. Only requests that have a matching host header or fully qualified URL will be passed to that context with a
* virtual host name. A context with no virtual host names or a null virtual host name is available to all requests that are not served by a context with a
* matching virtual host name.
*
* @return Array of virtual hosts that this context responds to. A null/empty array means any hostname is acceptable. Host names may be String
* representation of IP addresses. Host names may start with '*.' to wildcard one level of names. Hosts and wildcard hosts may be followed with
* '@connectorname', in which case they will match only if the the {@link Connector#getName()} for the request also matches. If an entry is just
* '@connectorname' it will match any host if that connector was used. Note - In previous versions if one or more connectorname only entries existed
* and non of the connectors matched the handler would not match regardless of any hostname entries. If there is one or more connectorname only
* entries and one or more host only entries but no hostname and connector entries we assume the old behavior and will log a warning. The warning
* can be removed by removing the host entries that were previously being ignored, or modifying to include a hostname and connectorname entry.
*/
@ManagedAttribute(value = "Virtual hosts accepted by the context", readonly = true)
public String[] getVirtualHosts()
{
if (_vhosts == null)
return null;
String[] vhosts = new String[_vhosts.length];
for (int i = 0; i < _vhosts.length; i++)
{
StringBuilder sb = new StringBuilder();
if (_vhostswildcard[i])
sb.append("*");
if (_vhosts[i] != null)
sb.append(_vhosts[i]);
if (_vconnectors[i] != null)
sb.append("@").append(_vconnectors[i]);
vhosts[i] = sb.toString();
}
return vhosts;
}
@Override
public Object getAttribute(String name)
{
return _attributes.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames()
{
return AttributesMap.getAttributeNamesCopy(_attributes);
}
@Override
public Set<String> getAttributeNameSet()
{
return _attributes.getAttributeNameSet();
}
/**
* @return Returns the attributes.
*/
public Attributes getAttributes()
{
return _attributes;
}
/**
* @return Returns the classLoader.
*/
public ClassLoader getClassLoader()
{
return _classLoader;
}
/**
* Make best effort to extract a file classpath from the context classloader
*
* @return Returns the classLoader.
*/
@ManagedAttribute("The file classpath")
public String getClassPath()
{
if (_classLoader == null || !(_classLoader instanceof URLClassLoader))
return null;
URLClassLoader loader = (URLClassLoader)_classLoader;
URL[] urls = loader.getURLs();
StringBuilder classpath = new StringBuilder();
for (int i = 0; i < urls.length; i++)
{
URL url = urls[i];
try
{
Resource resource = newResource(url);
File file = resource.getFile();
if (file != null && file.exists())
{
if (classpath.length() > 0)
classpath.append(File.pathSeparatorChar);
classpath.append(file.getAbsolutePath());
}
}
catch (IOException e)
{
LOG.debug("Could not found resource: {}", url, e);
}
}
if (classpath.length() == 0)
return null;
return classpath.toString();
}
/**
* @return Returns the contextPath.
*/
@ManagedAttribute("True if URLs are compacted to replace the multiple '/'s with a single '/'")
public String getContextPath()
{
return _contextPath;
}
/**
* @return Returns the encoded contextPath.
*/
public String getContextPathEncoded()
{
return _contextPathEncoded;
}
/**
* Get the context path in a form suitable to be returned from {@link HttpServletRequest#getContextPath()}
* or {@link ServletContext#getContextPath()}.
* @return Returns the encoded contextPath, or empty string for root context
*/
public String getRequestContextPath()
{
String contextPathEncoded = getContextPathEncoded();
return "/".equals(contextPathEncoded) ? "" : contextPathEncoded;
}
/*
* @see javax.servlet.ServletContext#getInitParameter(java.lang.String)
*/
public String getInitParameter(String name)
{
return _initParams.get(name);
}
public String setInitParameter(String name, String value)
{
return _initParams.put(name, value);
}
/*
* @see javax.servlet.ServletContext#getInitParameterNames()
*/
public Enumeration<String> getInitParameterNames()
{
return Collections.enumeration(_initParams.keySet());
}
/**
* @return Returns the initParams.
*/
@ManagedAttribute("Initial Parameter map for the context")
public Map<String, String> getInitParams()
{
return _initParams;
}
/*
* @see javax.servlet.ServletContext#getServletContextName()
*/
@ManagedAttribute(value = "Display name of the Context", readonly = true)
public String getDisplayName()
{
return _displayName;
}
/**
* Add a context event listeners.
*
* @param listener the event listener to add
* @return true if the listener was added
* @see ContextScopeListener
* @see ServletContextListener
* @see ServletContextAttributeListener
* @see ServletRequestListener
* @see ServletRequestAttributeListener
*/
@Override
public boolean addEventListener(EventListener listener)
{
if (super.addEventListener(listener))
{
if (listener instanceof ContextScopeListener)
{
_contextListeners.add((ContextScopeListener)listener);
if (__context.get() != null)
((ContextScopeListener)listener).enterScope(__context.get(), null, "Listener registered");
}
if (listener instanceof ServletContextListener)
{
if (_contextStatus == ContextStatus.INITIALIZED)
{
ServletContextListener scl = (ServletContextListener)listener;
_destroyServletContextListeners.add(scl);
if (isStarting())
{
LOG.warn("ContextListener {} added whilst starting {}", scl, this);
callContextInitialized(scl, new ServletContextEvent(_scontext));
}
else
{
LOG.warn("ContextListener {} added after starting {}", scl, this);
}
}
_servletContextListeners.add((ServletContextListener)listener);
}
if (listener instanceof ServletContextAttributeListener)
_servletContextAttributeListeners.add((ServletContextAttributeListener)listener);
if (listener instanceof ServletRequestListener)
_servletRequestListeners.add((ServletRequestListener)listener);
if (listener instanceof ServletRequestAttributeListener)
_servletRequestAttributeListeners.add((ServletRequestAttributeListener)listener);
return true;
}
return false;
}
@Override
public boolean removeEventListener(EventListener listener)
{
if (super.removeEventListener(listener))
{
if (listener instanceof ContextScopeListener)
_contextListeners.remove(listener);
if (listener instanceof ServletContextListener)
{
_servletContextListeners.remove(listener);
_destroyServletContextListeners.remove(listener);
}
if (listener instanceof ServletContextAttributeListener)
_servletContextAttributeListeners.remove(listener);
if (listener instanceof ServletRequestListener)
_servletRequestListeners.remove(listener);
if (listener instanceof ServletRequestAttributeListener)
_servletRequestAttributeListeners.remove(listener);
return true;
}
return false;
}
/**
* Apply any necessary restrictions on a programmatic added listener.
*
* @param listener the programmatic listener to add
*/
protected void addProgrammaticListener(EventListener listener)
{
_programmaticListeners.add(listener);
}
public boolean isProgrammaticListener(EventListener listener)
{
return _programmaticListeners.contains(listener);
}
public boolean isDurableListener(EventListener listener)
{
// The durable listeners are those set when the context is started
if (isStarted())
return _durableListeners.contains(listener);
// If we are not yet started then all set listeners are durable
return getEventListeners().contains(listener);
}
/**
* @return true if this context is shutting down
*/
@ManagedAttribute("true for graceful shutdown, which allows existing requests to complete")
public boolean isShutdown()
{
return _availability.get() == Availability.SHUTDOWN;
}
/**
* Set shutdown status. This field allows for graceful shutdown of a context. A started context may be put into non accepting state so that existing
* requests can complete, but no new requests are accepted.
*/
@Override
public CompletableFuture<Void> shutdown()
{
while (true)
{
Availability availability = _availability.get();
switch (availability)
{
case STOPPED:
return CompletableFuture.failedFuture(new IllegalStateException(getState()));
case STARTING:
case AVAILABLE:
case UNAVAILABLE:
if (!_availability.compareAndSet(availability, Availability.SHUTDOWN))
continue;
break;
default:
break;
}
break;
}
return CompletableFuture.completedFuture(null);
}
/**
* @return false if this context is unavailable (sends 503)
*/
public boolean isAvailable()
{
return _availability.get() == Availability.AVAILABLE;
}
/**
* Set Available status.
*
* @param available true to set as enabled
*/
public void setAvailable(boolean available)
{
// Only supported state transitions are:
// UNAVAILABLE --true---> AVAILABLE
// STARTING -----false--> UNAVAILABLE
// AVAILABLE ----false--> UNAVAILABLE
if (available)
{
while (true)
{
Availability availability = _availability.get();
switch (availability)
{
case AVAILABLE:
break;
case UNAVAILABLE:
if (!_availability.compareAndSet(availability, Availability.AVAILABLE))
continue;
break;
default:
throw new IllegalStateException(availability.toString());
}
break;
}
}
else
{
while (true)
{
Availability availability = _availability.get();
switch (availability)
{
case STARTING:
case AVAILABLE:
if (!_availability.compareAndSet(availability, Availability.UNAVAILABLE))
continue;
break;
default:
break;
}
break;
}
}
}
public Logger getLogger()
{
return _logger;
}
public void setLogger(Logger logger)
{
_logger = logger;
}
@Override
protected void doStart() throws Exception
{
if (_contextPath == null)
throw new IllegalStateException("Null contextPath");
if (getBaseResource() != null && getBaseResource().isAlias())
LOG.warn("BaseResource {} is aliased to {} in {}. May not be supported in future releases.",
getBaseResource(), getBaseResource().getAlias(), this);
_availability.set(Availability.STARTING);
if (_logger == null)
_logger = LoggerFactory.getLogger(ContextHandler.class.getName() + getLogNameSuffix());
ClassLoader oldClassloader = null;
Thread currentThread = null;
Context oldContext = null;
_attributes.setAttribute("org.eclipse.jetty.server.Executor", getServer().getThreadPool());
if (_mimeTypes == null)
_mimeTypes = new MimeTypes();
_durableListeners.addAll(getEventListeners());
try
{
// Set the classloader, context and enter scope
if (_classLoader != null)
{
currentThread = Thread.currentThread();
oldClassloader = currentThread.getContextClassLoader();
currentThread.setContextClassLoader(_classLoader);
}
oldContext = __context.get();
__context.set(_scontext);
enterScope(null, getState());
// defers the calling of super.doStart()
startContext();
contextInitialized();
_availability.compareAndSet(Availability.STARTING, Availability.AVAILABLE);
LOG.info("Started {}", this);
}
finally
{
_availability.compareAndSet(Availability.STARTING, Availability.UNAVAILABLE);
exitScope(null);
__context.set(oldContext);
// reset the classloader
if (_classLoader != null && currentThread != null)
currentThread.setContextClassLoader(oldClassloader);
}
}
private String getLogNameSuffix()
{
// Use display name first
String logName = getDisplayName();
if (StringUtil.isBlank(logName))
{
// try context path
logName = getContextPath();
if (logName != null)
{
// Strip prefix slash
if (logName.startsWith("/"))
{
logName = logName.substring(1);
}
}
if (StringUtil.isBlank(logName))
{
// an empty context path is the ROOT context
logName = "ROOT";
}
}
// Replace bad characters.
return '.' + logName.replaceAll("\\W", "_");
}
/**
* Extensible startContext. this method is called from {@link ContextHandler#doStart()} instead of a call to super.doStart(). This allows derived classes to
* insert additional handling (Eg configuration) before the call to super.doStart by this method will start contained handlers.
*
* @throws Exception if unable to start the context
* @see ContextHandler.Context
*/
protected void startContext() throws Exception
{
String managedAttributes = _initParams.get(MANAGED_ATTRIBUTES);
if (managedAttributes != null)
addEventListener(new ManagedAttributeListener(this, StringUtil.csvSplit(managedAttributes)));
super.doStart();
}
/**
* Call the ServletContextListeners contextInitialized methods.
* This can be called from a ServletHandler during the proper sequence
* of initializing filters, servlets and listeners. However, if there is
* no ServletHandler, the ContextHandler will call this method during
* doStart().
*
* @throws Exception
*/
public void contextInitialized() throws Exception
{
// Call context listeners
if (_contextStatus == ContextStatus.NOTSET)
{
_contextStatus = ContextStatus.INITIALIZED;
_destroyServletContextListeners.clear();
if (!_servletContextListeners.isEmpty())
{
ServletContextEvent event = new ServletContextEvent(_scontext);
for (ServletContextListener listener : _servletContextListeners)
{
callContextInitialized(listener, event);
_destroyServletContextListeners.add(listener);
}
}
}
}
/**
* Call the ServletContextListeners with contextDestroyed.
* This method can be called from a ServletHandler in the
* proper sequence of destroying filters, servlets and listeners.
* If there is no ServletHandler, the ContextHandler must ensure
* these listeners are called instead.
*
* @throws Exception
*/
public void contextDestroyed() throws Exception
{
switch (_contextStatus)
{
case INITIALIZED:
{
try
{
//Call context listeners