-
Notifications
You must be signed in to change notification settings - Fork 208
/
RepositoryServiceImpl.java
3528 lines (3161 loc) · 155 KB
/
RepositoryServiceImpl.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.spi2dav;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.jcr.AccessDeniedException;
import javax.jcr.Credentials;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.LoginException;
import javax.jcr.MergeException;
import javax.jcr.NamespaceException;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.PathNotFoundException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.InvalidNodeTypeDefinitionException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.nodetype.NodeTypeExistsException;
import javax.jcr.query.InvalidQueryException;
import javax.jcr.version.VersionException;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.jackrabbit.commons.webdav.AtomFeedConstants;
import org.apache.jackrabbit.commons.webdav.EventUtil;
import org.apache.jackrabbit.commons.webdav.JcrRemotingConstants;
import org.apache.jackrabbit.commons.webdav.JcrValueType;
import org.apache.jackrabbit.commons.webdav.NodeTypeConstants;
import org.apache.jackrabbit.commons.webdav.NodeTypeUtil;
import org.apache.jackrabbit.commons.webdav.ValueUtil;
import org.apache.jackrabbit.spi.Batch;
import org.apache.jackrabbit.spi.ChildInfo;
import org.apache.jackrabbit.spi.Event;
import org.apache.jackrabbit.spi.EventBundle;
import org.apache.jackrabbit.spi.EventFilter;
import org.apache.jackrabbit.spi.IdFactory;
import org.apache.jackrabbit.spi.ItemId;
import org.apache.jackrabbit.spi.ItemInfo;
import org.apache.jackrabbit.spi.ItemInfoCache;
import org.apache.jackrabbit.spi.LockInfo;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.NameFactory;
import org.apache.jackrabbit.spi.NodeId;
import org.apache.jackrabbit.spi.NodeInfo;
import org.apache.jackrabbit.spi.Path;
import org.apache.jackrabbit.spi.PathFactory;
import org.apache.jackrabbit.spi.PrivilegeDefinition;
import org.apache.jackrabbit.spi.PropertyId;
import org.apache.jackrabbit.spi.PropertyInfo;
import org.apache.jackrabbit.spi.QItemDefinition;
import org.apache.jackrabbit.spi.QNodeDefinition;
import org.apache.jackrabbit.spi.QNodeTypeDefinition;
import org.apache.jackrabbit.spi.QPropertyDefinition;
import org.apache.jackrabbit.spi.QValue;
import org.apache.jackrabbit.spi.QValueFactory;
import org.apache.jackrabbit.spi.QueryInfo;
import org.apache.jackrabbit.spi.RepositoryService;
import org.apache.jackrabbit.spi.SessionInfo;
import org.apache.jackrabbit.spi.Subscription;
import org.apache.jackrabbit.spi.Tree;
import org.apache.jackrabbit.spi.commons.ChildInfoImpl;
import org.apache.jackrabbit.spi.commons.EventBundleImpl;
import org.apache.jackrabbit.spi.commons.EventFilterImpl;
import org.apache.jackrabbit.spi.commons.ItemInfoCacheImpl;
import org.apache.jackrabbit.spi.commons.conversion.IdentifierResolver;
import org.apache.jackrabbit.spi.commons.conversion.IllegalNameException;
import org.apache.jackrabbit.spi.commons.conversion.MalformedPathException;
import org.apache.jackrabbit.spi.commons.conversion.NameException;
import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver;
import org.apache.jackrabbit.spi.commons.conversion.NameResolver;
import org.apache.jackrabbit.spi.commons.conversion.ParsingNameResolver;
import org.apache.jackrabbit.spi.commons.conversion.ParsingPathResolver;
import org.apache.jackrabbit.spi.commons.conversion.PathResolver;
import org.apache.jackrabbit.spi.commons.iterator.Iterators;
import org.apache.jackrabbit.spi.commons.name.NameConstants;
import org.apache.jackrabbit.spi.commons.namespace.AbstractNamespaceResolver;
import org.apache.jackrabbit.spi.commons.namespace.NamespaceResolver;
import org.apache.jackrabbit.spi.commons.nodetype.compact.CompactNodeTypeDefWriter;
import org.apache.jackrabbit.spi.commons.privilege.PrivilegeDefinitionImpl;
import org.apache.jackrabbit.spi.commons.value.QValueValue;
import org.apache.jackrabbit.spi.commons.value.ValueFactoryQImpl;
import org.apache.jackrabbit.spi.commons.value.ValueFormat;
import org.apache.jackrabbit.util.Text;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.DavMethods;
import org.apache.jackrabbit.webdav.DavServletResponse;
import org.apache.jackrabbit.webdav.MultiStatus;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.client.methods.CheckinMethod;
import org.apache.jackrabbit.webdav.client.methods.CheckoutMethod;
import org.apache.jackrabbit.webdav.client.methods.CopyMethod;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.client.methods.DavMethodBase;
import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
import org.apache.jackrabbit.webdav.client.methods.LabelMethod;
import org.apache.jackrabbit.webdav.client.methods.LockMethod;
import org.apache.jackrabbit.webdav.client.methods.MergeMethod;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.apache.jackrabbit.webdav.client.methods.MkWorkspaceMethod;
import org.apache.jackrabbit.webdav.client.methods.MoveMethod;
import org.apache.jackrabbit.webdav.client.methods.OptionsMethod;
import org.apache.jackrabbit.webdav.client.methods.OrderPatchMethod;
import org.apache.jackrabbit.webdav.client.methods.PollMethod;
import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
import org.apache.jackrabbit.webdav.client.methods.PropPatchMethod;
import org.apache.jackrabbit.webdav.client.methods.PutMethod;
import org.apache.jackrabbit.webdav.client.methods.ReportMethod;
import org.apache.jackrabbit.webdav.client.methods.SearchMethod;
import org.apache.jackrabbit.webdav.client.methods.SubscribeMethod;
import org.apache.jackrabbit.webdav.client.methods.UnLockMethod;
import org.apache.jackrabbit.webdav.client.methods.UnSubscribeMethod;
import org.apache.jackrabbit.webdav.client.methods.UpdateMethod;
import org.apache.jackrabbit.webdav.header.CodedUrlHeader;
import org.apache.jackrabbit.webdav.header.IfHeader;
import org.apache.jackrabbit.webdav.lock.ActiveLock;
import org.apache.jackrabbit.webdav.lock.LockDiscovery;
import org.apache.jackrabbit.webdav.lock.Scope;
import org.apache.jackrabbit.webdav.lock.Type;
import org.apache.jackrabbit.webdav.observation.DefaultEventType;
import org.apache.jackrabbit.webdav.observation.EventDiscovery;
import org.apache.jackrabbit.webdav.observation.EventType;
import org.apache.jackrabbit.webdav.observation.ObservationConstants;
import org.apache.jackrabbit.webdav.observation.SubscriptionInfo;
import org.apache.jackrabbit.webdav.ordering.OrderingConstants;
import org.apache.jackrabbit.webdav.property.DavProperty;
import org.apache.jackrabbit.webdav.property.DavPropertyName;
import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
import org.apache.jackrabbit.webdav.property.HrefProperty;
import org.apache.jackrabbit.webdav.search.SearchConstants;
import org.apache.jackrabbit.webdav.search.SearchInfo;
import org.apache.jackrabbit.webdav.security.CurrentUserPrivilegeSetProperty;
import org.apache.jackrabbit.webdav.security.Privilege;
import org.apache.jackrabbit.webdav.security.SecurityConstants;
import org.apache.jackrabbit.webdav.security.SupportedPrivilege;
import org.apache.jackrabbit.webdav.security.SupportedPrivilegeSetProperty;
import org.apache.jackrabbit.webdav.transaction.TransactionConstants;
import org.apache.jackrabbit.webdav.transaction.TransactionInfo;
import org.apache.jackrabbit.webdav.version.DeltaVConstants;
import org.apache.jackrabbit.webdav.version.LabelInfo;
import org.apache.jackrabbit.webdav.version.MergeInfo;
import org.apache.jackrabbit.webdav.version.UpdateInfo;
import org.apache.jackrabbit.webdav.version.VersionControlledResource;
import org.apache.jackrabbit.webdav.version.report.ReportInfo;
import org.apache.jackrabbit.webdav.xml.DomUtil;
import org.apache.jackrabbit.webdav.xml.ElementIterator;
import org.apache.jackrabbit.webdav.xml.XmlSerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* <code>RepositoryServiceImpl</code>...
*/
// TODO: encapsulate URI building, escaping, unescaping...
// TODO: TO-BE-FIXED. caches don't get adjusted upon removal/move of items
public class RepositoryServiceImpl implements RepositoryService, DavConstants {
private static Logger log = LoggerFactory.getLogger(RepositoryServiceImpl.class);
private static final SubscriptionInfo S_INFO = new SubscriptionInfo(DefaultEventType.create(EventUtil.EVENT_ALL, ItemResourceConstants.NAMESPACE), true, INFINITE_TIMEOUT);
/**
* Key for the client map during repo creation (no sessionInfo present)
*/
private static final String CLIENT_KEY = "repoCreation";
/**
* Default value for the maximum number of connections per host such as
* configured with {@link HttpConnectionManagerParams#setDefaultMaxConnectionsPerHost(int)}.
*/
public static final int MAX_CONNECTIONS_DEFAULT = 20;
private final IdFactory idFactory;
private final NameFactory nameFactory;
private final PathFactory pathFactory;
private final QValueFactory qValueFactory;
private final ValueFactory valueFactory;
private final int itemInfoCacheSize;
private final NamespaceCache nsCache;
private final URIResolverImpl uriResolver;
private final HostConfiguration hostConfig;
private final ConcurrentMap<Object, HttpClient> clients;
private final HttpConnectionManager connectionManager;
private final Map<Name, QNodeTypeDefinition> nodeTypeDefinitions = new HashMap<Name, QNodeTypeDefinition>();
/** Repository descriptors. */
private final Map<String, QValue[]> descriptors =
new HashMap<String, QValue[]>();
/** Observation features. */
private boolean remoteServerProvidesNodeTypes = false;
private boolean remoteServerProvidesNoLocalFlag = false;
/* DAV conformance levels */
private Set<String> remoteDavComplianceClasses = null;
/**
* Same as {@link #RepositoryServiceImpl(String, IdFactory, NameFactory, PathFactory, QValueFactory, int, int)}
* using {@link ItemInfoCacheImpl#DEFAULT_CACHE_SIZE)} as size for the item
* cache and {@link #MAX_CONNECTIONS_DEFAULT} for the maximum number of
* connections on the client.
*
* @param uri The server uri.
* @param idFactory The id factory.
* @param nameFactory The name factory.
* @param pathFactory The path factory.
* @param qValueFactory The value factory.
* @throws RepositoryException If an error occurs.
*/
public RepositoryServiceImpl(String uri, IdFactory idFactory,
NameFactory nameFactory, PathFactory pathFactory,
QValueFactory qValueFactory) throws RepositoryException {
this(uri, idFactory, nameFactory, pathFactory, qValueFactory, ItemInfoCacheImpl.DEFAULT_CACHE_SIZE);
}
/**
* Same as {@link #RepositoryServiceImpl(String, IdFactory, NameFactory, PathFactory, QValueFactory, int, int)}
* using {@link #MAX_CONNECTIONS_DEFAULT} for the maximum number of
* connections on the client.
*
* @param uri The server uri.
* @param idFactory The id factory.
* @param nameFactory The name factory.
* @param pathFactory The path factory.
* @param qValueFactory The value factory.
* @param itemInfoCacheSize The size of the item info cache.
* @throws RepositoryException If an error occurs.
*/
public RepositoryServiceImpl(String uri, IdFactory idFactory,
NameFactory nameFactory, PathFactory pathFactory,
QValueFactory qValueFactory, int itemInfoCacheSize) throws RepositoryException {
this(uri, idFactory, nameFactory, pathFactory, qValueFactory, itemInfoCacheSize, MAX_CONNECTIONS_DEFAULT);
}
/**
* Creates a new instance of this repository service.
*
* @param uri The server uri.
* @param idFactory The id factory.
* @param nameFactory The name factory.
* @param pathFactory The path factory.
* @param qValueFactory The value factory.
* @param itemInfoCacheSize The size of the item info cache.
* @param maximumHttpConnections A int >0 defining the maximum number of
* connections per host to be configured on
* {@link HttpConnectionManagerParams#setDefaultMaxConnectionsPerHost(int)}.
* @throws RepositoryException If an error occurs.
*/
public RepositoryServiceImpl(String uri, IdFactory idFactory,
NameFactory nameFactory, PathFactory pathFactory,
QValueFactory qValueFactory, int itemInfoCacheSize,
int maximumHttpConnections ) throws RepositoryException {
if (uri == null || "".equals(uri)) {
throw new RepositoryException("Invalid repository uri '" + uri + "'.");
}
if (idFactory == null || qValueFactory == null) {
throw new RepositoryException("IdFactory and QValueFactory may not be null.");
}
this.idFactory = idFactory;
this.nameFactory = nameFactory;
this.pathFactory = pathFactory;
this.qValueFactory = qValueFactory;
this.itemInfoCacheSize = itemInfoCacheSize;
try {
URI repositoryUri = computeRepositoryUri(uri);
hostConfig = new HostConfiguration();
hostConfig.setHost(repositoryUri);
nsCache = new NamespaceCache();
uriResolver = new URIResolverImpl(repositoryUri, this, DomUtil.createDocument());
NamePathResolver resolver = new NamePathResolverImpl(nsCache);
valueFactory = new ValueFactoryQImpl(qValueFactory, resolver);
} catch (URIException e) {
throw new RepositoryException(e);
} catch (ParserConfigurationException e) {
throw new RepositoryException(e);
}
connectionManager = new MultiThreadedHttpConnectionManager();
if (maximumHttpConnections > 0) {
HttpConnectionManagerParams connectionParams = connectionManager.getParams();
connectionParams.setDefaultMaxConnectionsPerHost(maximumHttpConnections);
connectionParams.setMaxTotalConnections(maximumHttpConnections);
}
// This configuration of the clients cache assumes that the level of
// concurrency on this map will be equal to the default number of maximum
// connections allowed on the httpClient level.
// TODO: review again
int concurrencyLevel = MAX_CONNECTIONS_DEFAULT;
int initialCapacity = MAX_CONNECTIONS_DEFAULT;
if (maximumHttpConnections > 0) {
concurrencyLevel = maximumHttpConnections;
initialCapacity = maximumHttpConnections;
}
clients = new ConcurrentHashMap<Object, HttpClient>(concurrencyLevel, .75f, initialCapacity);
}
private static void checkSessionInfo(SessionInfo sessionInfo) throws RepositoryException {
if (!(sessionInfo instanceof SessionInfoImpl)) {
throw new RepositoryException("Unknown SessionInfo implementation.");
}
}
/**
* Resolve the given URI against a base URI (usually the request URI of an HTTP request)
*/
private static String resolve(String baseUri, String relUri) throws RepositoryException {
try {
java.net.URI base = new java.net.URI(baseUri);
java.net.URI rel = new java.net.URI(relUri);
return base.resolve(rel).toString();
}
catch (URISyntaxException ex) {
throw new RepositoryException(ex);
}
}
private static void checkSubscription(Subscription subscription) throws RepositoryException {
if (!(subscription instanceof EventSubscriptionImpl)) {
throw new RepositoryException("Unknown Subscription implementation.");
}
}
private static boolean isUnLockMethod(DavMethod method) {
int code = DavMethods.getMethodCode(method.getName());
return DavMethods.DAV_UNLOCK == code;
}
protected static void initMethod(HttpMethod method, SessionInfo sessionInfo, boolean addIfHeader) throws RepositoryException {
if (addIfHeader) {
checkSessionInfo(sessionInfo);
Set<String> allLockTokens = ((SessionInfoImpl) sessionInfo).getAllLockTokens();
// TODO: ev. build tagged if header
if (!allLockTokens.isEmpty()) {
String[] locktokens = allLockTokens.toArray(new String[allLockTokens.size()]);
IfHeader ifH = new IfHeader(locktokens);
method.setRequestHeader(ifH.getHeaderName(), ifH.getHeaderValue());
}
}
initMethod(method, sessionInfo);
}
// set of HTTP methods that will not change the remote state
private static final Set<String> readMethods;
static {
Set<String> tmp = new HashSet<String>();
tmp.add("GET");
tmp.add("HEAD");
tmp.add("PROPFIND");
tmp.add("POLL");
tmp.add("REPORT");
tmp.add("SEARCH");
readMethods = Collections.unmodifiableSet(tmp);
}
// set headers for user data and session identification
protected static void initMethod(HttpMethod method, SessionInfo sessionInfo) throws RepositoryException {
boolean isReadAccess = readMethods.contains(method.getName());
boolean needsSessionId = !isReadAccess || "POLL".equals(method.getName());
if (sessionInfo instanceof SessionInfoImpl && needsSessionId) {
StringBuilder linkHeaderField = new StringBuilder();
String sessionIdentifier = ((SessionInfoImpl) sessionInfo)
.getSessionIdentifier();
linkHeaderField.append("<").append(sessionIdentifier).append(">; rel=\"")
.append(JcrRemotingConstants.RELATION_REMOTE_SESSION_ID).append("\"");
String userdata = ((SessionInfoImpl) sessionInfo).getUserData();
if (userdata != null && ! isReadAccess) {
String escaped = Text.escape(userdata);
linkHeaderField.append(", <data:,").append(escaped).append(">; rel=\"")
.append(JcrRemotingConstants.RELATION_USER_DATA).append("\"");
}
method.addRequestHeader("Link", linkHeaderField.toString());
}
}
private static void initMethod(DavMethod method, BatchImpl batchImpl, boolean addIfHeader) throws RepositoryException {
initMethod(method, batchImpl.sessionInfo, addIfHeader);
// add batchId as separate header, TODO: could probably re-use session id Link relation
CodedUrlHeader ch = new CodedUrlHeader(TransactionConstants.HEADER_TRANSACTIONID, batchImpl.batchId);
method.setRequestHeader(ch.getHeaderName(), ch.getHeaderValue());
}
private static boolean isSameResource(String requestURI, MultiStatusResponse response) {
try {
String href = resolve(requestURI, response.getHref());
if (href.endsWith("/") && !requestURI.endsWith("/")) {
href = href.substring(0, href.length() - 1);
}
return requestURI.equals(href);
} catch (RepositoryException e) {
return false;
}
}
private String saveGetIdString(ItemId id, SessionInfo sessionInfo) {
NamePathResolver resolver = null;
try {
resolver = getNamePathResolver(sessionInfo);
} catch (RepositoryException e) {
// ignore.
}
return saveGetIdString(id, resolver);
}
private String saveGetIdString(ItemId id, NamePathResolver resolver) {
StringBuffer bf = new StringBuffer();
String uid = id.getUniqueID();
if (uid != null) {
bf.append(uid);
}
Path p = id.getPath();
if (p != null) {
if (resolver == null) {
bf.append(p.toString());
} else {
try {
bf.append(resolver.getJCRPath(p));
} catch (NamespaceException e) {
bf.append(p.toString());
}
}
}
return bf.toString();
}
protected NamePathResolver getNamePathResolver(SessionInfo sessionInfo) throws RepositoryException {
checkSessionInfo(sessionInfo);
return getNamePathResolver(((SessionInfoImpl) sessionInfo));
}
private NamePathResolver getNamePathResolver(SessionInfoImpl sessionInfo) {
NamePathResolver resolver = sessionInfo.getNamePathResolver();
if (resolver == null) {
resolver = new NamePathResolverImpl(sessionInfo);
sessionInfo.setNamePathResolver(resolver);
}
return resolver;
}
/**
* Returns a key for the httpClient hash. The key is either the specified
* SessionInfo or a marker if the session info is null (used during
* repository instantiation).
*
* @param sessionInfo
* @return Key for the client map.
*/
private static Object getClientKey(SessionInfo sessionInfo) {
return (sessionInfo == null) ? CLIENT_KEY : sessionInfo;
}
protected HttpClient getClient(SessionInfo sessionInfo) throws RepositoryException {
Object clientKey = getClientKey(sessionInfo);
HttpClient client = clients.get(clientKey);
if (client == null) {
client = new HttpClient(connectionManager);
client.setHostConfiguration(hostConfig);
// NOTE: null credentials only work if 'missing-auth-mapping' param is
// set on the server
org.apache.commons.httpclient.Credentials creds = null;
if (sessionInfo != null) {
checkSessionInfo(sessionInfo);
creds = ((SessionInfoImpl) sessionInfo).getCredentials().getCredentials();
// always send authentication not waiting for 401
client.getParams().setAuthenticationPreemptive(true);
}
client.getState().setCredentials(AuthScope.ANY, creds);
clients.put(clientKey, client);
log.debug("Created Client " + client + " for SessionInfo " + sessionInfo);
}
return client;
}
private void removeClient(SessionInfo sessionInfo) {
HttpClient cl = clients.remove(getClientKey(sessionInfo));
log.debug("Removed Client " + cl + " for SessionInfo " + sessionInfo);
}
protected String getItemUri(ItemId itemId, SessionInfo sessionInfo) throws RepositoryException {
return getItemUri(itemId, sessionInfo, sessionInfo.getWorkspaceName());
}
protected String getItemUri(ItemId itemId, SessionInfo sessionInfo, String workspaceName) throws RepositoryException {
return uriResolver.getItemUri(itemId, workspaceName, sessionInfo);
}
/**
* Clear all URI mappings. This is required after hierarchy operations such
* as e.g. MOVE.
*
* @param sessionInfo
*/
protected void clearItemUriCache(SessionInfo sessionInfo) {
uriResolver.clearCacheEntries(sessionInfo);
}
private String getItemUri(NodeId parentId, Name childName,
SessionInfo sessionInfo) throws RepositoryException {
String parentUri = uriResolver.getItemUri(parentId, sessionInfo.getWorkspaceName(), sessionInfo);
NamePathResolver resolver = getNamePathResolver(sessionInfo);
// JCR-2920: don't append '/' to a trailing '/'
if (!parentUri.endsWith("/")) {
parentUri += "/";
}
return parentUri + Text.escape(resolver.getJCRName(childName));
}
private NodeId getParentId(String baseUri, DavPropertySet propSet, SessionInfo sessionInfo)
throws RepositoryException {
NodeId parentId = null;
DavProperty<?> p = propSet.get(JcrRemotingConstants.JCR_PARENT_LN, ItemResourceConstants.NAMESPACE);
if (p != null) {
HrefProperty parentProp = new HrefProperty(p);
String parentHref = parentProp.getHrefs().get(0);
if (parentHref != null && parentHref.length() > 0) {
parentId = uriResolver.getNodeId(resolve(baseUri, parentHref), sessionInfo);
}
}
return parentId;
}
String getUniqueID(DavPropertySet propSet) {
DavProperty<?> prop = propSet.get(JcrRemotingConstants.JCR_UUID_LN, ItemResourceConstants.NAMESPACE);
if (prop != null) {
return prop.getValue().toString();
} else {
return null;
}
}
Name getQName(DavPropertySet propSet, NamePathResolver resolver) throws RepositoryException {
DavProperty<?> nameProp = propSet.get(JcrRemotingConstants.JCR_NAME_LN, ItemResourceConstants.NAMESPACE);
if (nameProp != null && nameProp.getValue() != null) {
// not root node. Note that 'unespacing' is not required since
// the jcr:name property does not provide the value in escaped form.
String jcrName = nameProp.getValue().toString();
try {
return resolver.getQName(jcrName);
} catch (NameException e) {
throw new RepositoryException(e);
}
} else {
return NameConstants.ROOT;
}
}
int getIndex(DavPropertySet propSet) {
int index = Path.INDEX_UNDEFINED;
DavProperty<?> indexProp = propSet.get(JcrRemotingConstants.JCR_INDEX_LN, ItemResourceConstants.NAMESPACE);
if (indexProp != null && indexProp.getValue() != null) {
index = Integer.parseInt(indexProp.getValue().toString());
}
return index;
}
//--------------------------------------------------------------------------
/**
* Execute a 'Workspace' operation.
*
* @param method
* @param sessionInfo
* @throws RepositoryException
*/
private void execute(DavMethod method, SessionInfo sessionInfo) throws RepositoryException {
try {
initMethod(method, sessionInfo, !isUnLockMethod(method));
getClient(sessionInfo).executeMethod(method);
method.checkSuccess();
} catch (IOException e) {
throw new RepositoryException(e);
} catch (DavException e) {
throw ExceptionConverter.generate(e, method);
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
//--------------------------------------------------< RepositoryService >---
/**
* @see RepositoryService#getIdFactory()
*/
public IdFactory getIdFactory() {
return idFactory;
}
/**
* @see RepositoryService#getNameFactory()
*/
public NameFactory getNameFactory() {
return nameFactory;
}
/**
* @see RepositoryService#getPathFactory()
*/
public PathFactory getPathFactory() {
return pathFactory;
}
public QValueFactory getQValueFactory() {
return qValueFactory;
}
public ItemInfoCache getItemInfoCache(SessionInfo sessionInfo) throws RepositoryException {
return new ItemInfoCacheImpl(itemInfoCacheSize);
}
/**
* @see RepositoryService#getRepositoryDescriptors()
*/
public Map<String, QValue[]> getRepositoryDescriptors() throws RepositoryException {
if (descriptors.isEmpty()) {
ReportInfo info = new ReportInfo(JcrRemotingConstants.REPORT_REPOSITORY_DESCRIPTORS, ItemResourceConstants.NAMESPACE);
ReportMethod method = null;
try {
method = new ReportMethod(uriResolver.getRepositoryUri(), info);
int sc = getClient(null).executeMethod(method);
if (sc == HttpStatus.SC_UNAUTHORIZED
|| sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// JCR-3076: Mandatory authentication prevents us from
// accessing the descriptors on the server, so instead
// of failing with an exception we simply return an empty
// set of descriptors
log.warn("Authentication required to access repository descriptors");
return descriptors;
}
method.checkSuccess();
Document doc = method.getResponseBodyAsDocument();
if (doc != null) {
Element rootElement = doc.getDocumentElement();
ElementIterator nsElems = DomUtil.getChildren(rootElement, JcrRemotingConstants.XML_DESCRIPTOR, ItemResourceConstants.NAMESPACE);
while (nsElems.hasNext()) {
Element elem = nsElems.nextElement();
String key = DomUtil.getChildText(elem, JcrRemotingConstants.XML_DESCRIPTORKEY, ItemResourceConstants.NAMESPACE);
ElementIterator it = DomUtil.getChildren(elem, JcrRemotingConstants.XML_DESCRIPTORVALUE, ItemResourceConstants.NAMESPACE);
List<QValue> vs = new ArrayList<QValue>();
while (it.hasNext()) {
Element dv = it.nextElement();
String descriptor = DomUtil.getText(dv);
if (key != null && descriptor != null) {
String typeStr = (DomUtil.getAttribute(dv, JcrRemotingConstants.ATTR_VALUE_TYPE, null));
int type = (typeStr == null) ? PropertyType.STRING : PropertyType.valueFromName(typeStr);
vs.add(getQValueFactory().create(descriptor, type));
} else {
log.error("Invalid descriptor key / value pair: " + key + " -> " + descriptor);
}
}
descriptors.put(key, vs.toArray(new QValue[vs.size()]));
}
}
} catch (IOException e) {
throw new RepositoryException(e);
} catch (DavException e) {
throw ExceptionConverter.generate(e);
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
return descriptors;
}
/**
* @see RepositoryService#obtain(Credentials, String)
*/
public SessionInfo obtain(Credentials credentials, String workspaceName)
throws LoginException, NoSuchWorkspaceException, RepositoryException {
CredentialsWrapper dc = new CredentialsWrapper(credentials);
return obtain(dc, workspaceName);
}
public SessionInfo obtain(SessionInfo sessionInfo, String workspaceName)
throws LoginException, NoSuchWorkspaceException, RepositoryException {
checkSessionInfo(sessionInfo);
return obtain(((SessionInfoImpl)sessionInfo).getCredentials(), workspaceName);
}
public SessionInfo impersonate(SessionInfo sessionInfo, Credentials credentials) throws LoginException, RepositoryException {
throw new UnsupportedOperationException("Not implemented yet.");
}
private SessionInfo obtain(CredentialsWrapper credentials, String workspaceName)
throws LoginException, NoSuchWorkspaceException, RepositoryException {
// check if the workspace with the given name is accessible
PropFindMethod method = null;
SessionInfoImpl sessionInfo = new SessionInfoImpl(credentials, workspaceName);
try {
DavPropertyNameSet nameSet = new DavPropertyNameSet();
// for backwards compat. -> retrieve DAV:workspace if the newly
// added property (workspaceName) is not supported by the server.
nameSet.add(DeltaVConstants.WORKSPACE);
nameSet.add(JcrRemotingConstants.JCR_WORKSPACE_NAME_LN, ItemResourceConstants.NAMESPACE);
method = new PropFindMethod(uriResolver.getWorkspaceUri(workspaceName), nameSet, DEPTH_0);
getClient(sessionInfo).executeMethod(method);
MultiStatusResponse[] responses = method.getResponseBodyAsMultiStatus().getResponses();
if (responses.length != 1) {
throw new LoginException("Login failed: Unknown workspace '" + workspaceName+ "'.");
}
DavPropertySet props = responses[0].getProperties(DavServletResponse.SC_OK);
DavProperty<?> prop = props.get(JcrRemotingConstants.JCR_WORKSPACE_NAME_LN, ItemResourceConstants.NAMESPACE);
if (prop != null) {
String wspName = prop.getValue().toString();
if (workspaceName == null) {
// login with 'null' workspace name -> retrieve the effective
// workspace name from the property and recreate the SessionInfo.
sessionInfo = new SessionInfoImpl(credentials, wspName);
} else if (!wspName.equals(workspaceName)) {
throw new LoginException("Login failed: Invalid workspace name '" + workspaceName + "'.");
}
} else if (props.contains(DeltaVConstants.WORKSPACE)) {
String wspHref = new HrefProperty(props.get(DeltaVConstants.WORKSPACE)).getHrefs().get(0);
String wspName = Text.unescape(Text.getName(wspHref, true));
if (!wspName.equals(workspaceName)) {
throw new LoginException("Login failed: Invalid workspace name " + workspaceName);
}
} else {
throw new LoginException("Login failed: Unknown workspace '" + workspaceName+ "'.");
}
} catch (IOException e) {
throw new RepositoryException(e.getMessage());
} catch (DavException e) {
throw ExceptionConverter.generate(e);
} finally {
if (method != null) {
method.releaseConnection();
}
}
// make sure the general namespace mappings have been loaded once
// before additional requests are executed that rely on the namespace
// mappings.
if (nsCache.prefixToURI.isEmpty()) {
try {
getRegisteredNamespaces(sessionInfo);
} catch (RepositoryException e) {
// ignore
}
}
// return the sessionInfo
return sessionInfo;
}
public void dispose(SessionInfo sessionInfo) throws RepositoryException {
checkSessionInfo(sessionInfo);
removeClient(sessionInfo);
}
/**
* @see RepositoryService#getWorkspaceNames(SessionInfo)
*/
public String[] getWorkspaceNames(SessionInfo sessionInfo) throws RepositoryException {
DavPropertyNameSet nameSet = new DavPropertyNameSet();
nameSet.add(DeltaVConstants.WORKSPACE);
PropFindMethod method = null;
try {
method = new PropFindMethod(uriResolver.getRepositoryUri(), nameSet, DEPTH_1);
getClient(sessionInfo).executeMethod(method);
MultiStatusResponse[] responses = method.getResponseBodyAsMultiStatus().getResponses();
Set<String> wspNames = new HashSet<String>();
for (MultiStatusResponse response : responses) {
DavPropertySet props = response.getProperties(DavServletResponse.SC_OK);
if (props.contains(DeltaVConstants.WORKSPACE)) {
HrefProperty hp = new HrefProperty(props.get(DeltaVConstants.WORKSPACE));
String wspHref = hp.getHrefs().get(0);
String name = Text.unescape(Text.getName(wspHref, true));
wspNames.add(name);
}
}
return wspNames.toArray(new String[wspNames.size()]);
} catch (IOException e) {
throw new RepositoryException(e);
} catch (DavException e) {
throw ExceptionConverter.generate(e);
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
/**
* @see RepositoryService#isGranted(SessionInfo, ItemId, String[] actions)
*/
public boolean isGranted(SessionInfo sessionInfo, ItemId itemId, String[] actions) throws RepositoryException {
ReportMethod method = null;
try {
String uri = obtainAbsolutePathFromUri(getItemUri(itemId, sessionInfo));
ReportInfo reportInfo = new ReportInfo(JcrRemotingConstants.REPORT_PRIVILEGES, ItemResourceConstants.NAMESPACE);
reportInfo.setContentElement(DomUtil.hrefToXml(uri, DomUtil.createDocument()));
method = new ReportMethod(uriResolver.getWorkspaceUri(sessionInfo.getWorkspaceName()), reportInfo);
getClient(sessionInfo).executeMethod(method);
method.checkSuccess();
MultiStatusResponse[] responses = method.getResponseBodyAsMultiStatus().getResponses();
if (responses.length < 1) {
throw new ItemNotFoundException("Unable to retrieve permissions for item " + saveGetIdString(itemId, sessionInfo));
}
DavProperty<?> p = responses[0].getProperties(DavServletResponse.SC_OK).get(SecurityConstants.CURRENT_USER_PRIVILEGE_SET);
if (p == null) {
return false;
}
// build set of privileges from given actions. NOTE: since the actions
// have no qualifying namespace, the {@link ItemResourceConstants#NAMESPACE}
// is used.
Set<Privilege> requiredPrivileges = new HashSet<Privilege>();
for (String action : actions) {
requiredPrivileges.add(Privilege.getPrivilege(action, ItemResourceConstants.NAMESPACE));
}
// build set of privileges granted to the current user.
CurrentUserPrivilegeSetProperty privSet = new CurrentUserPrivilegeSetProperty(p);
Collection<Privilege> privileges = privSet.getValue();
// check privileges present against required privileges.
return privileges.containsAll(requiredPrivileges);
} catch (IOException e) {
throw new RepositoryException(e);
} catch (ParserConfigurationException e) {
throw new RepositoryException(e);
} catch (DavException e) {
throw ExceptionConverter.generate(e);
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
@Override
public PrivilegeDefinition[] getPrivilegeDefinitions(SessionInfo sessionInfo) throws RepositoryException {
return internalGetPrivilegeDefinitions(sessionInfo, uriResolver.getRepositoryUri());
}
@Override
public PrivilegeDefinition[] getSupportedPrivileges(SessionInfo sessionInfo, NodeId nodeId) throws RepositoryException {
String uri = (nodeId == null) ? uriResolver.getWorkspaceUri(sessionInfo.getWorkspaceName()) : getItemUri(nodeId, sessionInfo);
return internalGetPrivilegeDefinitions(sessionInfo, uri);
}
@Override
public Name[] getPrivilegeNames(SessionInfo sessionInfo, NodeId nodeId) throws RepositoryException {
String uri = (nodeId == null) ? uriResolver.getWorkspaceUri(sessionInfo.getWorkspaceName()) : getItemUri(nodeId, sessionInfo);
DavPropertyNameSet nameSet = new DavPropertyNameSet();
nameSet.add(SecurityConstants.CURRENT_USER_PRIVILEGE_SET);
DavMethodBase method = null;
try {
method = new PropFindMethod(uri, nameSet, DEPTH_0);
getClient(sessionInfo).executeMethod(method);
MultiStatusResponse[] responses = method.getResponseBodyAsMultiStatus().getResponses();
if (responses.length < 1) {
throw new PathNotFoundException("Unable to retrieve privileges definitions.");
}
DavPropertyName displayName = SecurityConstants.CURRENT_USER_PRIVILEGE_SET;
DavProperty<?> p = responses[0].getProperties(DavServletResponse.SC_OK).get(displayName);
if (p == null) {
return new Name[0];
} else {
Collection<Privilege> privs = new CurrentUserPrivilegeSetProperty(p).getValue();
Set<Name> privNames = new HashSet<Name>(privs.size());
for (Privilege priv : privs) {
privNames.add(nameFactory.create(priv.getNamespace().getURI(), priv.getName()));
}
return privNames.toArray(new Name[privNames.size()]);
}
} catch (IOException e) {
throw new RepositoryException(e);
} catch (DavException e) {
throw ExceptionConverter.generate(e);
} finally {
if (method != null) {
method.releaseConnection();
}
}
}
private PrivilegeDefinition[] internalGetPrivilegeDefinitions(SessionInfo sessionInfo, String uri) throws RepositoryException {
DavPropertyNameSet nameSet = new DavPropertyNameSet();
nameSet.add(SecurityConstants.SUPPORTED_PRIVILEGE_SET);
DavMethodBase method = null;
try {
method = new PropFindMethod(uri, nameSet, DEPTH_0);
getClient(sessionInfo).executeMethod(method);
MultiStatusResponse[] responses = method.getResponseBodyAsMultiStatus().getResponses();
if (responses.length < 1) {
throw new PathNotFoundException("Unable to retrieve privileges definitions.");
}
DavPropertyName displayName = SecurityConstants.SUPPORTED_PRIVILEGE_SET;
DavProperty<?> p = responses[0].getProperties(DavServletResponse.SC_OK).get(displayName);
if (p == null) {
return new PrivilegeDefinition[0];
} else {
// build PrivilegeDefinition(s) from the supported-privileges dav property
Map<Name, SupportedPrivilege> spMap = new HashMap<Name, SupportedPrivilege>();
fillSupportedPrivilegeMap(new SupportedPrivilegeSetProperty(p).getValue(), spMap, getNameFactory());
List<PrivilegeDefinition> pDefs = new ArrayList<PrivilegeDefinition>();
for (Name privilegeName : spMap.keySet()) {
SupportedPrivilege sp = spMap.get(privilegeName);
Set<Name> aggrnames = null;
SupportedPrivilege[] aggregates = sp.getSupportedPrivileges();
if (aggregates != null && aggregates.length > 0) {
aggrnames = new HashSet<Name>();
for (SupportedPrivilege aggregate : aggregates) {
Name aggregateName = nameFactory.create(aggregate.getPrivilege().getNamespace().getURI(),
aggregate.getPrivilege().getName());
aggrnames.add(aggregateName);
}