/
XWiki.java
7238 lines (6263 loc) · 282 KB
/
XWiki.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;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
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.TimeZone;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.ZipOutputStream;
import javax.annotation.Priority;
import javax.inject.Provider;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.NamingException;
import javax.script.ScriptContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.velocity.VelocityContext;
import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xwiki.bridge.event.DocumentCreatedEvent;
import org.xwiki.bridge.event.DocumentCreatingEvent;
import org.xwiki.bridge.event.DocumentDeletedEvent;
import org.xwiki.bridge.event.DocumentDeletingEvent;
import org.xwiki.bridge.event.DocumentRolledBackEvent;
import org.xwiki.bridge.event.DocumentRollingBackEvent;
import org.xwiki.bridge.event.DocumentUpdatedEvent;
import org.xwiki.bridge.event.DocumentUpdatingEvent;
import org.xwiki.bridge.event.WikiCopiedEvent;
import org.xwiki.bridge.event.WikiDeletedEvent;
import org.xwiki.cache.Cache;
import org.xwiki.classloader.ClassLoaderManager;
import org.xwiki.component.event.ComponentDescriptorAddedEvent;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.component.manager.NamespacedComponentManager;
import org.xwiki.component.util.DefaultParameterizedType;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.context.Execution;
import org.xwiki.edit.EditConfiguration;
import org.xwiki.job.Job;
import org.xwiki.job.JobException;
import org.xwiki.job.JobExecutor;
import org.xwiki.job.annotation.Serializable;
import org.xwiki.job.event.status.JobProgressManager;
import org.xwiki.job.event.status.JobStatus.State;
import org.xwiki.localization.ContextualLocalizationManager;
import org.xwiki.mail.MailListener;
import org.xwiki.mail.MailSender;
import org.xwiki.mail.MailSenderConfiguration;
import org.xwiki.mail.MailStatusResultSerializer;
import org.xwiki.mail.XWikiAuthenticator;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.AttachmentReference;
import org.xwiki.model.reference.AttachmentReferenceResolver;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.DocumentReferenceResolver;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceResolver;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.model.reference.LocalDocumentReference;
import org.xwiki.model.reference.ObjectReference;
import org.xwiki.model.reference.RegexEntityReference;
import org.xwiki.model.reference.SpaceReference;
import org.xwiki.model.reference.WikiReference;
import org.xwiki.observation.EventListener;
import org.xwiki.observation.ObservationManager;
import org.xwiki.observation.event.CancelableEvent;
import org.xwiki.observation.event.Event;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryFilter;
import org.xwiki.refactoring.batch.BatchOperationExecutor;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.Block.Axes;
import org.xwiki.rendering.block.MetaDataBlock;
import org.xwiki.rendering.block.match.MetadataBlockMatcher;
import org.xwiki.rendering.internal.transformation.MutableRenderingContext;
import org.xwiki.rendering.listener.MetaData;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.syntax.SyntaxContent;
import org.xwiki.rendering.transformation.RenderingContext;
import org.xwiki.resource.ResourceReference;
import org.xwiki.resource.ResourceReferenceManager;
import org.xwiki.resource.ResourceReferenceResolver;
import org.xwiki.resource.ResourceType;
import org.xwiki.resource.ResourceTypeResolver;
import org.xwiki.resource.entity.EntityResourceReference;
import org.xwiki.script.ScriptContextManager;
import org.xwiki.skin.Resource;
import org.xwiki.skin.Skin;
import org.xwiki.skin.SkinManager;
import org.xwiki.template.TemplateManager;
import org.xwiki.url.ExtendedURL;
import org.xwiki.velocity.VelocityManager;
import org.xwiki.wiki.descriptor.WikiDescriptor;
import org.xwiki.wiki.descriptor.WikiDescriptorManager;
import org.xwiki.wiki.manager.WikiManager;
import org.xwiki.wiki.manager.WikiManagerException;
import org.xwiki.xml.XMLUtils;
import com.xpn.xwiki.api.Api;
import com.xpn.xwiki.api.Document;
import com.xpn.xwiki.api.User;
import com.xpn.xwiki.criteria.api.XWikiCriteriaService;
import com.xpn.xwiki.doc.DeletedAttachment;
import com.xpn.xwiki.doc.DocumentRevisionProvider;
import com.xpn.xwiki.doc.MandatoryDocumentInitializer;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDeletedDocument;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.doc.XWikiDocument.XWikiAttachmentToRemove;
import com.xpn.xwiki.doc.XWikiDocumentArchive;
import com.xpn.xwiki.internal.WikiInitializerJob;
import com.xpn.xwiki.internal.WikiInitializerRequest;
import com.xpn.xwiki.internal.XWikiCfgConfigurationSource;
import com.xpn.xwiki.internal.XWikiConfigDelegate;
import com.xpn.xwiki.internal.XWikiInitializerJob;
import com.xpn.xwiki.internal.event.XObjectPropertyAddedEvent;
import com.xpn.xwiki.internal.event.XObjectPropertyDeletedEvent;
import com.xpn.xwiki.internal.event.XObjectPropertyEvent;
import com.xpn.xwiki.internal.event.XObjectPropertyUpdatedEvent;
import com.xpn.xwiki.internal.mandatory.XWikiPreferencesDocumentInitializer;
import com.xpn.xwiki.internal.render.OldRendering;
import com.xpn.xwiki.internal.render.groovy.ParseGroovyFromString;
import com.xpn.xwiki.internal.skin.InternalSkinConfiguration;
import com.xpn.xwiki.internal.skin.InternalSkinManager;
import com.xpn.xwiki.internal.skin.WikiSkin;
import com.xpn.xwiki.internal.skin.WikiSkinUtils;
import com.xpn.xwiki.internal.store.StoreConfiguration;
import com.xpn.xwiki.internal.velocity.VelocityEvaluator;
import com.xpn.xwiki.job.JobRequestContext;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.PropertyInterface;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.objects.classes.PasswordClass;
import com.xpn.xwiki.objects.classes.PropertyClass;
import com.xpn.xwiki.objects.meta.MetaClass;
import com.xpn.xwiki.plugin.XWikiPluginInterface;
import com.xpn.xwiki.plugin.XWikiPluginManager;
import com.xpn.xwiki.render.groovy.XWikiPageClassLoader;
import com.xpn.xwiki.stats.api.XWikiStatsService;
import com.xpn.xwiki.stats.impl.SearchEngineRule;
import com.xpn.xwiki.stats.impl.XWikiStatsServiceImpl;
import com.xpn.xwiki.store.AttachmentRecycleBinStore;
import com.xpn.xwiki.store.AttachmentVersioningStore;
import com.xpn.xwiki.store.XWikiAttachmentStoreInterface;
import com.xpn.xwiki.store.XWikiCacheStoreInterface;
import com.xpn.xwiki.store.XWikiHibernateStore;
import com.xpn.xwiki.store.XWikiRecycleBinStoreInterface;
import com.xpn.xwiki.store.XWikiStoreInterface;
import com.xpn.xwiki.store.XWikiVersioningStoreInterface;
import com.xpn.xwiki.user.api.XWikiAuthService;
import com.xpn.xwiki.user.api.XWikiGroupService;
import com.xpn.xwiki.user.api.XWikiRightService;
import com.xpn.xwiki.user.api.XWikiUser;
import com.xpn.xwiki.user.impl.xwiki.XWikiAuthServiceImpl;
import com.xpn.xwiki.user.impl.xwiki.XWikiGroupServiceImpl;
import com.xpn.xwiki.user.impl.xwiki.XWikiRightServiceImpl;
import com.xpn.xwiki.util.Util;
import com.xpn.xwiki.util.XWikiStubContextProvider;
import com.xpn.xwiki.web.Utils;
import com.xpn.xwiki.web.XWikiEngineContext;
import com.xpn.xwiki.web.XWikiMessageTool;
import com.xpn.xwiki.web.XWikiRequest;
import com.xpn.xwiki.web.XWikiURLFactory;
import com.xpn.xwiki.web.XWikiURLFactoryService;
import com.xpn.xwiki.web.XWikiURLFactoryServiceImpl;
import com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString;
@Serializable(false)
public class XWiki implements EventListener
{
/** Name of the default wiki. */
public static final String DEFAULT_MAIN_WIKI = "xwiki";
/** Name of the default home space. */
public static final String DEFAULT_HOME_SPACE = "Main";
/** Name of the default system space. */
public static final String SYSTEM_SPACE = "XWiki";
/** Name of the default space homepage. */
public static final String DEFAULT_SPACE_HOMEPAGE = "WebHome";
public static final String CKEY_SKIN = InternalSkinManager.CKEY_SKIN;
public static final String CKEY_BASESKIN = InternalSkinManager.CKEY_PARENTSKIN;
public static final String DEFAULT_SKIN = InternalSkinConfiguration.DEFAULT_SKIN;
/** Logging helper object. */
protected static final Logger LOGGER = LoggerFactory.getLogger(XWiki.class);
/** Frequently used Document reference, the class which holds virtual wiki definitions. */
private static final DocumentReference VIRTUAL_WIKI_DEFINITION_CLASS_REFERENCE =
new DocumentReference(DEFAULT_MAIN_WIKI, SYSTEM_SPACE, "XWikiServerClass");
/** The default encoding, and the internally used encoding when dealing with byte representation of strings. */
public static final String DEFAULT_ENCODING = "UTF-8";
/** Represents no value (ie the default value will be used) in xproperties */
private static final String NO_VALUE = "---";
/** The main document storage. */
private XWikiStoreInterface store;
/** The attachment content storage. */
private XWikiAttachmentStoreInterface defaultAttachmentContentStore;
/** The attachment archive storage. */
private AttachmentVersioningStore defaultAttachmentArchiveStore;
/** Document versioning storage. */
private XWikiVersioningStoreInterface versioningStore;
/** Deleted documents storage. */
private XWikiRecycleBinStoreInterface recycleBinStore;
private AttachmentRecycleBinStore attachmentRecycleBinStore;
private XWikiPluginManager pluginManager;
private XWikiAuthService authService;
private XWikiRightService rightService;
private XWikiGroupService groupService;
private XWikiStatsService statsService;
private XWikiURLFactoryService urlFactoryService;
private XWikiCriteriaService criteriaService;
/** Lock object used for the lazy initialization of the authentication service. */
private final Object AUTH_SERVICE_LOCK = new Object();
/** Lock object used for the lazy initialization of the authorization service. */
private final Object RIGHT_SERVICE_LOCK = new Object();
/** Lock object used for the lazy initialization of the group management service. */
private final Object GROUP_SERVICE_LOCK = new Object();
/** Lock object used for the lazy initialization of the statistics service. */
private final Object STATS_SERVICE_LOCK = new Object();
/** Lock object used for the lazy initialization of the URL Factory service. */
private final Object URLFACTORY_SERVICE_LOCK = new Object();
private MetaClass metaclass;
private String version;
private XWikiEngineContext engine_context;
private String database;
private String fullNameSQL;
/**
* The list of initialized wikis.
*/
private Map<String, WikiInitializerJob> initializedWikis = new ConcurrentHashMap<>();
private boolean isReadOnly = false;
/**
* @deprecated since 6.1M2, use {@link XWikiCfgConfigurationSource#CFG_ENV_NAME} instead
*/
@Deprecated
public static final String CFG_ENV_NAME = XWikiCfgConfigurationSource.CFG_ENV_NAME;
public static final String MACROS_FILE = "/templates/macros.txt";
/**
* File containing XWiki's version, in the format: <version name>.<SVN revision number>.
*/
private static final String VERSION_FILE = "/WEB-INF/version.properties";
/**
* Property containing the version value in the {@link #VERSION_FILE} file.
*/
private static final String VERSION_FILE_PROPERTY = "version";
private static XWikiInitializerJob job;
/** List of configured syntax ids. */
private List<String> configuredSyntaxes;
/** Used to convert a proper Document Reference to string (standard form). */
private EntityReferenceSerializer<String> defaultEntityReferenceSerializer;
/**
* Used to resolve a string into a proper Document Reference using the current document's reference to fill the
* blanks, except for the page name for which the default page name is used instead.
*/
private DocumentReferenceResolver<String> currentMixedDocumentReferenceResolver;
private DocumentReferenceResolver<EntityReference> currentReferenceDocumentReferenceResolver;
private EntityReferenceResolver<String> currentMixedEntityReferenceResolver;
private EntityReferenceResolver<String> relativeEntityReferenceResolver;
private EntityReferenceSerializer<String> localStringEntityReferenceSerializer;
private ResourceReferenceManager resourceReferenceManager;
private JobExecutor jobExecutor;
private InternalSkinManager internalSkinManager;
private TemplateManager templateManager;
private RenderingContext renderingContext;
private VelocityEvaluator velocityEvaluator;
/**
* Whether backlinks are enabled or not (cached for performance).
*
* @since 3.2M2
*/
private Boolean hasBacklinks;
private ConfigurationSource xwikicfg;
private ConfigurationSource wikiConfiguration;
private ConfigurationSource userConfiguration;
private ConfigurationSource spaceConfiguration;
private EditConfiguration editConfiguration;
private StoreConfiguration storeConfiguration;
private ObservationManager observationManager;
private Provider<XWikiContext> xcontextProvider;
private ContextualLocalizationManager localization;
private Provider<OldRendering> oldRenderingProvider;
private ParseGroovyFromString parseGroovyFromString;
private JobProgressManager progress;
private Provider<DocumentReference> defaultDocumentReferenceProvider;
private DocumentReferenceResolver<EntityReference> currentgetdocumentResolver;
private AttachmentReferenceResolver<EntityReference> currentAttachmentReferenceResolver;
private WikiSkinUtils wikiSkinUtils;
private DocumentRevisionProvider documentRevisionProvider;
/**
* List of top level space names that can be used in the fake context document created when accessing a resource
* with the 'skin' action.
*/
private List<String> SKIN_RESOURCE_SPACE_NAMES = Arrays.asList("skins", "resources");
private ConfigurationSource getConfiguration()
{
if (this.xwikicfg == null) {
this.xwikicfg = Utils.getComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT);
}
return this.xwikicfg;
}
private ConfigurationSource getWikiConfiguration()
{
if (this.wikiConfiguration == null) {
this.wikiConfiguration = Utils.getComponent(ConfigurationSource.class, "wiki");
}
return this.wikiConfiguration;
}
private ConfigurationSource getSpaceConfiguration()
{
if (this.spaceConfiguration == null) {
this.spaceConfiguration = Utils.getComponent(ConfigurationSource.class, "space");
}
return this.spaceConfiguration;
}
private ConfigurationSource getUserConfiguration()
{
if (this.userConfiguration == null) {
this.userConfiguration = Utils.getComponent(ConfigurationSource.class, "user");
}
return this.userConfiguration;
}
private EditConfiguration getEditConfiguration()
{
if (this.editConfiguration == null) {
this.editConfiguration = Utils.getComponent(EditConfiguration.class);
}
return this.editConfiguration;
}
private StoreConfiguration getStoreConfiguration()
{
if (this.storeConfiguration == null) {
this.storeConfiguration = Utils.getComponent(StoreConfiguration.class);
}
return this.storeConfiguration;
}
private InternalSkinManager getInternalSkinManager()
{
if (this.internalSkinManager == null) {
this.internalSkinManager = Utils.getComponent(InternalSkinManager.class);
}
return this.internalSkinManager;
}
private TemplateManager getTemplateManager()
{
if (this.templateManager == null) {
this.templateManager = Utils.getComponent(TemplateManager.class);
}
return this.templateManager;
}
private RenderingContext getRenderingContext()
{
if (this.renderingContext == null) {
this.renderingContext = Utils.getComponent(RenderingContext.class);
}
return this.renderingContext;
}
private MutableRenderingContext getMutableRenderingContext()
{
return getRenderingContext() instanceof MutableRenderingContext
? (MutableRenderingContext) getRenderingContext() : null;
}
private VelocityEvaluator getVelocityEvaluator()
{
if (this.velocityEvaluator == null) {
this.velocityEvaluator = Utils.getComponent(VelocityEvaluator.class);
}
return this.velocityEvaluator;
}
private ObservationManager getObservationManager()
{
if (this.observationManager == null) {
this.observationManager = Utils.getComponent(ObservationManager.class);
}
return this.observationManager;
}
private XWikiContext getXWikiContext()
{
if (this.xcontextProvider == null) {
this.xcontextProvider = Utils.getComponent(XWikiContext.TYPE_PROVIDER);
}
return this.xcontextProvider.get();
}
private ContextualLocalizationManager getLocalization()
{
if (this.localization == null) {
this.localization = Utils.getComponent(ContextualLocalizationManager.class);
}
return this.localization;
}
private OldRendering getOldRendering()
{
if (this.oldRenderingProvider == null) {
this.oldRenderingProvider = Utils.getComponent(OldRendering.TYPE_PROVIDER);
}
return this.oldRenderingProvider.get();
}
private ParseGroovyFromString getParseGroovyFromString()
{
if (this.parseGroovyFromString == null) {
this.parseGroovyFromString = Utils.getComponent(ParseGroovyFromString.class);
}
return this.parseGroovyFromString;
}
private JobProgressManager getProgress()
{
if (this.progress == null) {
this.progress = Utils.getComponent(JobProgressManager.class);
}
return this.progress;
}
private Provider<DocumentReference> getDefaultDocumentReferenceProvider()
{
if (this.defaultDocumentReferenceProvider == null) {
this.defaultDocumentReferenceProvider = Utils.getComponent(DocumentReference.TYPE_PROVIDER);
}
return this.defaultDocumentReferenceProvider;
}
private DocumentReferenceResolver<EntityReference> getCurrentGetDocumentResolver()
{
if (this.currentgetdocumentResolver == null) {
this.currentgetdocumentResolver =
Utils.getComponent(DocumentReferenceResolver.TYPE_REFERENCE, "currentgetdocument");
}
return this.currentgetdocumentResolver;
}
private AttachmentReferenceResolver<EntityReference> getCurrentAttachmentResolver()
{
if (this.currentAttachmentReferenceResolver == null) {
this.currentAttachmentReferenceResolver =
Utils.getComponent(AttachmentReferenceResolver.TYPE_REFERENCE, "current");
}
return this.currentAttachmentReferenceResolver;
}
private EntityReferenceSerializer<String> getDefaultEntityReferenceSerializer()
{
if (this.defaultEntityReferenceSerializer == null) {
this.defaultEntityReferenceSerializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING);
}
return this.defaultEntityReferenceSerializer;
}
private DocumentReferenceResolver<String> getCurrentMixedDocumentReferenceResolver()
{
if (this.currentMixedDocumentReferenceResolver == null) {
this.currentMixedDocumentReferenceResolver =
Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, "currentmixed");
}
return this.currentMixedDocumentReferenceResolver;
}
private DocumentReferenceResolver<EntityReference> getCurrentReferenceDocumentReferenceResolver()
{
if (this.currentReferenceDocumentReferenceResolver == null) {
this.currentReferenceDocumentReferenceResolver =
Utils.getComponent(DocumentReferenceResolver.TYPE_REFERENCE, "current");
}
return this.currentReferenceDocumentReferenceResolver;
}
private EntityReferenceResolver<String> getCurrentMixedEntityReferenceResolver()
{
if (this.currentMixedEntityReferenceResolver == null) {
this.currentMixedEntityReferenceResolver =
Utils.getComponent(EntityReferenceResolver.TYPE_STRING, "currentmixed");
}
return this.currentMixedEntityReferenceResolver;
}
private EntityReferenceResolver<String> getRelativeEntityReferenceResolver()
{
if (this.relativeEntityReferenceResolver == null) {
this.relativeEntityReferenceResolver = Utils.getComponent(EntityReferenceResolver.TYPE_STRING, "relative");
}
return this.relativeEntityReferenceResolver;
}
private EntityReferenceSerializer<String> getLocalStringEntityReferenceSerializer()
{
if (this.localStringEntityReferenceSerializer == null) {
this.localStringEntityReferenceSerializer =
Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, "local");
}
return this.localStringEntityReferenceSerializer;
}
private ResourceReferenceManager getResourceReferenceManager()
{
if (this.resourceReferenceManager == null) {
this.resourceReferenceManager = Utils.getComponent(ResourceReferenceManager.class);
}
return this.resourceReferenceManager;
}
private JobExecutor getJobExecutor()
{
if (this.jobExecutor == null) {
this.jobExecutor = Utils.getComponent(JobExecutor.class);
}
return this.jobExecutor;
}
private DocumentReference getDefaultDocumentReference()
{
return getDefaultDocumentReferenceProvider().get();
}
private WikiSkinUtils getWikiSkinUtils()
{
if (this.wikiSkinUtils == null) {
this.wikiSkinUtils = Utils.getComponent(WikiSkinUtils.class);
}
return this.wikiSkinUtils;
}
private DocumentRevisionProvider getDocumentRevisionProvider()
{
if (this.documentRevisionProvider == null) {
this.documentRevisionProvider = Utils.getComponent(DocumentRevisionProvider.class);
}
return this.documentRevisionProvider;
}
private String localizePlainOrKey(String key, Object... parameters)
{
return StringUtils.defaultString(getLocalization().getTranslationPlain(key, parameters), key);
}
/**
* @param context see {@link XWikiContext}
*/
public static XWiki getMainXWiki(XWikiContext context) throws XWikiException
{
return getMainXWiki(true, context);
}
/**
* @param wait true if the method should way for {@link XWiki} instance to be initialized
* @param context see {@link XWikiContext}
*/
public static XWiki getMainXWiki(boolean wait, XWikiContext context) throws XWikiException
{
String xwikiname = DEFAULT_MAIN_WIKI;
context.setMainXWiki(xwikiname);
XWiki xwiki;
try {
XWikiEngineContext econtext = context.getEngineContext();
xwiki = (XWiki) econtext.getAttribute(xwikiname);
if (xwiki == null) {
// Start XWiki initialization
synchronized (XWiki.class) {
xwiki = (XWiki) econtext.getAttribute(xwikiname);
if (xwiki == null && job == null) {
job = Utils.getComponent((Type) Job.class, XWikiInitializerJob.JOBTYPE);
if (job.getStatus() == null) {
// "Pre-initialize" XWikiStubContextProvider so that XWiki initializer can find one
Utils.<XWikiStubContextProvider>getComponent(XWikiStubContextProvider.class)
.initialize(context);
job.startAsync();
}
}
}
// Wait until XWiki is initialized
if (wait) {
job.join();
xwiki = (XWiki) econtext.getAttribute(xwikiname);
}
}
context.setWiki(xwiki);
return xwiki;
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_INIT_FAILED,
"Could not initialize main XWiki instance", e);
}
}
public static boolean isInitializing(XWikiContext xcontext)
{
return Boolean.TRUE.equals(xcontext.getEngineContext().getAttribute("xwiki.init"));
}
/**
* Return the XWiki object (as in "the Wiki API") corresponding to the requested wiki.
*
* @param context see {@link XWikiContext}
* @return an XWiki object configured for the wiki corresponding to the current request
* @throws XWikiException if the requested URL does not correspond to a real wiki, or if there's an error in the
* storage
*/
public static XWiki getXWiki(XWikiContext context) throws XWikiException
{
return getXWiki(true, context);
}
/**
* Return the XWiki object (as in "the Wiki API") corresponding to the requested wiki.
* <p>
* Unless <code>wait</code> is false the method return right away null if XWiki is not yet initialized.
*
* @param wait wait until XWiki is initialized
* @param xcontext see {@link XWikiContext}
* @return an XWiki object configured for the wiki corresponding to the current request
* @throws XWikiException if the requested URL does not correspond to a real wiki, or if there's an error in the
* storage
*/
public static XWiki getXWiki(boolean wait, XWikiContext xcontext) throws XWikiException
{
XWiki xwiki = getMainXWiki(wait, xcontext);
if (xwiki == null) {
return null;
}
// Extract Entity Resource from URL and put it in the Execution Context
EntityResourceReference entityResourceReference = initializeResourceFromURL(xcontext);
// If not an entity resource reference assume main wiki
if (entityResourceReference == null) {
return xwiki;
}
// Get the wiki id
String wikiId = entityResourceReference.getEntityReference().extractReference(EntityType.WIKI).getName();
if (wikiId.equals(xcontext.getMainXWiki())) {
// The main wiki was requested.
return xwiki;
}
// Check if the wiki exists by checking if a descriptor exists for the wiki id.
WikiDescriptorManager wikiDescriptorManager = Utils.getComponent(WikiDescriptorManager.class);
WikiDescriptor descriptor;
try {
descriptor = wikiDescriptorManager.getById(wikiId);
} catch (WikiManagerException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_STORE_MISC,
String.format("Failed find wiki descriptor for wiki id [%s]", wikiId), e);
}
if (descriptor == null) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_DOES_NOT_EXIST,
String.format("The wiki [%s] does not exist", wikiId));
}
// Initialize wiki
xcontext.setWikiId(wikiId);
xcontext.setOriginalWikiId(wikiId);
if (!xwiki.initializeWiki(wikiId, wait, xcontext)) {
// The wiki is still initializing
return null;
}
return xwiki;
}
/**
* @param wikiId the identifier of the wiki
* @return the current {@link WikiInitializerJob} associated to the passed wiki or null if there is none
*/
public Job getWikiInitializerJob(String wikiId)
{
return this.initializedWikis.get(wikiId);
}
/**
* Make sure the wiki is initializing or wait for it.
*
* @param wikiId the identifier of the wiki to initialize
* @param wait true if the method should return only when the wiki is fully initialized
* @return true if the wiki is fully initialized
* @param xcontext the XWiki context
* @throws XWikiException when the initialization failed
* @since 8.4RC1
*/
public boolean initializeWiki(String wikiId, boolean wait, XWikiContext xcontext) throws XWikiException
{
Job wikiJob = this.initializedWikis.get(wikiId);
// Create and start the job if it does not exist
if (wikiJob == null) {
try {
wikiJob = initializeWiki(wikiId, xcontext);
} catch (JobException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_INIT_FAILED,
"Could not start [" + wikiId + "] wiki initialization", e);
}
}
// Check if the job is done
if (wikiJob.getStatus().getState() == State.FINISHED) {
return true;
}
// Wait until the job is finished if asked to
if (wait) {
try {
wikiJob.join();
} catch (InterruptedException e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_INIT_FAILED,
"Wiki [" + wikiId + "] initialization was interrupted unexpectedly", e);
}
if (wikiJob.getStatus().getError() != null) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_INIT_FAILED,
"Wiki [" + wikiId + "] initialization failed", wikiJob.getStatus().getError());
}
return true;
}
// Still initializing
return false;
}
private Job initializeWiki(String wikiId, XWikiContext xcontext) throws JobException
{
synchronized (this.initializedWikis) {
WikiInitializerJob wikiJob = this.initializedWikis.get(wikiId);
if (wikiJob == null) {
WikiInitializerRequest request = new WikiInitializerRequest(wikiId);
JobRequestContext.set(request, xcontext);
wikiJob = (WikiInitializerJob) getJobExecutor().execute(WikiInitializerJob.JOBTYPE, request);
this.initializedWikis.put(wikiId, wikiJob);
}
return wikiJob;
}
}
private static EntityResourceReference initializeResourceFromURL(XWikiContext context) throws XWikiException
{
// Extract the Entity Resource from the URL
// TODO: This code should be put in an ExecutionContextInitializer but we couldn't do yet since this code
// requires that the XWiki object be initialized first (the line above). Thus we'll be able to to move it only
// after the XWiki init is done also in an ExecutionContextInitializer (and with priorities).
@SuppressWarnings("deprecation")
EntityResourceReference entityResourceReference;
URL url = context.getURL();
try {
ExtendedURL extendedURL = new ExtendedURL(url, context.getRequest().getContextPath());
ResourceTypeResolver<ExtendedURL> typeResolver =
Utils.getComponent(new DefaultParameterizedType(null, ResourceTypeResolver.class, ExtendedURL.class));
ResourceType type = typeResolver.resolve(extendedURL, Collections.<String, Object>emptyMap());
ResourceReferenceResolver<ExtendedURL> resourceResolver = Utils
.getComponent(new DefaultParameterizedType(null, ResourceReferenceResolver.class, ExtendedURL.class));
ResourceReference reference =
resourceResolver.resolve(extendedURL, type, Collections.<String, Object>emptyMap());
entityResourceReference =
reference instanceof EntityResourceReference ? (EntityResourceReference) reference : null;
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION,
String.format("Failed to extract Entity Resource Reference from URL [%s]", url), e);
}
Utils.getComponent(Execution.class).getContext().setProperty(ResourceReferenceManager.RESOURCE_CONTEXT_PROPERTY,
entityResourceReference);
return entityResourceReference;
}
public static URL getRequestURL(XWikiRequest request) throws XWikiException
{
try {
StringBuffer requestURL = request.getRequestURL();
String qs = request.getQueryString();
if ((qs != null) && (!qs.equals(""))) {
return new URL(requestURL.toString() + "?" + qs);
} else {
return new URL(requestURL.toString());
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION,
"Exception while getting URL from request", e);
}
}
public static Object callPrivateMethod(Object obj, String methodName)
{
return callPrivateMethod(obj, methodName, null, null);
}
public static Object callPrivateMethod(Object obj, String methodName, Class<?>[] classes, Object[] args)
{
try {
Method method = obj.getClass().getDeclaredMethod(methodName, classes);
method.setAccessible(true);
return method.invoke(obj, args);
} catch (IllegalAccessException e) {
LOGGER.error("Failed to call private method [{}]: [{}]", methodName, e);
return null;
} catch (NoSuchMethodException e) {
return null;
} catch (InvocationTargetException e) {
LOGGER.error("Private method [{}] failed: [{}]", methodName, e);
return null;
}
}
public static HttpClient getHttpClient(int timeout, String userAgent)
{