-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
QuickStartGeneratorConfiguration.java
817 lines (707 loc) · 31.7 KB
/
QuickStartGeneratorConfiguration.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
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.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.quickstart;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.servlet.DispatcherType;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspPropertyGroupDescriptor;
import javax.servlet.descriptor.TaglibDescriptor;
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.plus.annotation.LifeCycleCallback;
import org.eclipse.jetty.plus.annotation.LifeCycleCallbackCollection;
import org.eclipse.jetty.security.ConstraintAware;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.security.authentication.FormAuthenticator;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ListenerHolder;
import org.eclipse.jetty.servlet.ServletContextHandler.JspConfig;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletMapping;
import org.eclipse.jetty.servlet.Source;
import org.eclipse.jetty.util.QuotedStringTokenizer;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.webapp.AbstractConfiguration;
import org.eclipse.jetty.webapp.MetaData;
import org.eclipse.jetty.webapp.MetaData.OriginInfo;
import org.eclipse.jetty.webapp.MetaInfConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.xml.XmlAppendable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* QuickStartGeneratorConfiguration
* <p>
* Generate an effective web.xml from a WebAppContext, including all components
* from web.xml, web-fragment.xmls annotations etc.
* <p>
* If generating quickstart for a different java platform than the current running
* platform, then the org.eclipse.jetty.annotations.javaTargetPlatform attribute
* should be set on the Context with the platform number of the target JVM (eg 8).
*/
public class QuickStartGeneratorConfiguration extends AbstractConfiguration
{
static final Logger LOG = LoggerFactory.getLogger(QuickStartGeneratorConfiguration.class);
public static final String ORIGIN = "org.eclipse.jetty.originAttribute";
public static final String DEFAULT_ORIGIN_ATTRIBUTE_NAME = "origin";
protected final boolean _abort;
protected String _originAttribute;
protected int _count;
protected Resource _quickStartWebXml;
public QuickStartGeneratorConfiguration()
{
this(false);
}
public QuickStartGeneratorConfiguration(boolean abort)
{
super(false);
_count = 0;
_abort = abort;
}
@Override
public boolean abort(WebAppContext context)
{
return _abort;
}
public void setOriginAttribute(String name)
{
_originAttribute = name;
}
/**
* @return the originAttribute
*/
public String getOriginAttribute()
{
return _originAttribute;
}
public Resource getQuickStartWebXml()
{
return _quickStartWebXml;
}
public void setQuickStartWebXml(Resource quickStartWebXml)
{
_quickStartWebXml = quickStartWebXml;
}
/**
* Perform the generation of the xml file
*
* @param stream the stream to generate the quickstart-web.xml to
* @throws IOException if unable to generate the quickstart-web.xml
* @throws FileNotFoundException if unable to find the file
*/
public void generateQuickStartWebXml(WebAppContext context, OutputStream stream) throws FileNotFoundException, IOException
{
if (context == null)
throw new IllegalStateException("No webapp for quickstart generation");
if (stream == null)
throw new IllegalStateException("No output for quickstart generation");
if (_originAttribute == null)
_originAttribute = DEFAULT_ORIGIN_ATTRIBUTE_NAME;
context.getMetaData().getOrigins();
if (context.getBaseResource() == null)
throw new IllegalArgumentException("No base resource for " + this);
MetaData md = context.getMetaData();
Map<String, String> webappAttr = new HashMap<>();
int major = context.getServletContext().getEffectiveMajorVersion();
int minor = context.getServletContext().getEffectiveMinorVersion();
webappAttr.put("xmlns", "http://xmlns.jcp.org/xml/ns/javaee");
webappAttr.put("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
webappAttr.put("xsi:schemaLocation", "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_" + (major + "_" + minor) + ".xsd");
webappAttr.put("metadata-complete", Boolean.toString(context.getMetaData().isMetaDataComplete()));
webappAttr.put("version", major + "." + minor);
XmlAppendable out = new XmlAppendable(stream, "UTF-8");
out.openTag("web-app", webappAttr);
if (context.getDisplayName() != null)
out.tag("display-name", context.getDisplayName());
// Set some special context parameters
// The location of the war file on disk
AttributeNormalizer normalizer = new AttributeNormalizer(context.getBaseResource());
// The library order
addContextParamFromAttribute(context, out, ServletContext.ORDERED_LIBS);
//the servlet container initializers
addContextParamFromAttribute(context, out, AnnotationConfiguration.CONTAINER_INITIALIZERS);
//the tlds discovered
addContextParamFromAttribute(context, out, MetaInfConfiguration.METAINF_TLDS, normalizer);
//the META-INF/resources discovered
addContextParamFromAttribute(context, out, MetaInfConfiguration.METAINF_RESOURCES, normalizer);
// the default-context-path, if present
String defaultContextPath = (String)context.getAttribute("default-context-path");
if (defaultContextPath != null)
out.tag("default-context-path", defaultContextPath);
String requestEncoding = (String)context.getAttribute("request-character-encoding");
if (!StringUtil.isBlank(requestEncoding))
out.tag("request-character-encoding", requestEncoding);
String responseEncoding = (String)context.getAttribute("response-character-encoding");
if (!StringUtil.isBlank(responseEncoding))
out.tag("response-character-encoding", responseEncoding);
//add the name of the origin attribute, if it is being used
if (StringUtil.isNotBlank(_originAttribute))
{
out.openTag("context-param")
.tag("param-name", ORIGIN)
.tag("param-value", _originAttribute)
.closeTag();
}
// init params
for (String p : context.getInitParams().keySet())
{
out.openTag("context-param", origin(md, "context-param." + p))
.tag("param-name", p)
.tag("param-value", context.getInitParameter(p))
.closeTag();
}
if (context.getServletHandler().getListeners() != null)
for (ListenerHolder e : context.getServletHandler().getListeners())
{
if (e.getSource() == Source.EMBEDDED)
continue;
out.openTag("listener", origin(md, e.getClassName() + ".listener"))
.tag("listener-class", e.getClassName())
.closeTag();
}
ServletHandler servlets = context.getServletHandler();
if (servlets.getFilters() != null)
{
for (FilterHolder holder : servlets.getFilters())
{
if (holder.getSource() == Source.EMBEDDED)
continue;
outholder(out, md, holder);
}
}
if (servlets.getFilterMappings() != null)
{
for (FilterMapping mapping :servlets.getFilterMappings())
{
FilterHolder f = servlets.getFilter(mapping.getFilterName());
if (f != null && f.getSource() == Source.EMBEDDED)
continue;
out.openTag("filter-mapping");
out.tag("filter-name", mapping.getFilterName());
if (mapping.getPathSpecs() != null)
for (String s : mapping.getPathSpecs())
{
out.tag("url-pattern", s);
}
if (mapping.getServletNames() != null)
for (String n : mapping.getServletNames())
{
out.tag("servlet-name", n);
}
if (!mapping.isDefaultDispatches())
{
if (mapping.appliesTo(DispatcherType.REQUEST))
out.tag("dispatcher", "REQUEST");
if (mapping.appliesTo(DispatcherType.ASYNC))
out.tag("dispatcher", "ASYNC");
if (mapping.appliesTo(DispatcherType.ERROR))
out.tag("dispatcher", "ERROR");
if (mapping.appliesTo(DispatcherType.FORWARD))
out.tag("dispatcher", "FORWARD");
if (mapping.appliesTo(DispatcherType.INCLUDE))
out.tag("dispatcher", "INCLUDE");
}
out.closeTag();
}
}
if (servlets.getServlets() != null)
{
for (ServletHolder holder : servlets.getServlets())
{
if (holder.getSource() == Source.EMBEDDED)
continue;
outholder(out, md, holder);
}
}
if (servlets.getServletMappings() != null)
{
for (ServletMapping mapping : servlets.getServletMappings())
{
ServletHolder sh = servlets.getServlet(mapping.getServletName());
if (sh != null && sh.getSource() == Source.EMBEDDED)
continue;
out.openTag("servlet-mapping", origin(md, mapping.getServletName() + ".servlet.mappings"));
out.tag("servlet-name", mapping.getServletName());
if (mapping.getPathSpecs() != null)
for (String s : mapping.getPathSpecs())
{
out.tag("url-pattern", s);
}
out.closeTag();
}
}
// Security elements
SecurityHandler security = context.getSecurityHandler();
if (security != null && (security.getRealmName() != null || security.getAuthMethod() != null))
{
out.openTag("login-config");
if (security.getAuthMethod() != null)
out.tag("auth-method", origin(md, "auth-method"), security.getAuthMethod());
if (security.getRealmName() != null)
out.tag("realm-name", origin(md, "realm-name"), security.getRealmName());
if (Constraint.__FORM_AUTH.equalsIgnoreCase(security.getAuthMethod()))
{
out.openTag("form-login-config");
out.tag("form-login-page", origin(md, "form-login-page"), security.getInitParameter(FormAuthenticator.__FORM_LOGIN_PAGE));
out.tag("form-error-page", origin(md, "form-error-page"), security.getInitParameter(FormAuthenticator.__FORM_ERROR_PAGE));
out.closeTag();
}
out.closeTag();
}
if (security instanceof ConstraintAware)
{
ConstraintAware ca = (ConstraintAware)security;
for (String r : ca.getRoles())
{
out.openTag("security-role")
.tag("role-name", r)
.closeTag();
}
for (ConstraintMapping m : ca.getConstraintMappings())
{
out.openTag("security-constraint");
out.openTag("web-resource-collection");
{
if (m.getConstraint().getName() != null)
out.tag("web-resource-name", m.getConstraint().getName());
if (m.getPathSpec() != null)
out.tag("url-pattern", origin(md, "constraint.url." + m.getPathSpec()), m.getPathSpec());
if (m.getMethod() != null)
out.tag("http-method", m.getMethod());
if (m.getMethodOmissions() != null)
for (String o : m.getMethodOmissions())
{
out.tag("http-method-omission", o);
}
out.closeTag();
}
if (m.getConstraint().getAuthenticate())
{
String[] roles = m.getConstraint().getRoles();
if (roles != null && roles.length > 0)
{
out.openTag("auth-constraint");
if (m.getConstraint().getRoles() != null)
for (String r : m.getConstraint().getRoles())
{
out.tag("role-name", r);
}
out.closeTag();
}
else
out.tag("auth-constraint");
}
switch (m.getConstraint().getDataConstraint())
{
case Constraint.DC_NONE:
out.openTag("user-data-constraint").tag("transport-guarantee", "NONE").closeTag();
break;
case Constraint.DC_INTEGRAL:
out.openTag("user-data-constraint").tag("transport-guarantee", "INTEGRAL").closeTag();
break;
case Constraint.DC_CONFIDENTIAL:
out.openTag("user-data-constraint").tag("transport-guarantee", "CONFIDENTIAL").closeTag();
break;
default:
break;
}
out.closeTag();
}
}
if (context.getWelcomeFiles() != null)
{
out.openTag("welcome-file-list");
for (String welcomeFile : context.getWelcomeFiles())
{
out.tag("welcome-file", welcomeFile);
}
out.closeTag();
}
Map<String, String> localeEncodings = context.getLocaleEncodings();
if (localeEncodings != null && !localeEncodings.isEmpty())
{
out.openTag("locale-encoding-mapping-list");
for (Map.Entry<String, String> entry : localeEncodings.entrySet())
{
out.openTag("locale-encoding-mapping", origin(md, "locale-encoding." + entry.getKey()));
out.tag("locale", entry.getKey());
out.tag("encoding", entry.getValue());
out.closeTag();
}
out.closeTag();
}
//session-config
if (context.getSessionHandler() != null)
{
out.openTag("session-config");
int maxInactiveSec = context.getSessionHandler().getMaxInactiveInterval();
out.tag("session-timeout", (maxInactiveSec == 0 ? "0" : Integer.toString(maxInactiveSec / 60)));
//cookie-config
SessionCookieConfig cookieConfig = context.getSessionHandler().getSessionCookieConfig();
if (cookieConfig != null)
{
out.openTag("cookie-config");
if (cookieConfig.getName() != null)
out.tag("name", origin(md, "cookie-config.name"), cookieConfig.getName());
if (cookieConfig.getDomain() != null)
out.tag("domain", origin(md, "cookie-config.domain"), cookieConfig.getDomain());
if (cookieConfig.getPath() != null)
out.tag("path", origin(md, "cookie-config.path"), cookieConfig.getPath());
if (cookieConfig.getComment() != null)
out.tag("comment", origin(md, "cookie-config.comment"), cookieConfig.getComment());
out.tag("http-only", origin(md, "cookie-config.http-only"), Boolean.toString(cookieConfig.isHttpOnly()));
out.tag("secure", origin(md, "cookie-config.secure"), Boolean.toString(cookieConfig.isSecure()));
out.tag("max-age", origin(md, "cookie-config.max-age"), Integer.toString(cookieConfig.getMaxAge()));
out.closeTag();
}
// tracking-modes
Set<SessionTrackingMode> modes = context.getSessionHandler().getEffectiveSessionTrackingModes();
if (modes != null)
{
for (SessionTrackingMode mode : modes)
{
out.tag("tracking-mode", mode.toString());
}
}
out.closeTag();
}
//error-pages
Map<String, String> errorPages = ((ErrorPageErrorHandler)context.getErrorHandler()).getErrorPages();
if (errorPages != null)
{
for (Map.Entry<String, String> entry : errorPages.entrySet())
{
out.openTag("error-page", origin(md, "error." + entry.getKey()));
//a global or default error page has no code or exception
if (!ErrorPageErrorHandler.GLOBAL_ERROR_PAGE.equals(entry.getKey()))
{
if (entry.getKey().matches("\\d{3}"))
out.tag("error-code", entry.getKey());
else
out.tag("exception-type", entry.getKey());
}
out.tag("location", entry.getValue());
out.closeTag();
}
}
//mime-types
MimeTypes mimeTypes = context.getMimeTypes();
if (mimeTypes != null)
{
for (Map.Entry<String, String> entry : mimeTypes.getMimeMap().entrySet())
{
out.openTag("mime-mapping");
out.tag("extension", origin(md, "extension." + entry.getKey()), entry.getKey());
out.tag("mime-type", entry.getValue());
out.closeTag();
}
}
//jsp-config
JspConfig jspConfig = (JspConfig)context.getServletContext().getJspConfigDescriptor();
if (jspConfig != null)
{
out.openTag("jsp-config");
Collection<TaglibDescriptor> tlds = jspConfig.getTaglibs();
if (tlds != null && !tlds.isEmpty())
{
for (TaglibDescriptor tld : tlds)
{
out.openTag("taglib");
out.tag("taglib-uri", tld.getTaglibURI());
out.tag("taglib-location", tld.getTaglibLocation());
out.closeTag();
}
}
Collection<JspPropertyGroupDescriptor> jspPropertyGroups = jspConfig.getJspPropertyGroups();
if (jspPropertyGroups != null && !jspPropertyGroups.isEmpty())
{
for (JspPropertyGroupDescriptor jspPropertyGroup : jspPropertyGroups)
{
out.openTag("jsp-property-group");
Collection<String> strings = jspPropertyGroup.getUrlPatterns();
if (strings != null && !strings.isEmpty())
{
for (String urlPattern : strings)
{
out.tag("url-pattern", urlPattern);
}
}
if (jspPropertyGroup.getElIgnored() != null)
out.tag("el-ignored", jspPropertyGroup.getElIgnored());
if (jspPropertyGroup.getPageEncoding() != null)
out.tag("page-encoding", jspPropertyGroup.getPageEncoding());
if (jspPropertyGroup.getScriptingInvalid() != null)
out.tag("scripting-invalid", jspPropertyGroup.getScriptingInvalid());
if (jspPropertyGroup.getIsXml() != null)
out.tag("is-xml", jspPropertyGroup.getIsXml());
if (jspPropertyGroup.getDeferredSyntaxAllowedAsLiteral() != null)
out.tag("deferred-syntax-allowed-as-literal", jspPropertyGroup.getDeferredSyntaxAllowedAsLiteral());
if (jspPropertyGroup.getTrimDirectiveWhitespaces() != null)
out.tag("trim-directive-whitespaces", jspPropertyGroup.getTrimDirectiveWhitespaces());
if (jspPropertyGroup.getDefaultContentType() != null)
out.tag("default-content-type", jspPropertyGroup.getDefaultContentType());
if (jspPropertyGroup.getBuffer() != null)
out.tag("buffer", jspPropertyGroup.getBuffer());
if (jspPropertyGroup.getErrorOnUndeclaredNamespace() != null)
out.tag("error-on-undeclared-namespace", jspPropertyGroup.getErrorOnUndeclaredNamespace());
strings = jspPropertyGroup.getIncludePreludes();
if (strings != null && !strings.isEmpty())
{
for (String prelude : strings)
{
out.tag("include-prelude", prelude);
}
}
strings = jspPropertyGroup.getIncludeCodas();
if (strings != null && !strings.isEmpty())
{
for (String coda : strings)
{
out.tag("include-coda", coda);
}
}
out.closeTag();
}
}
out.closeTag();
}
//lifecycle: post-construct, pre-destroy
LifeCycleCallbackCollection lifecycles = ((LifeCycleCallbackCollection)context.getAttribute(LifeCycleCallbackCollection.LIFECYCLE_CALLBACK_COLLECTION));
if (lifecycles != null)
{
Collection<LifeCycleCallback> tmp = lifecycles.getPostConstructCallbacks();
for (LifeCycleCallback c : tmp)
{
out.openTag("post-construct");
out.tag("lifecycle-callback-class", c.getTargetClassName());
out.tag("lifecycle-callback-method", c.getMethodName());
out.closeTag();
}
tmp = lifecycles.getPreDestroyCallbacks();
for (LifeCycleCallback c : tmp)
{
out.openTag("pre-destroy");
out.tag("lifecycle-callback-class", c.getTargetClassName());
out.tag("lifecycle-callback-method", c.getMethodName());
out.closeTag();
}
}
ExtraXmlDescriptorProcessor extraXmlProcessor = (ExtraXmlDescriptorProcessor)context.getAttribute(ExtraXmlDescriptorProcessor.class.getName());
out.literal(extraXmlProcessor.getXML());
out.closeTag();
}
/**
* Turn attribute into context-param to store.
*/
private void addContextParamFromAttribute(WebAppContext context, XmlAppendable out, String attribute) throws IOException
{
Object o = context.getAttribute(attribute);
if (o == null)
return;
Collection<?> c = (o instanceof Collection) ? (Collection<?>)o : Collections.singletonList(o);
StringBuilder v = new StringBuilder();
for (Object i : c)
{
if (i != null)
{
if (v.length() > 0)
v.append(",\n ");
else
v.append("\n ");
QuotedStringTokenizer.quote(v, i.toString());
}
}
out.openTag("context-param")
.tag("param-name", attribute)
.tagCDATA("param-value", v.toString())
.closeTag();
}
/**
* Turn context attribute into context-param to store.
*/
private void addContextParamFromAttribute(WebAppContext context, XmlAppendable out, String attribute, AttributeNormalizer normalizer) throws IOException
{
Object o = context.getAttribute(attribute);
if (o == null)
return;
Collection<?> c = (o instanceof Collection) ? (Collection<?>)o : Collections.singletonList(o);
StringBuilder v = new StringBuilder();
for (Object i : c)
{
if (i != null)
{
if (v.length() > 0)
v.append(",\n ");
else
v.append("\n ");
QuotedStringTokenizer.quote(v, normalizer.normalize(i));
}
}
out.openTag("context-param")
.tag("param-name", attribute)
.tagCDATA("param-value", v.toString())
.closeTag();
}
/**
* Generate xml for a Holder (Filter/Servlet)
*/
private void outholder(XmlAppendable out, MetaData md, FilterHolder holder) throws IOException
{
if (LOG.isDebugEnabled())
out.openTag("filter", Collections.singletonMap("source", holder.getSource().toString()));
else
out.openTag("filter");
String n = holder.getName();
out.tag("filter-name", n);
String ot = n + ".filter.";
if (holder instanceof FilterHolder)
{
out.tag("filter-class", origin(md, ot + "filter-class"), holder.getClassName());
out.tag("async-supported", origin(md, ot + "async-supported"), holder.isAsyncSupported() ? "true" : "false");
}
for (String p : holder.getInitParameters().keySet())
{
out.openTag("init-param", origin(md, ot + "init-param." + p))
.tag("param-name", p)
.tag("param-value", holder.getInitParameter(p))
.closeTag();
}
out.closeTag();
}
private void outholder(XmlAppendable out, MetaData md, ServletHolder holder) throws IOException
{
if (LOG.isDebugEnabled())
out.openTag("servlet", Collections.singletonMap("source", holder.getSource().toString()));
else
out.openTag("servlet");
String n = holder.getName();
out.tag("servlet-name", n);
String ot = n + ".servlet.";
ServletHolder s = (ServletHolder)holder;
if (s.getForcedPath() != null && s.getClassName() == null)
out.tag("jsp-file", s.getForcedPath());
else
out.tag("servlet-class", origin(md, ot + "servlet-class"), s.getClassName());
for (String p : holder.getInitParameters().keySet())
{
if ("jsp".equalsIgnoreCase(n) && "scratchdir".equalsIgnoreCase(p)) //don't preconfigure the temp dir for jsp output
continue;
out.openTag("init-param", origin(md, ot + "init-param." + p))
.tag("param-name", p)
.tag("param-value", holder.getInitParameter(p))
.closeTag();
}
if (s.getInitOrder() >= 0)
out.tag("load-on-startup", Integer.toString(s.getInitOrder()));
if (!s.isEnabled())
out.tag("enabled", origin(md, ot + "enabled"), "false");
out.tag("async-supported", origin(md, ot + "async-supported"), holder.isAsyncSupported() ? "true" : "false");
if (s.getRunAsRole() != null)
out.openTag("run-as", origin(md, ot + "run-as"))
.tag("role-name", s.getRunAsRole())
.closeTag();
Map<String, String> roles = s.getRoleRefMap();
if (roles != null)
{
for (Map.Entry<String, String> e : roles.entrySet())
{
out.openTag("security-role-ref", origin(md, ot + "role-name." + e.getKey()))
.tag("role-name", e.getKey())
.tag("role-link", e.getValue())
.closeTag();
}
}
//multipart-config
MultipartConfigElement multipartConfig = ((ServletHolder.Registration)s.getRegistration()).getMultipartConfig();
if (multipartConfig != null)
{
out.openTag("multipart-config", origin(md, s.getName() + ".servlet.multipart-config"));
if (multipartConfig.getLocation() != null)
out.tag("location", multipartConfig.getLocation());
out.tag("max-file-size", Long.toString(multipartConfig.getMaxFileSize()));
out.tag("max-request-size", Long.toString(multipartConfig.getMaxRequestSize()));
out.tag("file-size-threshold", Long.toString(multipartConfig.getFileSizeThreshold()));
out.closeTag();
}
out.closeTag();
}
/**
* Find the origin (web.xml, fragment, annotation etc) of a web artifact from MetaData.
*
* @param md the metadata
* @param name the name
* @return the origin map
*/
public Map<String, String> origin(MetaData md, String name)
{
if (StringUtil.isBlank(_originAttribute))
return Collections.emptyMap();
if (name == null)
return Collections.emptyMap();
OriginInfo origin = md.getOriginInfo(name);
if (LOG.isDebugEnabled())
LOG.debug("origin of {} is {}", name, origin);
if (origin == null)
return Collections.emptyMap();
return Collections.singletonMap(_originAttribute, origin.toString() + ":" + (_count++));
}
@Override
public void preConfigure(WebAppContext context) throws Exception
{
ExtraXmlDescriptorProcessor extraXmlProcessor = new ExtraXmlDescriptorProcessor();
context.getMetaData().addDescriptorProcessor(extraXmlProcessor);
context.setAttribute(ExtraXmlDescriptorProcessor.class.getName(), extraXmlProcessor);
super.preConfigure(context);
}
@Override
public void configure(WebAppContext context) throws Exception
{
MetaData metadata = context.getMetaData();
metadata.resolve(context);
try (FileOutputStream fos = new FileOutputStream(_quickStartWebXml.getFile(), false))
{
generateQuickStartWebXml(context, fos);
LOG.info("Generated {}", _quickStartWebXml);
if (context.getAttribute(WebInfConfiguration.TEMPORARY_RESOURCE_BASE) != null && !context.isPersistTempDirectory())
LOG.warn("Generated to non persistent location: {}", _quickStartWebXml);
}
}
@Override
public void deconfigure(WebAppContext context) throws Exception
{
super.deconfigure(context);
}
}