/
InternalTemplateManager.java
1232 lines (998 loc) · 37.3 KB
/
InternalTemplateManager.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
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.xpn.xwiki.internal.template;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.xwiki.cache.Cache;
import org.xwiki.cache.CacheControl;
import org.xwiki.cache.CacheException;
import org.xwiki.cache.CacheManager;
import org.xwiki.cache.config.LRUCacheConfiguration;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLifecycleException;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.phase.Disposable;
import org.xwiki.component.phase.Initializable;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.environment.Environment;
import org.xwiki.filter.input.InputSource;
import org.xwiki.filter.input.InputStreamInputSource;
import org.xwiki.filter.input.ReaderInputSource;
import org.xwiki.filter.input.StringInputSource;
import org.xwiki.job.event.status.JobProgressManager;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.properties.BeanManager;
import org.xwiki.properties.ConverterManager;
import org.xwiki.properties.PropertyException;
import org.xwiki.properties.RawProperties;
import org.xwiki.properties.annotation.PropertyHidden;
import org.xwiki.properties.annotation.PropertyId;
import org.xwiki.rendering.async.internal.AsyncRendererConfiguration;
import org.xwiki.rendering.async.internal.block.BlockAsyncRendererExecutor;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.CompositeBlock;
import org.xwiki.rendering.block.RawBlock;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.parser.ContentParser;
import org.xwiki.rendering.renderer.BlockRenderer;
import org.xwiki.rendering.renderer.printer.WikiPrinter;
import org.xwiki.rendering.renderer.printer.WriterWikiPrinter;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.transformation.RenderingContext;
import org.xwiki.rendering.util.ErrorBlockGenerator;
import org.xwiki.skin.Resource;
import org.xwiki.skin.ResourceRepository;
import org.xwiki.skin.Skin;
import org.xwiki.template.Template;
import org.xwiki.template.TemplateContent;
import org.xwiki.template.TemplateRequirement;
import org.xwiki.template.TemplateRequirementsException;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.internal.skin.AbstractSkinResource;
import com.xpn.xwiki.internal.skin.InternalSkinManager;
import com.xpn.xwiki.internal.skin.WikiResource;
import com.xpn.xwiki.user.api.XWikiRightService;
/**
* Internal toolkit to experiment on templates.
*
* @version $Id$
* @since 7.0M1
*/
@Component(roles = InternalTemplateManager.class)
@Singleton
public class InternalTemplateManager implements Initializable, Disposable
{
/**
* The reference of the superadmin user.
*/
public static final DocumentReference SUPERADMIN_REFERENCE =
new DocumentReference("xwiki", XWiki.SYSTEM_SPACE, XWikiRightService.SUPERADMIN_USER);
private static final Pattern PROPERTY_LINE = Pattern.compile("^##!(.+)=(.*)$\r?\n?", Pattern.MULTILINE);
private static final String TEMPLATE_RESOURCE_SUFFIX = "/templates/";
private static final String PROPERTY_REQUIRE_PREFIX = "require.";
@Inject
private Environment environment;
@Inject
private ContentParser parser;
@Inject
@Named("context")
private Provider<ComponentManager> componentManagerProvider;
@Inject
private RenderingContext renderingContext;
@Inject
@Named("plain/1.0")
private BlockRenderer plainRenderer;
@Inject
@Named("xwikicfg")
private ConfigurationSource xwikicfg;
@Inject
@Named("all")
private ConfigurationSource allConfiguration;
@Inject
@Named("currentmixed")
private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver;
@Inject
private BeanManager beanManager;
@Inject
private ConverterManager converter;
@Inject
private InternalSkinManager skins;
@Inject
private JobProgressManager progress;
@Inject
private Provider<TemplateAsyncRenderer> rendererProvider;
@Inject
private BlockAsyncRendererExecutor asyncExecutor;
@Inject
private TemplateContext templateContext;
@Inject
private VelocityTemplateEvaluator evaluator;
@Inject
private Provider<ErrorBlockGenerator> errorBlockGeneratorProvider;
@Inject
private CacheManager cacheManager;
@Inject
private CacheControl cacheControl;
@Inject
private Logger logger;
private String templateRootURL;
private Cache<Template> templateCache;
private abstract static class AbtractTemplate<T extends TemplateContent, R extends Resource<?>> implements Template
{
protected R resource;
protected T content;
protected Instant instant;
public AbtractTemplate(R resource)
{
this.resource = resource;
}
@Override
public String getId()
{
return this.resource.getId();
}
@Override
public String getPath()
{
return this.resource.getPath();
}
@Override
public TemplateContent getContent() throws Exception
{
if (this.content == null) {
try {
this.instant = this.resource.getInstant();
} catch (Exception e) {
// Failed to get the resource instant, it's unknown
}
this.content = loadContent();
} else if (this.instant != null) {
// Check if the resource has been modified
Instant resourceInstant = this.resource.getInstant();
if (resourceInstant.isAfter(this.instant)) {
// The resource changed, reload it
this.instant = resourceInstant;
this.content = loadContent();
}
}
return this.content;
}
protected T loadContent() throws Exception
{
String strinContent;
try (InputSource source = this.resource.getInputSource()) {
if (source instanceof StringInputSource) {
strinContent = source.toString();
} else if (source instanceof ReaderInputSource) {
strinContent = IOUtils.toString(((ReaderInputSource) source).getReader());
} else if (source instanceof InputStreamInputSource) {
// It's impossible to know the real attachment encoding, but let's assume that they respect the
// standard and use UTF-8 (which is required for the files located on the filesystem)
strinContent =
IOUtils.toString(((InputStreamInputSource) source).getInputStream(), StandardCharsets.UTF_8);
} else {
return null;
}
}
return getContentInternal(strinContent);
}
protected abstract T getContentInternal(String content) throws Exception;
@Override
public Instant getInstant()
{
return this.instant;
}
@Override
public String toString()
{
return this.resource.getId();
}
}
private class EnvironmentTemplate extends AbtractTemplate<FilesystemTemplateContent, AbstractSkinResource>
{
EnvironmentTemplate(AbstractSkinResource resource)
{
super(resource);
}
@Override
protected FilesystemTemplateContent getContentInternal(String content)
{
return new FilesystemTemplateContent(content);
}
}
private class ClassloaderTemplate extends AbtractTemplate<FilesystemTemplateContent, ClassloaderResource>
{
ClassloaderTemplate(ClassloaderResource resource)
{
super(resource);
}
@Override
protected FilesystemTemplateContent getContentInternal(String content)
{
return new FilesystemTemplateContent(content);
}
}
private class DefaultTemplate extends AbtractTemplate<DefaultTemplateContent, Resource<?>>
{
DefaultTemplate(Resource<?> resource)
{
super(resource);
}
@Override
protected DefaultTemplateContent getContentInternal(String content)
{
if (this.resource instanceof WikiResource) {
WikiResource<?> wikiResource = ((WikiResource<?>) this.resource);
return new DefaultTemplateContent(content, wikiResource.getAuthorReference(),
wikiResource.getDocumentReference());
} else {
return new DefaultTemplateContent(content);
}
}
}
private class StringTemplate extends DefaultTemplate
{
StringTemplate(String id, String content, DocumentReference authorReference, DocumentReference documentReference)
throws Exception
{
super(new StringResource(id, content));
// As StringTemplate extends DefaultTemplate, the TemplateContent is DefaultTemplateContent
((DefaultTemplateContent) this.getContent()).setAuthorReference(authorReference);
((DefaultTemplateContent) this.getContent()).setDocumentReference(documentReference);
}
}
class DefaultTemplateContent implements RawProperties, TemplateContent
{
protected String content;
protected boolean authorProvided;
protected DocumentReference authorReference;
protected DocumentReference documentReference;
@PropertyId("source.syntax")
public Syntax sourceSyntax;
@PropertyId("raw.syntax")
public Syntax rawSyntax;
public boolean cacheAllowed;
public boolean asyncAllowed;
public Set<String> contextEntries;
public UniqueContext unique;
protected Map<String, Object> properties = new HashMap<>();
protected Object compiledContent;
DefaultTemplateContent(String content)
{
this.content = content;
init();
}
DefaultTemplateContent(String content, DocumentReference authorReference)
{
this(content);
setAuthorReference(authorReference);
}
DefaultTemplateContent(String content, DocumentReference authorReference, DocumentReference sourceReference)
{
this(content, authorReference);
setDocumentReference(sourceReference);
}
@Override
public Syntax getSourceSyntax()
{
return this.sourceSyntax;
}
@Override
public Syntax getRawSyntax()
{
return this.rawSyntax;
}
@Override
public boolean isAsyncAllowed()
{
return this.asyncAllowed;
}
@Override
public boolean isCacheAllowed()
{
return this.cacheAllowed;
}
@Override
public UniqueContext getUnique()
{
return this.unique;
}
@Override
public Set<String> getContextEntries()
{
if (this.contextEntries == null) {
return Collections.emptySet();
}
if (this.contextEntries instanceof AbstractSet) {
this.contextEntries = Collections.unmodifiableSet(this.contextEntries);
}
return this.contextEntries;
}
@Override
public <T> T getProperty(String name, T def)
{
if (!this.properties.containsKey(name)) {
return def;
}
if (def != null) {
return getProperty(name, def.getClass());
}
return (T) this.properties.get(name);
}
@Override
public <T> T getProperty(String name, Type type)
{
return converter.convert(type, this.properties.get(name));
}
@Override
public Collection<String> getPropertyNames()
{
return this.properties.keySet();
}
protected void init()
{
Matcher matcher = PROPERTY_LINE.matcher(this.content);
int newContentIndex = 0;
Map<String, String> map = new HashMap<>();
while (matcher.find()) {
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
// Remove the line from the content
newContentIndex = matcher.end();
}
if (newContentIndex > 0) {
this.content = this.content.substring(newContentIndex);
}
try {
InternalTemplateManager.this.beanManager.populate(this, map);
} catch (PropertyException e) {
// Should never happen
InternalTemplateManager.this.logger.error("Failed to populate properties of template", e);
}
}
@Override
public String getContent()
{
return this.content;
}
@PropertyHidden
@Override
public boolean isAuthorProvided()
{
return this.authorProvided;
}
@PropertyId("author")
@Override
public DocumentReference getAuthorReference()
{
return this.authorReference;
}
protected void setAuthorReference(DocumentReference authorReference)
{
this.authorReference = authorReference;
this.authorProvided = true;
}
@Override
public DocumentReference getDocumentReference()
{
return this.documentReference;
}
protected void setDocumentReference(DocumentReference documentReference)
{
this.documentReference = documentReference;
}
// RawProperties
@Override
public void set(String propertyName, Object value)
{
this.properties.put(propertyName, value);
}
}
private class FilesystemTemplateContent extends DefaultTemplateContent
{
public FilesystemTemplateContent(String content)
{
super(content);
// Give programming right to filesystem templates by default
setPrivileged(true);
}
/**
* {@inheritDoc}
* <p>
* Allow filesystem template to indicate the user to executed them with.
* </p>
*
* @see #setAuthorReference(DocumentReference)
*/
@Override
public void setAuthorReference(DocumentReference authorReference)
{
super.setAuthorReference(authorReference);
}
/**
* Made public to be seen as bean property.
*
* @since 6.3.1
* @since 6.4M1
*/
@SuppressWarnings("unused")
public boolean isPrivileged()
{
return SUPERADMIN_REFERENCE.equals(getAuthorReference());
}
/**
* Made public to be seen as bean property.
*
* @since 6.3.1
* @since 6.4M1
*/
public void setPrivileged(boolean privileged)
{
if (privileged) {
setAuthorReference(SUPERADMIN_REFERENCE);
} else {
// Reset author
this.authorReference = null;
this.authorProvided = false;
}
}
}
@Override
public void initialize() throws InitializationException
{
getTemplateRootPath();
// Initialize the filesystem template cache
try {
this.templateCache = cacheManager.createNewCache(new LRUCacheConfiguration("templates", 500));
} catch (CacheException e) {
this.logger.error("Failed to create the filesystem template cache", e);
}
}
@Override
public void dispose() throws ComponentLifecycleException
{
if (this.templateCache != null) {
this.templateCache.dispose();
}
}
private void checkRequirements(Template template) throws Exception
{
ComponentManager componentManager = this.componentManagerProvider.get();
List<Throwable> causes = null;
TemplateContent templateContent = template.getContent();
for (String propertyName : templateContent.getPropertyNames()) {
if (propertyName.startsWith(PROPERTY_REQUIRE_PREFIX)) {
String requirementKey = propertyName.substring(PROPERTY_REQUIRE_PREFIX.length());
if (componentManager.hasComponent(TemplateRequirement.class, requirementKey)) {
try {
TemplateRequirement requirement =
componentManager.getInstance(TemplateRequirement.class, requirementKey);
requirement.checkRequirement(requirementKey,
templateContent.getProperty(propertyName, (String) null), template);
} catch (Exception e) {
if (causes == null) {
causes = new ArrayList<>();
}
causes.add(e);
}
} else {
this.logger.warn("No template requirement handler could be found for key [{}] in template [{}]",
propertyName, template.getId());
}
}
}
if (causes != null) {
throw new TemplateRequirementsException(template.getId(), causes);
}
}
private String getTemplateRootPath()
{
if (this.templateRootURL == null) {
URL url = this.environment.getResource(TEMPLATE_RESOURCE_SUFFIX);
if (url != null) {
this.templateRootURL = url.toString();
}
}
return this.templateRootURL;
}
private boolean checkFilesystemTemplate(String templatePath)
{
URL templateURL = this.environment.getResource(templatePath);
// Check if the resource exist
if (templateURL == null) {
return false;
}
// Prevent inclusion of templates from other directories
String rootTemplate = getTemplateRootPath();
if (rootTemplate != null) {
String templateURLString = templateURL.toString();
if (!templateURLString.startsWith(getTemplateRootPath())) {
this.logger.warn("Direct access to template file [{}] refused. Possible break-in attempt!",
templateURLString);
return false;
}
}
return true;
}
private void renderError(Throwable throwable, boolean inline, Writer writer)
{
Block block = generateError(throwable, inline);
render(block, writer);
}
private Block generateError(Throwable throwable, boolean inline)
{
List<Block> errorBlocks;
if (throwable instanceof TemplateRequirementsException) {
errorBlocks = this.errorBlockGeneratorProvider.get().generateErrorBlocks(inline,
TemplateRequirementsException.TRANSLATION_KEY, throwable.getMessage(), null, throwable);
} else {
errorBlocks = this.errorBlockGeneratorProvider.get().generateErrorBlocks(inline, null,
"Failed to execute template", null, throwable);
}
if (inline) {
if (errorBlocks.size() == 1) {
return errorBlocks.get(0);
} else {
return new CompositeBlock(errorBlocks);
}
} else {
return new XDOM(errorBlocks);
}
}
/**
* @param templateName the template to parse
* @return the result of the template parsing
*/
public XDOM getXDOMNoException(String templateName)
{
XDOM xdom;
try {
xdom = getXDOM(templateName);
} catch (Throwable e) {
this.logger.error("Error while getting template [{}] XDOM", templateName, e);
xdom = (XDOM) generateError(e, false);
}
return xdom;
}
/**
* @param template the template to parse
* @return the result of the template parsing
* @since 8.3RC1
*/
public XDOM getXDOMNoException(Template template)
{
XDOM xdom;
try {
xdom = getXDOM(template);
} catch (Throwable e) {
this.logger.error("Error while getting template [{}] XDOM", template.getId(), e);
xdom = (XDOM) generateError(e, false);
}
return xdom;
}
public XDOM getXDOM(Template template) throws Exception
{
XDOM xdom;
if (template != null) {
xdom = getXDOM(template, template.getContent());
} else {
xdom = new XDOM(Collections.<Block>emptyList());
}
return xdom;
}
private XDOM getXDOM(Template template, TemplateContent content) throws Exception
{
XDOM xdom;
if (content.getSourceSyntax() != null) {
xdom = this.parser.parse(content.getContent(), content.getSourceSyntax());
} else {
String result = evaluateContent(template, content);
if (StringUtils.isEmpty(result)) {
xdom = new XDOM(Collections.emptyList());
} else {
xdom = new XDOM(Arrays.asList(new RawBlock(result, content.getRawSyntax() != null
? content.getRawSyntax() : this.renderingContext.getTargetSyntax())));
}
}
return xdom;
}
public XDOM getXDOM(String templateName) throws Exception
{
Template template = getTemplate(templateName);
return getXDOM(template);
}
public String renderNoException(String template, boolean inline)
{
Writer writer = new StringWriter();
renderNoException(template, inline, writer);
return writer.toString();
}
public void renderNoException(String templateName, boolean inline, Writer writer)
{
try {
render(templateName, inline, writer);
} catch (Exception e) {
this.logger.error("Error while rendering template [{}]", templateName, e);
renderError(e, inline, writer);
}
}
/**
* @since 8.3RC1
*/
public void renderNoException(Template template, boolean inline, Writer writer)
{
try {
render(template, inline, writer);
} catch (Exception e) {
this.logger.error("Error while rendering template [{}]", template, e);
renderError(e, inline, writer);
}
}
public String render(String templateName, boolean inline) throws Exception
{
return renderFromSkin(templateName, (Skin) null, inline);
}
public String renderFromSkin(String templateName, String skinId, boolean inline) throws Exception
{
Skin skin = this.skins.getSkin(skinId);
return skin != null ? renderFromSkin(templateName, skin, inline) : null;
}
public String renderFromSkin(String templateName, Skin skin, boolean inline) throws Exception
{
Writer writer = new StringWriter();
renderFromSkin(templateName, skin, inline, writer);
return writer.toString();
}
public void render(String templateName, boolean inline, Writer writer) throws Exception
{
renderFromSkin(templateName, null, inline, writer);
}
public void renderFromSkin(final String templateName, ResourceRepository repository, boolean inline,
final Writer writer) throws Exception
{
this.progress.startStep(templateName, "template.render.message", "Render template [{}]", templateName);
try {
final Template template =
repository != null ? getTemplate(templateName, repository) : getTemplate(templateName);
if (template != null) {
render(template, inline, writer);
}
} finally {
this.progress.endStep(templateName);
}
}
private AsyncRendererConfiguration configure(TemplateAsyncRenderer renderer, Template template, boolean inline,
boolean blockMode) throws Exception
{
Set<String> contextEntries = renderer.initialize(template, inline, blockMode);
AsyncRendererConfiguration configuration = new AsyncRendererConfiguration();
configuration.setContextEntries(contextEntries);
TemplateContent templateContent = template.getContent();
if (templateContent.isAuthorProvided()) {
configuration.setSecureReference(templateContent.getDocumentReference(),
templateContent.getAuthorReference());
}
return configuration;
}
public void render(Template template, boolean inline, Writer writer) throws Exception
{
if (!shouldExecute(template)) {
return;
}
// Make sure executing the template is allowed
checkRequirements(template);
TemplateAsyncRenderer renderer = this.rendererProvider.get();
AsyncRendererConfiguration configuration = configure(renderer, template, inline, false);
String result = this.asyncExecutor.render(renderer, configuration);
writer.append(result);
}
private boolean shouldExecute(Template template) throws Exception
{
return template != null
&& (template.getContent().getUnique() == null || !this.templateContext.isExecuted(template));
}
private void render(Block block, Writer writer)
{
WikiPrinter printer = new WriterWikiPrinter(writer);
BlockRenderer blockRenderer;
try {
blockRenderer =
this.componentManagerProvider.get().getInstance(BlockRenderer.class, getTargetSyntax().toIdString());
} catch (ComponentLookupException e) {
blockRenderer = this.plainRenderer;
}
blockRenderer.render(block, printer);
}
public Block executeNoException(String templateName, boolean inline)
{
Block block;
try {
block = execute(templateName, inline);
} catch (Throwable e) {
this.logger.error("Error while executing template [{}]", templateName, e);
block = generateError(e, inline);
}
return block;
}
/**
* @since 14.0RC1
*/
public Block executeNoException(Template template, boolean inline)
{
Block block;
try {
block = execute(template, inline);
} catch (Throwable e) {
this.logger.error("Error while executing template [{}]", template.getId(), e);
block = generateError(e, inline);
}
return block;
}
/**
* @since 14.0RC1
*/
public Block execute(String templateName, boolean inline) throws Exception
{
final Template template = getTemplate(templateName);
return execute(template, inline);
}
/**
* @since 14.0RC1
*/
public Block execute(Template template, boolean inline) throws Exception
{
if (!shouldExecute(template)) {
return new XDOM(Collections.emptyList());
}
// Make sure executing the template is allowed
checkRequirements(template);
TemplateAsyncRenderer renderer = this.rendererProvider.get();
AsyncRendererConfiguration configuration = configure(renderer, template, inline, true);
Block block = this.asyncExecutor.execute(renderer, configuration);
if (inline) {
return block;
}
return block instanceof XDOM ? block : new XDOM(Collections.singletonList(block));
}
private String evaluateContent(Template template, TemplateContent content) throws Exception
{
Writer writer = new StringWriter();