-
Notifications
You must be signed in to change notification settings - Fork 974
/
ServletContextImpl.java
1307 lines (1185 loc) · 53.9 KB
/
ServletContextImpl.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
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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 io.undertow.servlet.spec;
import io.undertow.Version;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.cache.LRUCache;
import io.undertow.server.handlers.resource.Resource;
import io.undertow.server.session.PathParameterSessionConfig;
import io.undertow.server.session.Session;
import io.undertow.server.session.SessionConfig;
import io.undertow.server.session.SessionManager;
import io.undertow.server.session.SslSessionConfig;
import io.undertow.servlet.UndertowServletLogger;
import io.undertow.servlet.UndertowServletMessages;
import io.undertow.servlet.api.Deployment;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.FilterInfo;
import io.undertow.servlet.api.HttpMethodSecurityInfo;
import io.undertow.servlet.api.InstanceFactory;
import io.undertow.servlet.api.ListenerInfo;
import io.undertow.servlet.api.SecurityInfo;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.servlet.api.ServletInfo;
import io.undertow.servlet.api.ServletSecurityInfo;
import io.undertow.servlet.api.SessionConfigWrapper;
import io.undertow.servlet.api.ThreadSetupHandler;
import io.undertow.servlet.api.TransportGuaranteeType;
import io.undertow.servlet.core.ApplicationListeners;
import io.undertow.servlet.core.ManagedListener;
import io.undertow.servlet.core.ManagedServlet;
import io.undertow.servlet.handlers.ServletChain;
import io.undertow.servlet.handlers.ServletHandler;
import io.undertow.servlet.handlers.ServletRequestContext;
import io.undertow.servlet.util.EmptyEnumeration;
import io.undertow.servlet.util.ImmediateInstanceFactory;
import io.undertow.servlet.util.IteratorEnumeration;
import io.undertow.util.AttachmentKey;
import io.undertow.util.CanonicalPathUtils;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RunAs;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ReadListener;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRequest;
import javax.servlet.SessionTrackingMode;
import javax.servlet.WriteListener;
import javax.servlet.annotation.HttpMethodConstraint;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.descriptor.JspConfigDescriptor;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
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.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static io.undertow.servlet.core.ApplicationListeners.ListenerState.NO_LISTENER;
import static io.undertow.servlet.core.ApplicationListeners.ListenerState.PROGRAMATIC_LISTENER;
/**
* @author Stuart Douglas
*/
public class ServletContextImpl implements ServletContext {
private final ServletContainer servletContainer;
private final Deployment deployment;
private volatile DeploymentInfo deploymentInfo;
private final ConcurrentMap<String, Object> attributes;
private final SessionCookieConfigImpl sessionCookieConfig;
private final AttachmentKey<HttpSessionImpl> sessionAttachmentKey = AttachmentKey.create(HttpSessionImpl.class);
private volatile Set<SessionTrackingMode> sessionTrackingModes = new HashSet<>(Arrays.asList(new SessionTrackingMode[]{SessionTrackingMode.COOKIE, SessionTrackingMode.URL}));
private volatile Set<SessionTrackingMode> defaultSessionTrackingModes = new HashSet<>(Arrays.asList(new SessionTrackingMode[]{SessionTrackingMode.COOKIE, SessionTrackingMode.URL}));
private volatile SessionConfig sessionConfig;
private volatile boolean initialized = false;
private int filterMappingUrlPatternInsertPosition = 0;
private int filterMappingServletNameInsertPosition = 0;
private final LRUCache<String, ContentTypeInfo> contentTypeCache;
//I don't think these really belong here, but there is not really anywhere else for them
//maybe we should move them into a separate class
private volatile ThreadSetupHandler.Action<Void, WriteListener> onWritePossibleTask;
private volatile ThreadSetupHandler.Action<Void, Runnable> runnableTask;
private volatile ThreadSetupHandler.Action<Void, ReadListener> onDataAvailableTask;
private volatile ThreadSetupHandler.Action<Void, ReadListener> onAllDataReadTask;
private volatile ThreadSetupHandler.Action<Void, ThreadSetupHandler.Action<Void, Object>> invokeActionTask;
private volatile int defaultSessionTimeout;
public ServletContextImpl(final ServletContainer servletContainer, final Deployment deployment) {
this.servletContainer = servletContainer;
this.deployment = deployment;
this.deploymentInfo = deployment.getDeploymentInfo();
sessionCookieConfig = new SessionCookieConfigImpl(this);
sessionCookieConfig.setPath(deploymentInfo.getContextPath());
if (deploymentInfo.getServletContextAttributeBackingMap() == null) {
this.attributes = new ConcurrentHashMap<>();
} else {
this.attributes = deploymentInfo.getServletContextAttributeBackingMap();
}
attributes.putAll(deployment.getDeploymentInfo().getServletContextAttributes());
this.contentTypeCache = new LRUCache<>(deployment.getDeploymentInfo().getContentTypeCacheSize(), -1, true);
this.defaultSessionTimeout = deploymentInfo.getDefaultSessionTimeout() / 60;
}
public void initDone() {
initialized = true;
Set<SessionTrackingMode> trackingMethods = sessionTrackingModes;
SessionConfig sessionConfig = sessionCookieConfig;
if (trackingMethods != null && !trackingMethods.isEmpty()) {
if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) {
sessionConfig = new SslSessionConfig(deployment.getSessionManager());
} else {
if (sessionTrackingModes.contains(SessionTrackingMode.COOKIE) && sessionTrackingModes.contains(SessionTrackingMode.URL)) {
sessionCookieConfig.setFallback(new PathParameterSessionConfig(sessionCookieConfig.getName().toLowerCase(Locale.ENGLISH)));
} else if (sessionTrackingModes.contains(SessionTrackingMode.URL)) {
sessionConfig = new PathParameterSessionConfig(sessionCookieConfig.getName().toLowerCase(Locale.ENGLISH));
}
}
}
SessionConfigWrapper wrapper = deploymentInfo.getSessionConfigWrapper();
if (wrapper != null) {
sessionConfig = wrapper.wrap(sessionConfig, deployment);
}
this.sessionConfig = new ServletContextSessionConfig(sessionConfig);
this.onWritePossibleTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, WriteListener>() {
@Override
public Void call(HttpServerExchange exchange, WriteListener context) throws Exception {
context.onWritePossible();
return null;
}
});
this.runnableTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Runnable>() {
@Override
public Void call(HttpServerExchange exchange, Runnable runnable) throws Exception {
runnable.run();
return null;
}
});
this.onDataAvailableTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ReadListener>() {
@Override
public Void call(HttpServerExchange exchange, ReadListener context) throws Exception {
context.onDataAvailable();
return null;
}
});
this.onAllDataReadTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ReadListener>() {
@Override
public Void call(HttpServerExchange exchange, ReadListener context) throws Exception {
context.onAllDataRead();
return null;
}
});
this.invokeActionTask = deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, ThreadSetupHandler.Action<Void, Object>>() {
@Override
public Void call(HttpServerExchange exchange, ThreadSetupHandler.Action<Void, Object> context) throws Exception {
context.call(exchange, null);
return null;
}
});
}
private DeploymentInfo getDeploymentInfo() {
final DeploymentInfo deploymentInfo = this.deploymentInfo;
if (deploymentInfo == null)
throw UndertowServletLogger.ROOT_LOGGER.contextDestroyed();
return deploymentInfo;
}
@Override
public String getContextPath() {
String contextPath = getDeploymentInfo().getContextPath();
if (contextPath.equals("/")) {
return "";
}
return contextPath;
}
@Override
public ServletContext getContext(final String uripath) {
DeploymentManager deploymentByPath = servletContainer.getDeploymentByPath(uripath);
if (deploymentByPath == null) {
return null;
}
return deploymentByPath.getDeployment().getServletContext();
}
@Override
public int getMajorVersion() {
return getDeploymentInfo().getContainerMajorVersion();
}
@Override
public int getMinorVersion() {
return getDeploymentInfo().getContainerMinorVersion();
}
@Override
public int getEffectiveMajorVersion() {
return getDeploymentInfo().getMajorVersion();
}
@Override
public int getEffectiveMinorVersion() {
return getDeploymentInfo().getMinorVersion();
}
@Override
public String getMimeType(final String file) {
if(file == null) {
return null;
}
String lower = file.toLowerCase(Locale.ENGLISH);
int pos = lower.lastIndexOf('.');
if (pos == -1) {
return null; //no extension
}
return deployment.getMimeExtensionMappings().get(lower.substring(pos + 1));
}
@Override
public Set<String> getResourcePaths(final String path) {
final Resource resource;
try {
resource = getDeploymentInfo().getResourceManager().getResource(path);
} catch (IOException e) {
return null;
}
if (resource == null || !resource.isDirectory()) {
return null;
}
final Set<String> resources = new HashSet<>();
for (Resource res : resource.list()) {
Path file = res.getFilePath();
if (file != null) {
Path base = res.getResourceManagerRootPath();
if (base == null) {
resources.add(file.toString()); //not much else we can do here
} else {
String filePath = file.toAbsolutePath().toString().substring(base.toAbsolutePath().toString().length());
filePath = filePath.replace('\\', '/'); //for windows systems
if (Files.isDirectory(file)) {
filePath = filePath + "/";
}
resources.add(filePath);
}
}
}
return resources;
}
@Override
public URL getResource(final String path) throws MalformedURLException {
if (path == null || !path.startsWith("/")) {
throw UndertowServletMessages.MESSAGES.pathMustStartWithSlash(path);
}
Resource resource = null;
try {
resource = getDeploymentInfo().getResourceManager().getResource(path);
} catch (IOException e) {
return null;
}
if (resource == null) {
return null;
}
return resource.getUrl();
}
@Override
public InputStream getResourceAsStream(final String path) {
Resource resource = null;
try {
resource = getDeploymentInfo().getResourceManager().getResource(path);
} catch (IOException e) {
return null;
}
if (resource == null) {
return null;
}
try {
if (resource.getFile() != null) {
return new BufferedInputStream(new FileInputStream(resource.getFile()));
} else {
return new BufferedInputStream(resource.getUrl().openStream());
}
} catch (FileNotFoundException e) {
//should never happen, as the resource loader should return null in this case
return null;
} catch (IOException e) {
return null;
}
}
@Override
public RequestDispatcher getRequestDispatcher(final String path) {
if (path == null) {
return null;
}
if (!path.startsWith("/")) {
throw UndertowServletMessages.MESSAGES.pathMustStartWithSlashForRequestDispatcher(path);
}
final String realPath = CanonicalPathUtils.canonicalize(path, true);
if (realPath == null) {
// path is outside the servlet context, return null per spec
return null;
}
return new RequestDispatcherImpl(realPath, this);
}
@Override
public RequestDispatcher getNamedDispatcher(final String name) {
ServletChain chain = deployment.getServletPaths().getServletHandlerByName(name);
if (chain != null) {
return new RequestDispatcherImpl(chain, this);
} else {
return null;
}
}
@Override
public Servlet getServlet(final String name) throws ServletException {
return deployment.getServletPaths().getServletHandlerByName(name).getManagedServlet().getServlet().getInstance();
}
@Override
public Enumeration<Servlet> getServlets() {
return EmptyEnumeration.instance();
}
@Override
public Enumeration<String> getServletNames() {
return EmptyEnumeration.instance();
}
@Override
public void log(final String msg) {
UndertowServletLogger.ROOT_LOGGER.info(msg);
}
@Override
public void log(final Exception exception, final String msg) {
UndertowServletLogger.ROOT_LOGGER.error(msg, exception);
}
@Override
public void log(final String message, final Throwable throwable) {
UndertowServletLogger.ROOT_LOGGER.error(message, throwable);
}
@Override
public String getRealPath(final String path) {
if (path == null) {
return null;
}
final DeploymentInfo deploymentInfo = getDeploymentInfo();
String canonicalPath = CanonicalPathUtils.canonicalize(path);
Resource resource;
try {
resource = deploymentInfo.getResourceManager().getResource(canonicalPath);
if (resource == null) {
//UNDERTOW-373 even though the resource does not exist we still need to return a path
Resource deploymentRoot = deploymentInfo.getResourceManager().getResource("/");
if(deploymentRoot == null) {
return null;
}
Path root = deploymentRoot.getFilePath();
if(root == null) {
return null;
}
if(!canonicalPath.startsWith("/")) {
canonicalPath = "/" + canonicalPath;
}
if(File.separatorChar != '/') {
canonicalPath = canonicalPath.replace('/', File.separatorChar);
}
return root.toAbsolutePath().toString() + canonicalPath;
}
} catch (IOException e) {
return null;
}
Path file = resource.getFilePath();
if (file == null) {
return null;
}
return file.toAbsolutePath().toString();
}
@Override
public String getServerInfo() {
return getDeploymentInfo().getServerName() + " - " + Version.getVersionString();
}
@Override
public String getInitParameter(final String name) {
if (name == null) {
throw UndertowServletMessages.MESSAGES.nullName();
}
return getDeploymentInfo().getInitParameters().get(name);
}
@Override
public Enumeration<String> getInitParameterNames() {
return new IteratorEnumeration<>(getDeploymentInfo().getInitParameters().keySet().iterator());
}
@Override
public boolean setInitParameter(final String name, final String value) {
if(name == null) {
throw UndertowServletMessages.MESSAGES.paramCannotBeNullNPE("name");
}
if (getDeploymentInfo().getInitParameters().containsKey(name)) {
return false;
}
getDeploymentInfo().addInitParameter(name, value);
return true;
}
@Override
public Object getAttribute(final String name) {
if (name == null) {
throw UndertowServletMessages.MESSAGES.nullName();
}
return attributes.get(name);
}
@Override
public Enumeration<String> getAttributeNames() {
return new IteratorEnumeration<>(attributes.keySet().iterator());
}
@Override
public void setAttribute(final String name, final Object object) {
if (name == null) {
throw UndertowServletMessages.MESSAGES.nullName();
}
if (object == null) {
Object existing = attributes.remove(name);
if (deployment.getApplicationListeners() != null) {
if (existing != null) {
deployment.getApplicationListeners().servletContextAttributeRemoved(name, existing);
}
}
} else {
Object existing = attributes.put(name, object);
if (deployment.getApplicationListeners() != null) {
if (existing != null) {
deployment.getApplicationListeners().servletContextAttributeReplaced(name, existing);
} else {
deployment.getApplicationListeners().servletContextAttributeAdded(name, object);
}
}
}
}
@Override
public void removeAttribute(final String name) {
Object exiting = attributes.remove(name);
deployment.getApplicationListeners().servletContextAttributeRemoved(name, exiting);
}
@Override
public String getServletContextName() {
return getDeploymentInfo().getDisplayName();
}
@Override
public ServletRegistration.Dynamic addServlet(final String servletName, final String className) {
return addServlet(servletName, className, Collections.emptyList());
}
public ServletRegistration.Dynamic addServlet(final String servletName, final String className, List<HandlerWrapper> wrappers) {
ensureNotProgramaticListener();
ensureNotInitialized();
ensureServletNameNotNull(servletName);
try {
final DeploymentInfo deploymentInfo = getDeploymentInfo();
if (deploymentInfo.getServlets().containsKey(servletName)) {
return null;
}
Class<? extends Servlet> servletClass=(Class<? extends Servlet>) deploymentInfo.getClassLoader().loadClass(className);
ServletInfo servlet = new ServletInfo(servletName, servletClass, deploymentInfo.getClassIntrospecter().createInstanceFactory(servletClass));
for(HandlerWrapper i : wrappers) {
servlet.addHandlerChainWrapper(i);
}
readServletAnnotations(servlet, deploymentInfo);
deploymentInfo.addServlet(servlet);
ServletHandler handler = deployment.getServlets().addServlet(servlet);
return new ServletRegistrationImpl(servlet, handler.getManagedServlet(), deployment);
} catch (ClassNotFoundException e) {
throw UndertowServletMessages.MESSAGES.cannotLoadClass(className, e);
} catch (NoSuchMethodException e) {
throw UndertowServletMessages.MESSAGES.couldNotCreateFactory(className,e);
}
}
@Override
public ServletRegistration.Dynamic addServlet(final String servletName, final Servlet servlet) {
ensureNotProgramaticListener();
ensureNotInitialized();
ensureServletNameNotNull(servletName);
final DeploymentInfo deploymentInfo = getDeploymentInfo();
if (deploymentInfo.getServlets().containsKey(servletName)) {
return null;
}
ServletInfo s = new ServletInfo(servletName, servlet.getClass(), new ImmediateInstanceFactory<>(servlet));
readServletAnnotations(s, deploymentInfo);
deploymentInfo.addServlet(s);
ServletHandler handler = deployment.getServlets().addServlet(s);
return new ServletRegistrationImpl(s, handler.getManagedServlet(), deployment);
}
@Override
public ServletRegistration.Dynamic addServlet(final String servletName, final Class<? extends Servlet> servletClass){
ensureNotProgramaticListener();
ensureNotInitialized();
ensureServletNameNotNull(servletName);
final DeploymentInfo deploymentInfo = getDeploymentInfo();
if (deploymentInfo.getServlets().containsKey(servletName)) {
return null;
}
try {
ServletInfo servlet = new ServletInfo(servletName, servletClass, deploymentInfo.getClassIntrospecter().createInstanceFactory(servletClass));
readServletAnnotations(servlet, deploymentInfo);
deploymentInfo.addServlet(servlet);
ServletHandler handler = deployment.getServlets().addServlet(servlet);
return new ServletRegistrationImpl(servlet, handler.getManagedServlet(), deployment);
} catch (NoSuchMethodException e) {
throw UndertowServletMessages.MESSAGES.couldNotCreateFactory(servletClass.getName(),e);
}
}
private void ensureServletNameNotNull(String servletName) {
if(servletName == null) {
throw UndertowServletMessages.MESSAGES.servletNameNull();
}
}
@Override
public <T extends Servlet> T createServlet(final Class<T> clazz) throws ServletException {
ensureNotProgramaticListener();
try {
return getDeploymentInfo().getClassIntrospecter().createInstanceFactory(clazz).createInstance().getInstance();
} catch (Exception e) {
throw UndertowServletMessages.MESSAGES.couldNotInstantiateComponent(clazz.getName(), e);
}
}
@Override
public ServletRegistration getServletRegistration(final String servletName) {
ensureNotProgramaticListener();
final ManagedServlet servlet = deployment.getServlets().getManagedServlet(servletName);
if (servlet == null) {
return null;
}
return new ServletRegistrationImpl(servlet.getServletInfo(), servlet, deployment);
}
@Override
public Map<String, ? extends ServletRegistration> getServletRegistrations() {
ensureNotProgramaticListener();
final Map<String, ServletRegistration> ret = new HashMap<>();
for (Map.Entry<String, ServletHandler> entry : deployment.getServlets().getServletHandlers().entrySet()) {
ret.put(entry.getKey(), new ServletRegistrationImpl(entry.getValue().getManagedServlet().getServletInfo(), entry.getValue().getManagedServlet(), deployment));
}
return ret;
}
@Override
public FilterRegistration.Dynamic addFilter(final String filterName, final String className) {
ensureNotProgramaticListener();
ensureNotInitialized();
final DeploymentInfo deploymentInfo = getDeploymentInfo();
if (deploymentInfo.getFilters().containsKey(filterName)) {
return null;
}
try {
Class<? extends Filter> filterClass=(Class<? extends Filter>) deploymentInfo.getClassLoader().loadClass(className);
FilterInfo filter = new FilterInfo(filterName, filterClass, deploymentInfo.getClassIntrospecter().createInstanceFactory(filterClass));
deploymentInfo.addFilter(filter);
deployment.getFilters().addFilter(filter);
return new FilterRegistrationImpl(filter, deployment, this);
} catch (ClassNotFoundException e) {
throw UndertowServletMessages.MESSAGES.cannotLoadClass(className, e);
}catch (NoSuchMethodException e) {
throw UndertowServletMessages.MESSAGES.couldNotCreateFactory(className,e);
}
}
@Override
public FilterRegistration.Dynamic addFilter(final String filterName, final Filter filter) {
ensureNotProgramaticListener();
ensureNotInitialized();
final DeploymentInfo deploymentInfo = getDeploymentInfo();
if (deploymentInfo.getFilters().containsKey(filterName)) {
return null;
}
FilterInfo f = new FilterInfo(filterName, filter.getClass(), new ImmediateInstanceFactory<>(filter));
deploymentInfo.addFilter(f);
deployment.getFilters().addFilter(f);
return new FilterRegistrationImpl(f, deployment, this);
}
@Override
public FilterRegistration.Dynamic addFilter(final String filterName, final Class<? extends Filter> filterClass) {
ensureNotProgramaticListener();
ensureNotInitialized();
final DeploymentInfo deploymentInfo = getDeploymentInfo();
if (deploymentInfo.getFilters().containsKey(filterName)) {
return null;
}
try {
FilterInfo filter = new FilterInfo(filterName, filterClass,deploymentInfo.getClassIntrospecter().createInstanceFactory(filterClass));
deploymentInfo.addFilter(filter);
deployment.getFilters().addFilter(filter);
return new FilterRegistrationImpl(filter, deployment, this);
} catch (NoSuchMethodException e) {
throw UndertowServletMessages.MESSAGES.couldNotCreateFactory(filterClass.getName(),e);
}
}
@Override
public <T extends Filter> T createFilter(final Class<T> clazz) throws ServletException {
ensureNotProgramaticListener();
try {
return getDeploymentInfo().getClassIntrospecter().createInstanceFactory(clazz).createInstance().getInstance();
} catch (Exception e) {
throw UndertowServletMessages.MESSAGES.couldNotInstantiateComponent(clazz.getName(), e);
}
}
@Override
public FilterRegistration getFilterRegistration(final String filterName) {
ensureNotProgramaticListener();
final FilterInfo filterInfo = getDeploymentInfo().getFilters().get(filterName);
if (filterInfo == null) {
return null;
}
return new FilterRegistrationImpl(filterInfo, deployment, this);
}
@Override
public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
ensureNotProgramaticListener();
final Map<String, FilterRegistration> ret = new HashMap<>();
for (Map.Entry<String, FilterInfo> entry : getDeploymentInfo().getFilters().entrySet()) {
ret.put(entry.getKey(), new FilterRegistrationImpl(entry.getValue(), deployment, this));
}
return ret;
}
@Override
public SessionCookieConfigImpl getSessionCookieConfig() {
ensureNotProgramaticListener();
return sessionCookieConfig;
}
@Override
public void setSessionTrackingModes(final Set<SessionTrackingMode> sessionTrackingModes) {
ensureNotProgramaticListener();
ensureNotInitialized();
if (sessionTrackingModes.size() > 1 && sessionTrackingModes.contains(SessionTrackingMode.SSL)) {
throw UndertowServletMessages.MESSAGES.sslCannotBeCombinedWithAnyOtherMethod();
}
this.sessionTrackingModes = new HashSet<>(sessionTrackingModes);
//TODO: actually make this work
}
@Override
public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
ensureNotProgramaticListener();
return defaultSessionTrackingModes;
}
@Override
public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
ensureNotProgramaticListener();
return Collections.unmodifiableSet(sessionTrackingModes);
}
@Override
public void addListener(final String className) {
try {
Class<? extends EventListener> clazz = (Class<? extends EventListener>) getDeploymentInfo().getClassLoader().loadClass(className);
addListener(clazz);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public <T extends EventListener> void addListener(final T t) {
ensureNotInitialized();
ensureNotProgramaticListener();
if (ApplicationListeners.listenerState() != NO_LISTENER
&& ServletContextListener.class.isAssignableFrom(t.getClass())) {
throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
}
ListenerInfo listener = new ListenerInfo(t.getClass(), new ImmediateInstanceFactory<EventListener>(t));
getDeploymentInfo().addListener(listener);
deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
}
@Override
public void addListener(final Class<? extends EventListener> listenerClass) {
ensureNotInitialized();
ensureNotProgramaticListener();
if (ApplicationListeners.listenerState() != NO_LISTENER
&& ServletContextListener.class.isAssignableFrom(listenerClass)) {
throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
}
final DeploymentInfo deploymentInfo = getDeploymentInfo();
InstanceFactory<? extends EventListener> factory = null;
try {
factory = deploymentInfo.getClassIntrospecter().createInstanceFactory(listenerClass);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
final ListenerInfo listener = new ListenerInfo(listenerClass, factory);
deploymentInfo.addListener(listener);
deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
}
@Override
public <T extends EventListener> T createListener(final Class<T> clazz) throws ServletException {
ensureNotProgramaticListener();
if (!ApplicationListeners.isListenerClass(clazz)) {
throw UndertowServletMessages.MESSAGES.listenerMustImplementListenerClass(clazz);
}
try {
return getDeploymentInfo().getClassIntrospecter().createInstanceFactory(clazz).createInstance().getInstance();
} catch (Exception e) {
throw UndertowServletMessages.MESSAGES.couldNotInstantiateComponent(clazz.getName(), e);
}
}
@Override
public JspConfigDescriptor getJspConfigDescriptor() {
return getDeploymentInfo().getJspConfigDescriptor();
}
@Override
public ClassLoader getClassLoader() {
return getDeploymentInfo().getClassLoader();
}
@Override
public void declareRoles(final String... roleNames) {
final DeploymentInfo di = this.getDeploymentInfo();
if (isInitialized()) {
throw UndertowServletMessages.MESSAGES.servletAlreadyInitialize(di.getDeploymentName(), di.getContextPath());
}
for (String role : roleNames) {
if (role == null || role.isEmpty()) {
throw UndertowServletMessages.MESSAGES.roleMustNotBeEmpty(di.getDeploymentName(), di.getContextPath());
}
}
if (ApplicationListeners.listenerState() == PROGRAMATIC_LISTENER) {
//NOTE: its either null or false for non-programatic? - null in case its not ApplicationListener
throw UndertowServletMessages.MESSAGES.cantCallFromDynamicListener(di.getDeploymentName(), di.getContextPath());
}
deploymentInfo.addSecurityRoles(roleNames);
}
@Override
public ServletRegistration.Dynamic addJspFile(String servletName, String jspFile) {
if(servletName == null || servletName.isEmpty()) {
throw UndertowServletMessages.MESSAGES.paramCannotBeNull("servletName");
}
return addServlet(servletName, "org.apache.jasper.servlet.JspServlet", Collections.singletonList(handler -> exchange -> {
ServletRequest request = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getServletRequest();
request.setAttribute(System.getProperty("org.apache.jasper.Constants.JSP_FILE", "org.apache.catalina.jsp_file"), jspFile);
handler.handleRequest(exchange);
}));
}
@Override
public int getSessionTimeout() {
return defaultSessionTimeout;
}
@Override
public void setSessionTimeout(int sessionTimeout) {
ensureNotInitialized();
ensureNotProgramaticListener();
this.defaultSessionTimeout = sessionTimeout;
deployment.getSessionManager().setDefaultSessionTimeout(sessionTimeout * 60);
}
@Override
public String getRequestCharacterEncoding() {
final DeploymentInfo deploymentInfo = getDeploymentInfo();
String enconding = deploymentInfo.getDefaultRequestEncoding();
if(enconding != null) {
return enconding;
}
return deploymentInfo.getDefaultEncoding();
}
@Override
public void setRequestCharacterEncoding(String encoding) {
ensureNotInitialized();
ensureNotProgramaticListener();
getDeploymentInfo().setDefaultRequestEncoding(encoding);
}
@Override
public String getResponseCharacterEncoding() {
final DeploymentInfo deploymentInfo = getDeploymentInfo();
String enconding = deploymentInfo.getDefaultResponseEncoding();
if(enconding != null) {
return enconding;
}
return deploymentInfo.getDefaultEncoding();
}
@Override
public void setResponseCharacterEncoding(String encoding) {
ensureNotInitialized();
ensureNotProgramaticListener();
getDeploymentInfo().setDefaultResponseEncoding(encoding);
}
@Override
public String getVirtualServerName() {
return deployment.getDeploymentInfo().getHostName();
}
/**
* Gets the session with the specified ID if it exists
*
* @param sessionId The session ID
* @return The session
*/
public HttpSessionImpl getSession(final String sessionId) {
final SessionManager sessionManager = deployment.getSessionManager();
Session session = sessionManager.getSession(sessionId);
if (session != null) {
return SecurityActions.forSession(session, this, false);
}
return null;
}
public HttpSessionImpl getSession(final ServletContextImpl originalServletContext, final HttpServerExchange exchange, boolean create) {
SessionConfig c = originalServletContext.getSessionConfig();
HttpSessionImpl httpSession = exchange.getAttachment(sessionAttachmentKey);
if (httpSession != null && httpSession.isInvalid()) {
exchange.removeAttachment(sessionAttachmentKey);
httpSession = null;
}
if (httpSession == null) {
final SessionManager sessionManager = deployment.getSessionManager();
Session session = sessionManager.getSession(exchange, c);
if (session != null) {
httpSession = SecurityActions.forSession(session, this, false);
exchange.putAttachment(sessionAttachmentKey, httpSession);
} else if (create) {
String existing = c.findSessionId(exchange);
Boolean isRequestedSessionIdSaved = exchange.getAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID_SET);
if (isRequestedSessionIdSaved == null || !isRequestedSessionIdSaved) {
exchange.putAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID_SET, Boolean.TRUE);
exchange.putAttachment(HttpServletRequestImpl.REQUESTED_SESSION_ID, existing);
}
if (originalServletContext != this) {
//this is a cross context request
//we need to make sure there is a top level session
final HttpSessionImpl topLevel = originalServletContext.getSession(originalServletContext, exchange, true);
//override the session id to just return the same ID as the top level session
c = new SessionConfig() {
@Override
public void setSessionId(HttpServerExchange exchange, String sessionId) {
//noop
}
@Override
public void clearSession(HttpServerExchange exchange, String sessionId) {
//noop
}
@Override
public String findSessionId(HttpServerExchange exchange) {
return topLevel.getId();
}
@Override
public SessionCookieSource sessionCookieSource(HttpServerExchange exchange) {
return SessionCookieSource.NONE;
}
@Override
public String rewriteUrl(String originalUrl, String sessionId) {
return null;
}
};
//first we check if there is a session with this id already
//this can happen with a shared session manager
session = sessionManager.getSession(exchange, c);
if (session != null) {
httpSession = SecurityActions.forSession(session, this, false);
exchange.putAttachment(sessionAttachmentKey, httpSession);
}
} else if (existing != null) {
if(getDeploymentInfo().isCheckOtherSessionManagers()) {
boolean found = false;
for (String deploymentName : deployment.getServletContainer().listDeployments()) {
DeploymentManager deployment = this.deployment.getServletContainer().getDeployment(deploymentName);
if (deployment != null) {
if (deployment.getDeployment().getSessionManager().getSession(existing) != null) {
found = true;
break;
}
}
}
if (!found) {
c.clearSession(exchange, existing);
}
} else {
c.clearSession(exchange, existing);
}
}
if (httpSession == null) {
final Session newSession = sessionManager.createSession(exchange, c);
httpSession = SecurityActions.forSession(newSession, this, true);
exchange.putAttachment(sessionAttachmentKey, httpSession);
}
}
}
return httpSession;
}
/**
* Gets the session
*
* @param create
* @return
*/
public HttpSessionImpl getSession(final HttpServerExchange exchange, boolean create) {
return getSession(this, exchange, create);
}
public void updateSessionAccessTime(final HttpServerExchange exchange) {
HttpSessionImpl httpSession = getSession(exchange, false);
if (httpSession != null) {
Session underlyingSession;
if (System.getSecurityManager() == null) {