/
SessionImpl.java
1519 lines (1351 loc) · 53.7 KB
/
SessionImpl.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
/*
* (C) Copyright 2006-2013 Nuxeo SA (http://nuxeo.com/) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Florent Guillaume
*/
package org.nuxeo.ecm.core.storage.sql;
import java.io.Serializable;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.resource.ResourceException;
import javax.resource.cci.ConnectionMetaData;
import javax.resource.cci.Interaction;
import javax.resource.cci.LocalTransaction;
import javax.resource.cci.ResultSetInfo;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuxeo.ecm.core.api.ConcurrentUpdateException;
import org.nuxeo.ecm.core.api.IterableQueryResult;
import org.nuxeo.ecm.core.api.NuxeoException;
import org.nuxeo.ecm.core.api.PartialList;
import org.nuxeo.ecm.core.api.repository.RepositoryManager;
import org.nuxeo.ecm.core.api.security.ACL;
import org.nuxeo.ecm.core.api.security.SecurityConstants;
import org.nuxeo.ecm.core.model.LockManager;
import org.nuxeo.ecm.core.query.QueryFilter;
import org.nuxeo.ecm.core.query.sql.NXQL;
import org.nuxeo.ecm.core.schema.DocumentType;
import org.nuxeo.ecm.core.schema.SchemaManager;
import org.nuxeo.ecm.core.storage.FulltextConfiguration;
import org.nuxeo.ecm.core.storage.FulltextParser;
import org.nuxeo.ecm.core.storage.FulltextUpdaterWork;
import org.nuxeo.ecm.core.storage.FulltextUpdaterWork.IndexAndText;
import org.nuxeo.ecm.core.storage.sql.PersistenceContext.PathAndId;
import org.nuxeo.ecm.core.storage.sql.RowMapper.RowBatch;
import org.nuxeo.ecm.core.storage.sql.coremodel.SQLFulltextExtractorWork;
import org.nuxeo.ecm.core.work.api.Work;
import org.nuxeo.ecm.core.work.api.WorkManager;
import org.nuxeo.ecm.core.work.api.WorkManager.Scheduling;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.metrics.MetricsService;
import org.nuxeo.runtime.transaction.TransactionHelper;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.SharedMetricRegistries;
import com.codahale.metrics.Timer;
/**
* The session is the main high level access point to data from the underlying database.
*/
public class SessionImpl implements Session, XAResource {
private static final Log log = LogFactory.getLog(SessionImpl.class);
/**
* Set this system property to false if you don't want repositories to be looked up under the compatibility name
* "default" in the "repositories" table.
* <p>
* Only do this if you start from an empty database, or if you have migrated the "repositories" table by hand, or if
* you need to create a new repository in a database already containing a "default" repository (table sharing, not
* recommended).
*/
public static final String COMPAT_REPOSITORY_NAME_KEY = "org.nuxeo.vcs.repository.name.default.compat";
private static final boolean COMPAT_REPOSITORY_NAME = Boolean.parseBoolean(Framework.getProperty(
COMPAT_REPOSITORY_NAME_KEY, "true"));
protected final RepositoryImpl repository;
private final Mapper mapper;
private final Model model;
protected final FulltextParser fulltextParser;
// public because used by unit tests
public final PersistenceContext context;
private volatile boolean live;
private boolean inTransaction;
private Node rootNode;
private long threadId;
private String threadName;
private Throwable threadStack;
private boolean readAclsChanged;
// @since 5.7
protected final MetricRegistry registry = SharedMetricRegistries.getOrCreate(MetricsService.class.getName());
private final Timer saveTimer;
private final Timer queryTimer;
private final Timer aclrUpdateTimer;
private static final java.lang.String LOG_MIN_DURATION_KEY = "org.nuxeo.vcs.query.log_min_duration_ms";
private static final long LOG_MIN_DURATION_NS = Long.parseLong(Framework.getProperty(LOG_MIN_DURATION_KEY, "-1")) * 1000000;
public SessionImpl(RepositoryImpl repository, Model model, Mapper mapper) {
this.repository = repository;
this.mapper = mapper;
this.model = model;
context = new PersistenceContext(model, mapper, this);
live = true;
readAclsChanged = false;
try {
fulltextParser = repository.fulltextParserClass.newInstance();
} catch (ReflectiveOperationException e) {
throw new NuxeoException(e);
}
saveTimer = registry.timer(MetricRegistry.name("nuxeo", "repositories", repository.getName(), "saves"));
queryTimer = registry.timer(MetricRegistry.name("nuxeo", "repositories", repository.getName(), "queries"));
aclrUpdateTimer = registry.timer(MetricRegistry.name("nuxeo", "repositories", repository.getName(),
"aclr-updates"));
computeRootNode();
}
public void checkLive() {
if (!live) {
throw new IllegalStateException("Session is not live");
}
checkThread();
}
// called by NetServlet when forwarding remote NetMapper calls.
@Override
public Mapper getMapper() {
return mapper;
}
/**
* Gets the XAResource. Called by the ManagedConnectionImpl, which actually wraps it in a connection-aware
* implementation.
*/
public XAResource getXAResource() {
return this;
}
/**
* Clears all the caches. Called by RepositoryManagement.
*/
protected int clearCaches() {
if (inTransaction) {
// avoid potential multi-threaded access to active session
return 0;
}
checkThreadEnd();
return context.clearCaches();
}
protected PersistenceContext getContext() {
return context;
}
protected void rollback() {
context.clearCaches();
}
protected void checkThread() {
if (threadId == 0) {
return;
}
long currentThreadId = Thread.currentThread().getId();
if (threadId == currentThreadId) {
return;
}
String currentThreadName = Thread.currentThread().getName();
String msg = String.format("Concurrency Error: Session was started in thread %s (%s)"
+ " but is being used in thread %s (%s)", threadId, threadName, currentThreadId, currentThreadName);
throw new IllegalStateException(msg, threadStack);
}
protected void checkThreadStart() {
threadId = Thread.currentThread().getId();
threadName = Thread.currentThread().getName();
if (log.isDebugEnabled()) {
threadStack = new Throwable("owner stack trace");
}
}
protected void checkThreadEnd() {
threadId = 0;
threadName = null;
threadStack = null;
}
/**
* Generates a new id, or used a pre-generated one (import).
*/
protected Serializable generateNewId(Serializable id) {
return context.generateNewId(id);
}
protected boolean isIdNew(Serializable id) {
return context.isIdNew(id);
}
/*
* ----- javax.resource.cci.Connection -----
*/
@Override
public void close() throws ResourceException {
try {
checkLive();
closeSession();
repository.closeSession(this);
} catch (Exception cause) {
throw new ResourceException(cause);
}
}
protected void closeSession() {
live = false;
context.clearCaches();
// close the mapper and therefore the connection
mapper.close();
// don't clean the caches, we keep the pristine cache around
// TODO this is getting destroyed, we can clean everything
}
@Override
public Interaction createInteraction() throws ResourceException {
throw new UnsupportedOperationException();
}
@Override
public LocalTransaction getLocalTransaction() throws ResourceException {
throw new UnsupportedOperationException();
}
@Override
public ConnectionMetaData getMetaData() throws ResourceException {
throw new UnsupportedOperationException();
}
@Override
public ResultSetInfo getResultSetInfo() throws ResourceException {
throw new UnsupportedOperationException();
}
/*
* ----- Session -----
*/
@Override
public boolean isLive() {
return live;
}
@Override
public String getRepositoryName() {
return repository.getName();
}
@Override
public Model getModel() {
return model;
}
@Override
public Node getRootNode() {
checkLive();
return rootNode;
}
@Override
public void save() {
final Timer.Context timerContext = saveTimer.time();
try {
checkLive();
flush();
if (!inTransaction) {
sendInvalidationsToOthers();
// as we don't have a way to know when the next
// non-transactional
// statement will start, process invalidations immediately
}
processReceivedInvalidations();
} finally {
timerContext.stop();
}
}
protected void flush() {
checkThread();
List<Work> works;
if (!repository.getRepositoryDescriptor().getFulltextDescriptor().getFulltextDisabled()) {
works = getFulltextWorks();
} else {
works = Collections.emptyList();
}
doFlush();
if (readAclsChanged) {
updateReadAcls();
}
scheduleWork(works);
checkInvalidationsConflict();
}
protected void scheduleWork(List<Work> works) {
// do async fulltext indexing only if high-level sessions are available
RepositoryManager repositoryManager = Framework.getLocalService(RepositoryManager.class);
if (repositoryManager != null && !works.isEmpty()) {
WorkManager workManager = Framework.getLocalService(WorkManager.class);
for (Work work : works) {
// schedule work post-commit
// in non-tx mode, this may execute it nearly immediately
workManager.schedule(work, Scheduling.IF_NOT_SCHEDULED, true);
}
}
}
protected void doFlush() {
List<Fragment> fragmentsToClearDirty = new ArrayList<>(0);
RowBatch batch = context.getSaveBatch(fragmentsToClearDirty);
if (!batch.isEmpty()) {
log.debug("Saving session");
// execute the batch
mapper.write(batch);
log.debug("End of save");
for (Fragment fragment : fragmentsToClearDirty) {
fragment.clearDirty();
}
}
}
protected Serializable getContainingDocument(Serializable id) {
return context.getContainingDocument(id);
}
/**
* Gets the fulltext updates to do. Called at save() time.
*
* @return a list of {@link Work} instances to schedule post-commit.
*/
protected List<Work> getFulltextWorks() {
Set<Serializable> dirtyStrings = new HashSet<Serializable>();
Set<Serializable> dirtyBinaries = new HashSet<Serializable>();
context.findDirtyDocuments(dirtyStrings, dirtyBinaries);
if (dirtyStrings.isEmpty() && dirtyBinaries.isEmpty()) {
return Collections.emptyList();
}
List<Work> works = new LinkedList<Work>();
getFulltextSimpleWorks(works, dirtyStrings);
getFulltextBinariesWorks(works, dirtyBinaries);
return works;
}
protected void getFulltextSimpleWorks(List<Work> works, Set<Serializable> dirtyStrings) {
FulltextConfiguration fulltextConfiguration = model.getFulltextConfiguration();
if (fulltextConfiguration.fulltextSearchDisabled) {
return;
}
// update simpletext on documents with dirty strings
for (Serializable docId : dirtyStrings) {
if (docId == null) {
// cannot happen, but has been observed :(
log.error("Got null doc id in fulltext update, cannot happen");
continue;
}
Node document = getNodeById(docId);
if (document == null) {
// cannot happen
continue;
}
if (document.isProxy()) {
// proxies don't have any fulltext attached, it's
// the target document that carries it
continue;
}
String documentType = document.getPrimaryType();
String[] mixinTypes = document.getMixinTypes();
if (!fulltextConfiguration.isFulltextIndexable(documentType)) {
continue;
}
document.getSimpleProperty(Model.FULLTEXT_JOBID_PROP).setValue(model.idToString(document.getId()));
FulltextFinder fulltextFinder = new FulltextFinder(fulltextParser, document, this);
List<IndexAndText> indexesAndText = new LinkedList<IndexAndText>();
for (String indexName : fulltextConfiguration.indexNames) {
Set<String> paths;
if (fulltextConfiguration.indexesAllSimple.contains(indexName)) {
// index all string fields, minus excluded ones
// TODO XXX excluded ones...
paths = model.getSimpleTextPropertyPaths(documentType, mixinTypes);
} else {
// index configured fields
paths = fulltextConfiguration.propPathsByIndexSimple.get(indexName);
}
String text = fulltextFinder.findFulltext(paths);
indexesAndText.add(new IndexAndText(indexName, text));
}
if (!indexesAndText.isEmpty()) {
Work work = new FulltextUpdaterWork(repository.getName(), model.idToString(docId), true, false,
indexesAndText);
works.add(work);
}
}
}
protected void getFulltextBinariesWorks(List<Work> works, final Set<Serializable> dirtyBinaries) {
if (dirtyBinaries.isEmpty()) {
return;
}
// mark indexing in progress, so that future copies (including versions)
// will be indexed as well
for (Node node : getNodesByIds(new ArrayList<Serializable>(dirtyBinaries))) {
if (!model.getFulltextConfiguration().isFulltextIndexable(node.getPrimaryType())) {
continue;
}
node.getSimpleProperty(Model.FULLTEXT_JOBID_PROP).setValue(model.idToString(node.getId()));
}
// FulltextExtractorWork does fulltext extraction using converters
// and then schedules a FulltextUpdaterWork to write the results
// single-threaded
for (Serializable id : dirtyBinaries) {
String docId = model.idToString(id);
Work work = new SQLFulltextExtractorWork(repository.getName(), docId);
works.add(work);
}
}
/**
* Finds the fulltext in a document and sends it to a fulltext parser.
*
* @since 5.9.5
*/
protected static class FulltextFinder {
protected final FulltextParser fulltextParser;
protected final Node document;
protected final SessionImpl session;
protected final String documentType;
protected final String[] mixinTypes;
public FulltextFinder(FulltextParser fulltextParser, Node document, SessionImpl session) {
this.fulltextParser = fulltextParser;
this.document = document;
this.session = session;
if (document == null) {
documentType = null;
mixinTypes = null;
} else { // null in tests
documentType = document.getPrimaryType();
mixinTypes = document.getMixinTypes();
}
}
/**
* Parses the document for one index.
*/
protected String findFulltext(Set<String> paths) {
if (paths == null) {
return "";
}
List<String> strings = new ArrayList<String>();
for (String path : paths) {
ModelProperty pi = session.getModel().getPathPropertyInfo(documentType, mixinTypes, path);
if (pi == null) {
continue; // doc type doesn't have this property
}
if (pi.propertyType != PropertyType.STRING && pi.propertyType != PropertyType.ARRAY_STRING) {
continue;
}
List<Node> nodes = new ArrayList<Node>(Collections.singleton(document));
String[] names = path.split("/");
for (int i = 0; i < names.length; i++) {
String name = names[i];
if (i < names.length - 1) {
// traverse
List<Node> newNodes;
if ("*".equals(names[i + 1])) {
// traverse complex list
i++;
newNodes = new ArrayList<Node>();
for (Node node : nodes) {
newNodes.addAll(session.getChildren(node, name, true));
}
} else {
// traverse child
newNodes = new ArrayList<Node>(nodes.size());
for (Node node : nodes) {
node = session.getChildNode(node, name, true);
if (node != null) {
newNodes.add(node);
}
}
}
nodes = newNodes;
} else {
// last path component: get value
for (Node node : nodes) {
if (pi.propertyType == PropertyType.STRING) {
String v = node.getSimpleProperty(name).getString();
if (v != null) {
fulltextParser.parse(v, path, strings);
}
} else { /* ARRAY_STRING */
for (Serializable v : node.getCollectionProperty(name).getValue()) {
if (v != null) {
fulltextParser.parse((String) v, path, strings);
}
}
}
}
}
}
}
return StringUtils.join(strings, ' ');
}
}
/**
* Post-transaction invalidations notification.
* <p>
* Called post-transaction by session commit/rollback or transactionless save.
*/
protected void sendInvalidationsToOthers() {
context.sendInvalidationsToOthers();
}
/**
* Processes all invalidations accumulated.
* <p>
* Called pre-transaction by start or transactionless save;
*/
protected void processReceivedInvalidations() {
context.processReceivedInvalidations();
}
/**
* Post transaction check invalidations processing.
*/
protected void checkInvalidationsConflict() {
// repository.receiveClusterInvalidations(this);
context.checkInvalidationsConflict();
}
/*
* -------------------------------------------------------------
* -------------------------------------------------------------
* -------------------------------------------------------------
*/
protected Node getNodeById(Serializable id, boolean prefetch) {
List<Node> nodes = getNodesByIds(Collections.singletonList(id), prefetch);
Node node = nodes.get(0);
// ((JDBCMapper) ((CachingMapper)
// mapper).mapper).logger.log("getNodeById " + id + " -> " + (node ==
// null ? "missing" : "found"));
return node;
}
@Override
public Node getNodeById(Serializable id) {
checkLive();
if (id == null) {
throw new IllegalArgumentException("Illegal null id");
}
return getNodeById(id, true);
}
public List<Node> getNodesByIds(List<Serializable> ids, boolean prefetch) {
// get hier fragments
List<RowId> hierRowIds = new ArrayList<RowId>(ids.size());
for (Serializable id : ids) {
hierRowIds.add(new RowId(Model.HIER_TABLE_NAME, id));
}
List<Fragment> hierFragments = context.getMulti(hierRowIds, false);
// find available paths
Map<Serializable, String> paths = new HashMap<Serializable, String>();
Set<Serializable> parentIds = new HashSet<Serializable>();
for (Fragment fragment : hierFragments) {
Serializable id = fragment.getId();
PathAndId pathOrId = context.getPathOrMissingParentId((SimpleFragment) fragment, false);
// find missing fragments
if (pathOrId.path != null) {
paths.put(id, pathOrId.path);
} else {
parentIds.add(pathOrId.id);
}
}
// fetch the missing parents and their ancestors in bulk
if (!parentIds.isEmpty()) {
// fetch them in the context
getHierarchyAndAncestors(parentIds);
// compute missing paths using context
for (Fragment fragment : hierFragments) {
Serializable id = fragment.getId();
if (paths.containsKey(id)) {
continue;
}
String path = context.getPath((SimpleFragment) fragment);
paths.put(id, path);
}
}
// prepare fragment groups to build nodes
Map<Serializable, FragmentGroup> fragmentGroups = new HashMap<Serializable, FragmentGroup>(ids.size());
for (Fragment fragment : hierFragments) {
Serializable id = fragment.row.id;
fragmentGroups.put(id, new FragmentGroup((SimpleFragment) fragment, new FragmentsMap()));
}
if (prefetch) {
List<RowId> bulkRowIds = new ArrayList<RowId>();
Set<Serializable> proxyIds = new HashSet<Serializable>();
// get rows to prefetch for hier fragments
for (Fragment fragment : hierFragments) {
findPrefetchedFragments((SimpleFragment) fragment, bulkRowIds, proxyIds);
}
// proxies
// get proxies fragments
List<RowId> proxiesRowIds = new ArrayList<RowId>(proxyIds.size());
for (Serializable id : proxyIds) {
proxiesRowIds.add(new RowId(Model.PROXY_TABLE_NAME, id));
}
List<Fragment> proxiesFragments = context.getMulti(proxiesRowIds, true);
Set<Serializable> targetIds = new HashSet<Serializable>();
for (Fragment fragment : proxiesFragments) {
Serializable targetId = ((SimpleFragment) fragment).get(Model.PROXY_TARGET_KEY);
targetIds.add(targetId);
}
// get hier fragments for proxies' targets
targetIds.removeAll(ids); // only those we don't have already
hierRowIds = new ArrayList<RowId>(targetIds.size());
for (Serializable id : targetIds) {
hierRowIds.add(new RowId(Model.HIER_TABLE_NAME, id));
}
hierFragments = context.getMulti(hierRowIds, true);
for (Fragment fragment : hierFragments) {
findPrefetchedFragments((SimpleFragment) fragment, bulkRowIds, null);
}
// we have everything to be prefetched
// fetch all the prefetches in bulk
List<Fragment> fragments = context.getMulti(bulkRowIds, true);
// put each fragment in the map of the proper group
for (Fragment fragment : fragments) {
FragmentGroup fragmentGroup = fragmentGroups.get(fragment.row.id);
if (fragmentGroup != null) {
fragmentGroup.fragments.put(fragment.row.tableName, fragment);
}
}
}
// assemble nodes from the fragment groups
List<Node> nodes = new ArrayList<Node>(ids.size());
for (Serializable id : ids) {
FragmentGroup fragmentGroup = fragmentGroups.get(id);
// null if deleted/absent
Node node = fragmentGroup == null ? null : new Node(context, fragmentGroup, paths.get(id));
nodes.add(node);
}
return nodes;
}
/**
* Finds prefetched fragments for a hierarchy fragment, takes note of the ones that are proxies.
*/
protected void findPrefetchedFragments(SimpleFragment hierFragment, List<RowId> bulkRowIds,
Set<Serializable> proxyIds) {
Serializable id = hierFragment.row.id;
// find type
String typeName = (String) hierFragment.get(Model.MAIN_PRIMARY_TYPE_KEY);
if (Model.PROXY_TYPE.equals(typeName)) {
if (proxyIds != null) {
proxyIds.add(id);
}
return;
}
// find table names
Set<String> tableNames = model.getTypePrefetchedFragments(typeName);
if (tableNames == null) {
return; // unknown (obsolete) type
}
// add row id for each table name
Serializable parentId = hierFragment.get(Model.HIER_PARENT_KEY);
for (String tableName : tableNames) {
if (Model.HIER_TABLE_NAME.equals(tableName)) {
continue; // already fetched
}
if (parentId != null && Model.VERSION_TABLE_NAME.equals(tableName)) {
continue; // not a version, don't fetch this table
// TODO incorrect if we have filed versions
}
bulkRowIds.add(new RowId(tableName, id));
}
}
@Override
public List<Node> getNodesByIds(List<Serializable> ids) {
checkLive();
return getNodesByIds(ids, true);
}
@Override
public Node getParentNode(Node node) {
checkLive();
if (node == null) {
throw new IllegalArgumentException("Illegal null node");
}
Serializable id = node.getHierFragment().get(Model.HIER_PARENT_KEY);
return id == null ? null : getNodeById(id);
}
@Override
public String getPath(Node node) {
checkLive();
String path = node.getPath();
if (path == null) {
path = context.getPath(node.getHierFragment());
}
return path;
}
/*
* Normalize using NFC to avoid decomposed characters (like 'e' + COMBINING ACUTE ACCENT instead of LATIN SMALL
* LETTER E WITH ACUTE). NFKC (normalization using compatibility decomposition) is not used, because compatibility
* decomposition turns some characters (LATIN SMALL LIGATURE FFI, TRADE MARK SIGN, FULLWIDTH SOLIDUS) into a series
* of characters ('f'+'f'+'i', 'T'+'M', '/') that cannot be re-composed into the original, and therefore loses
* information.
*/
protected String normalize(String path) {
return Normalizer.normalize(path, Normalizer.Form.NFC);
}
/* Does not apply to properties for now (no use case). */
@Override
public Node getNodeByPath(String path, Node node) {
// TODO optimize this to use a dedicated path-based table
checkLive();
if (path == null) {
throw new IllegalArgumentException("Illegal null path");
}
path = normalize(path);
int i;
if (path.startsWith("/")) {
node = getRootNode();
if (path.equals("/")) {
return node;
}
i = 1;
} else {
if (node == null) {
throw new IllegalArgumentException("Illegal relative path with null node: " + path);
}
i = 0;
}
String[] names = path.split("/", -1);
for (; i < names.length; i++) {
String name = names[i];
if (name.length() == 0) {
throw new IllegalArgumentException("Illegal path with empty component: " + path);
}
node = getChildNode(node, name, false);
if (node == null) {
return null;
}
}
return node;
}
@Override
public boolean addMixinType(Node node, String mixin) {
if (model.getMixinPropertyInfos(mixin) == null) {
throw new IllegalArgumentException("No such mixin: " + mixin);
}
if (model.getDocumentTypeFacets(node.getPrimaryType()).contains(mixin)) {
return false; // already present in type
}
List<String> list = new ArrayList<String>(Arrays.asList(node.getMixinTypes()));
if (list.contains(mixin)) {
return false; // already present in node
}
Set<String> otherChildrenNames = getChildrenNames(node.getPrimaryType(), list);
list.add(mixin);
String[] mixins = list.toArray(new String[list.size()]);
node.hierFragment.put(Model.MAIN_MIXIN_TYPES_KEY, mixins);
// immediately create child nodes (for complex properties) in order
// to avoid concurrency issue later on
Map<String, String> childrenTypes = model.getMixinComplexChildren(mixin);
for (Entry<String, String> es : childrenTypes.entrySet()) {
String childName = es.getKey();
String childType = es.getValue();
// child may already exist if the schema is part of the primary type or another facet
if (otherChildrenNames.contains(childName)) {
continue;
}
addChildNode(node, childName, null, childType, true);
}
return true;
}
@Override
public boolean removeMixinType(Node node, String mixin) {
List<String> list = new ArrayList<String>(Arrays.asList(node.getMixinTypes()));
if (!list.remove(mixin)) {
return false; // not present in node
}
String[] mixins = list.toArray(new String[list.size()]);
if (mixins.length == 0) {
mixins = null;
}
node.hierFragment.put(Model.MAIN_MIXIN_TYPES_KEY, mixins);
Set<String> otherChildrenNames = getChildrenNames(node.getPrimaryType(), list);
Map<String, String> childrenTypes = model.getMixinComplexChildren(mixin);
for (String childName : childrenTypes.keySet()) {
// child must be kept if the schema is part of primary type or another facet
if (otherChildrenNames.contains(childName)) {
continue;
}
Node child = getChildNode(node, childName, true);
removePropertyNode(child);
}
node.clearCache();
return true;
}
/**
* Gets complex children names defined by the primary type and the list of mixins.
*/
protected Set<String> getChildrenNames(String primaryType, List<String> mixins) {
Map<String, String> cc = model.getTypeComplexChildren(primaryType);
if (cc == null) {
cc = Collections.emptyMap();
}
Set<String> childrenNames = new HashSet<>(cc.keySet());
for (String mixin : mixins) {
cc = model.getMixinComplexChildren(mixin);
if (cc != null) {
childrenNames.addAll(cc.keySet());
}
}
return childrenNames;
}
@Override
public Node addChildNode(Node parent, String name, Long pos, String typeName, boolean complexProp) {
if (pos == null && !complexProp && parent != null) {
pos = context.getNextPos(parent.getId(), complexProp);
}
return addChildNode(null, parent, name, pos, typeName, complexProp);
}
@Override
public Node addChildNode(Serializable id, Node parent, String name, Long pos, String typeName,
boolean complexProp) {
checkLive();
if (name == null) {
throw new IllegalArgumentException("Illegal null name");
}
name = normalize(name);
if (name.contains("/") || name.equals(".") || name.equals("..")) {
throw new IllegalArgumentException("Illegal name: " + name);
}
if (!model.isType(typeName)) {
throw new IllegalArgumentException("Unknown type: " + typeName);
}
id = generateNewId(id);
Serializable parentId = parent == null ? null : parent.hierFragment.getId();
Node node = addNode(id, parentId, name, pos, typeName, complexProp);
// immediately create child nodes (for complex properties) in order
// to avoid concurrency issue later on
Map<String, String> childrenTypes = model.getTypeComplexChildren(typeName);
for (Entry<String, String> es : childrenTypes.entrySet()) {
String childName = es.getKey();
String childType = es.getValue();
addChildNode(node, childName, null, childType, true);
}
return node;
}
protected Node addNode(Serializable id, Serializable parentId, String name, Long pos, String typeName,
boolean complexProp) {
requireReadAclsUpdate();
// main info
Row hierRow = new Row(Model.HIER_TABLE_NAME, id);
hierRow.putNew(Model.HIER_PARENT_KEY, parentId);
hierRow.putNew(Model.HIER_CHILD_NAME_KEY, name);
hierRow.putNew(Model.HIER_CHILD_POS_KEY, pos);
hierRow.putNew(Model.MAIN_PRIMARY_TYPE_KEY, typeName);
hierRow.putNew(Model.HIER_CHILD_ISPROPERTY_KEY, Boolean.valueOf(complexProp));
SimpleFragment hierFragment = context.createHierarchyFragment(hierRow);
FragmentGroup fragmentGroup = new FragmentGroup(hierFragment, new FragmentsMap());
return new Node(context, fragmentGroup, context.getPath(hierFragment));
}
@Override
public Node addProxy(Serializable targetId, Serializable versionableId, Node parent, String name, Long pos) {
if (!repository.getRepositoryDescriptor().getProxiesEnabled()) {
throw new NuxeoException("Proxies are disabled by configuration");
}
Node proxy = addChildNode(parent, name, pos, Model.PROXY_TYPE, false);
proxy.setSimpleProperty(Model.PROXY_TARGET_PROP, targetId);
proxy.setSimpleProperty(Model.PROXY_VERSIONABLE_PROP, versionableId);
SimpleFragment proxyFragment = (SimpleFragment) proxy.fragments.get(Model.PROXY_TABLE_NAME);
context.createdProxyFragment(proxyFragment);
return proxy;
}
@Override
public void setProxyTarget(Node proxy, Serializable targetId) {
if (!repository.getRepositoryDescriptor().getProxiesEnabled()) {
throw new NuxeoException("Proxies are disabled by configuration");
}
SimpleProperty prop = proxy.getSimpleProperty(Model.PROXY_TARGET_PROP);
Serializable oldTargetId = prop.getValue();
if (!oldTargetId.equals(targetId)) {
SimpleFragment proxyFragment = (SimpleFragment) proxy.fragments.get(Model.PROXY_TABLE_NAME);
context.removedProxyTarget(proxyFragment);
proxy.setSimpleProperty(Model.PROXY_TARGET_PROP, targetId);
context.addedProxyTarget(proxyFragment);
}
}
@Override
public boolean hasChildNode(Node parent, String name, boolean complexProp) {
checkLive();
// TODO could optimize further by not fetching the fragment at all
SimpleFragment fragment = context.getChildHierByName(parent.getId(), normalize(name), complexProp);
return fragment != null;
}
@Override
public Node getChildNode(Node parent, String name, boolean complexProp) {
checkLive();
if (name == null || name.contains("/") || name.equals(".") || name.equals("..")) {
throw new IllegalArgumentException("Illegal name: " + name);
}
SimpleFragment fragment = context.getChildHierByName(parent.getId(), name, complexProp);
return fragment == null ? null : getNodeById(fragment.getId());
}
// TODO optimize with dedicated backend call
@Override
public boolean hasChildren(Node parent, boolean complexProp) {