-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
ODataListBinding.js
2368 lines (2169 loc) · 80.9 KB
/
ODataListBinding.js
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
/*!
* ${copyright}
*/
/*eslint-disable max-len */
//Provides class sap.ui.model.odata.v2.ODataListBinding
sap.ui.define([
"sap/base/assert",
"sap/base/Log",
"sap/base/util/deepEqual",
"sap/base/util/each",
"sap/base/util/isEmptyObject",
"sap/base/util/uid",
"sap/ui/model/ChangeReason",
"sap/ui/model/Context",
"sap/ui/model/Filter",
"sap/ui/model/FilterOperator",
"sap/ui/model/FilterProcessor",
"sap/ui/model/FilterType",
"sap/ui/model/ListBinding",
"sap/ui/model/Sorter",
"sap/ui/model/SorterProcessor",
"sap/ui/model/odata/CountMode",
"sap/ui/model/odata/Filter",
"sap/ui/model/odata/ODataUtils",
"sap/ui/model/odata/OperationMode"
], function(assert, Log, deepEqual, each, isEmptyObject, uid, ChangeReason, Context, Filter,
FilterOperator, FilterProcessor, FilterType, ListBinding, Sorter, SorterProcessor,
CountMode, ODataFilter, ODataUtils, OperationMode) {
"use strict";
var sClassName = "sap.ui.model.odata.v2.ODataListBinding",
aCreateParametersAllowlist = ["changeSetId", "error", "expand", "groupId", "inactive",
"success"];
/**
* @class
* List binding for an OData V2 model.
*
* @param {sap.ui.model.odata.v2.ODataModel} oModel The OData V2 model
* @param {string} sPath The binding path in the model
* @param {sap.ui.model.Context} [oContext]
* The context which is required as base for a relative path.
* @param {sap.ui.model.Sorter[]|sap.ui.model.Sorter} [aSorters=[]]
* The sorters used initially; call {@link #sort} to replace them
* @param {sap.ui.model.Filter[]|sap.ui.model.Filter} [aFilters=[]]
* The filters to be used initially with type {@link sap.ui.model.FilterType.Application}; call {@link #filter} to
* replace them
* @param {object} [mParameters] A map which contains additional parameters for the binding.
* @param {sap.ui.model.odata.CountMode} [mParameters.countMode]
* Defines the count mode of the binding; if not specified, the default count mode of the
* <code>oModel</code> is applied.
* @param {string} [mParameters.createdEntitiesKey=""]
* A key used in combination with the resolved path of the binding to identify the entities
* created by the binding's {@link #create} method.
*
* <b>Note:</b> Different controls or control aggregation bindings to the same collection must
* have different <code>createdEntitiesKey</code> values.
* @param {Object<string,string>} [mParameters.custom]
* An optional map of custom query parameters. Custom parameters must not start with
* <code>$</code>.
* @param {string} [mParameters.expand]
* Value for the OData <code>$expand</code> query option parameter which is included in the
* data request after URL encoding of the given value.
* @param {boolean} [mParameters.faultTolerant]
* Turns on the fault tolerance mode, data is not reset if a back-end request returns an
* error.
* @param {string} [mParameters.groupId]
* The group id to be used for requests originating from the binding
* @param {sap.ui.model.odata.OperationMode} [mParameters.operationMode]
* The operation mode of the binding
* @param {string} [mParameters.select]
* Value for the OData <code>$select</code> query option parameter which is included in the
* data request after URL encoding of the given value.
* @param {boolean} [mParameters.transitionMessagesOnly]
* Whether the list binding only requests transition messages from the back end. If messages
* for entities of this collection need to be updated, use
* {@link sap.ui.model.odata.v2.ODataModel#read} on the parent entity corresponding to the
* list binding's context, with the parameter <code>updateAggregatedMessages</code> set to
* <code>true</code>.
* @param {boolean} [mParameters.usePreliminaryContext]
* Whether a preliminary context is used. When set to <code>true</code>, the model can
* bundle the OData calls for dependent bindings into fewer $batch requests. For more
* information, see
* {@link topic:6c47b2b39db9404582994070ec3d57a2#loio62149734b5c24507868e722fe87a75db
* Optimizing Dependent Bindings}.
* @param {string} [mParameters.batchGroupId]
* <b>Deprecated</b>, use <code>groupId</code> instead. Sets the batch group id to be used for
* requests originating from the binding.
* @param {int} [mParameters.threshold]
* Deprecated since 1.102.0, as {@link sap.ui.model.odata.OperationMode.Auto} is deprecated;
* the threshold that defines how many entries should be fetched at least by the binding if
* <code>operationMode</code> is set to <code>Auto</code>.
* @throws {Error} If one of the filters uses an operator that is not supported by the underlying model
* implementation or if the {@link sap.ui.model.Filter.NONE} filter instance is contained in
* <code>aFilters</code> together with other filters
* @public
* @alias sap.ui.model.odata.v2.ODataListBinding
* @extends sap.ui.model.ListBinding
*/
var ODataListBinding = ListBinding.extend("sap.ui.model.odata.v2.ODataListBinding", /** @lends sap.ui.model.odata.v2.ODataListBinding.prototype */ {
constructor : function(oModel, sPath, oContext, aSorters, aFilters, mParameters) {
ListBinding.apply(this, arguments);
this.sFilterParams = null;
this.sSortParams = null;
this.sCustomParams = this.oModel.createCustomParams(this.mParameters);
this.mCustomParams = mParameters && mParameters.custom;
this.iLength = 0;
this.bPendingChange = false;
this.aAllKeys = null;
this.aKeys = [];
this.sCountMode = (mParameters && mParameters.countMode) || this.oModel.sDefaultCountMode;
this.sOperationMode = (mParameters && mParameters.operationMode) || this.oModel.sDefaultOperationMode;
this.bUsePreliminaryContext = (mParameters && mParameters.usePreliminaryContext) || oModel.bPreliminaryContext;
// avoid data request if the binding receives a preliminary context on construction, but does not use it
if (!this.bUsePreliminaryContext && oContext && oContext.isPreliminary && oContext.isPreliminary()) {
this.oContext = oContext = undefined;
}
this.bRefresh = false;
this.bNeedsUpdate = false;
this.bDataAvailable = false;
this.bIgnoreSuspend = false;
this.bPendingRefresh = false;
this.sGroupId = undefined;
this.sRefreshGroupId = undefined;
this.bLengthRequested = false;
this.bUseExtendedChangeDetection = false;
this.bFaultTolerant = mParameters && mParameters.faultTolerant;
this.bLengthFinal = false;
this.iLastEndIndex = 0;
this.aLastContexts = null;
this.aLastContextData = null;
this.bInitial = true;
this.mRequestHandles = {};
this.oCountHandle = null;
this.bSkipDataEvents = false;
this.bUseExpandedList = false;
this.oCombinedFilter = null;
this.sDeepPath = oModel.resolveDeep(sPath, oContext);
this.bCanonicalRequest = mParameters && mParameters.bCanonicalRequest;
this.mNormalizeCache = {};
this.bTransitionMessagesOnly = !!(mParameters
&& mParameters.transitionMessagesOnly);
this.sCreatedEntitiesKey = mParameters && mParameters.createdEntitiesKey || "";
this.oCreatedPersistedToRemove = new Set();
// whether persisted, created contexts are removed after successful GET for a binding refresh
this.bRemovePersistedCreatedAfterRefresh = false;
// check filter integrity
this.oModel.checkFilter(this.aApplicationFilters);
if (mParameters && (mParameters.batchGroupId || mParameters.groupId)) {
this.sGroupId = mParameters.groupId || mParameters.batchGroupId;
}
this.iThreshold = (mParameters && mParameters.threshold) || 0;
// flag to check if the threshold was rejected after a count was issued
this.bThresholdRejected = false;
if (this.sCountMode == CountMode.None) {
// In CountMode.None, the threshold is implicitly rejected
this.bThresholdRejected = true;
}
if (!this.checkExpandedList()) {
this._removePersistedCreatedContexts();
this.resetData();
}
this._reassignCreateActivate();
},
metadata : {
publicMethods : ["getLength"]
}
});
/**
* The 'createActivate' event is fired when a property is changed on a context in an 'inactive'
* state (see {@link #create}). The context then changes its state to 'transient'. Since
* 1.113.0, this default behavior can be prevented by calling
* {@link sap.ui.base.Event#preventDefault}. The context will then remain in the 'inactive'
* state.
*
* @param {sap.ui.base.Event} oEvent The event object
* @param {sap.ui.model.odata.v2.ODataListBinding} oEvent.getSource This binding
* @param {sap.ui.model.odata.v2.Context} oEvent.getParameters.context The affected context
*
* @event sap.ui.model.odata.v2.ODataListBinding#createActivate
* @public
* @since 1.98.0
*/
/**
* Attach event handler <code>fnFunction</code> to the 'createActivate' event of this binding.
*
* @param {function} fnFunction The function to call when the event occurs
* @param {object} [oListener] Object on which to call the given function
*
* @public
* @since 1.98.0
*/
ODataListBinding.prototype.attachCreateActivate = function (fnFunction, oListener) {
this.attachEvent("createActivate", fnFunction, oListener);
};
/**
* Detach event handler <code>fnFunction</code> from the 'createActivate' event of this binding.
*
* @param {function} fnFunction The function to call when the event occurs
* @param {object} [oListener] Object on which to call the given function
*
* @public
* @since 1.98.0
*/
ODataListBinding.prototype.detachCreateActivate = function (fnFunction, oListener) {
this.detachEvent("createActivate", fnFunction, oListener);
};
/**
* This helper function must be called only by {@link #getContexts}. It updates
* <code>iLastStartIndex</code>, <code>iLastLength</code> and
* <code>iLastMaximumPrefetchSize</code> with the given start index, length and maximum prefetch
* size. If <code>bKeepCurrent</code> is set, throw an error if keeping
* current contexts untouched is not supported, otherwise don't update
* <code>iLastStartIndex</code>, <code>iLastLength</code> and
* <code>iLastMaximumPrefetchSize</code>.
*
* @param {int} [iStartIndex]
* The start index
* @param {int} [iLength]
* The length
* @param {int} [iMaximumPrefetchSize]
* The maximum number of contexts to read before and after the given range
* @param {boolean} [bKeepCurrent]
* Whether the result of {@link #getCurrentContexts} keeps untouched
* @throws {Error}
* If extended change detection is enabled and <code>bKeepCurrent</code> is set, or if
* <code>iMaximumPrefetchSize</code> and <code>bKeepCurrent</code> are set
*
* @private
*/
ODataListBinding.prototype._updateLastStartAndLength = function (iStartIndex, iLength,
iMaximumPrefetchSize, bKeepCurrent) {
if (bKeepCurrent) {
this._checkKeepCurrentSupported(iMaximumPrefetchSize);
} else {
this.iLastStartIndex = iStartIndex;
this.iLastLength = iLength;
this.iLastMaximumPrefetchSize = iMaximumPrefetchSize;
}
};
/**
* Returns all current contexts of this list binding in no special order. Just like
* {@link #getCurrentContexts}, this method does not request any data from a back end and does
* not change the binding's state. In contrast to {@link #getCurrentContexts}, it does not only
* return those contexts that were last requested by a control, but all contexts that are
* currently available in the binding.
*
* @returns {sap.ui.model.odata.v2.Context[]}
* All current contexts of this list binding, in no special order
*
* @public
* @since 1.98.0
*/
ODataListBinding.prototype.getAllCurrentContexts = function () {
var aContexts = this._getCreatedContexts(),
that = this;
this.aKeys.forEach(function (sKey) {
aContexts.push(that.oModel.getContext("/" + sKey));
});
return aContexts;
};
/**
* Returns the context at the given index.
*
* @param {number} iIndex The index of the context
*
* @returns {sap.ui.model.odata.v2.Context|undefined}
* The context at the given index or <code>undefined</code> if no context exists at the given index
*
* @private
* @ui5-restricted sap.ui.table
*/
ODataListBinding.prototype.getContextByIndex = function (iIndex) {
return this._getContexts(iIndex, 1)[0];
};
/**
* Return contexts for the list.
*
* @param {int} [iStartIndex=0]
* The index where to start the retrieval of contexts
* @param {int} [iLength]
* The number of contexts to retrieve beginning from the start index; defaults to the model's
* size limit, see {@link sap.ui.model.Model#setSizeLimit}, or to the binding's final length
* @param {int} [iMaximumPrefetchSize=0]
* The maximum number of contexts to read before and after the given range; with this,
* controls can prefetch data that is likely to be needed soon, e.g. when scrolling down in a
* table
* @param {boolean} [bKeepCurrent]
* Whether this call keeps the result of {@link #getCurrentContexts} untouched; since 1.102.0.
* @return {sap.ui.model.odata.v2.Context[]}
* The array of already available contexts with the first entry containing the context for
* <code>iStartIndex</code>
* @throws {Error}
* If extended change detection is enabled and <code>bKeepCurrent</code> is set, or if
* <code>iMaximumPrefetchSize</code> and <code>bKeepCurrent</code> are set
*
* @protected
*/
ODataListBinding.prototype.getContexts = function(iStartIndex, iLength, iMaximumPrefetchSize,
bKeepCurrent) {
var aContexts, aContextData, oSkipAndTop;
if (this.bInitial) {
return [];
}
// OperationMode.Auto: handle synchronized count to check what the actual internal operation mode should be
// but only when using CountMode.Request or Both.
if (!this.bLengthFinal && this.sOperationMode == OperationMode.Auto && (this.sCountMode == CountMode.Request || this.sCountMode == CountMode.Both)) {
if (!this.bLengthRequested) {
this._getLength();
this.bLengthRequested = true;
}
return [];
}
//get length
if (!this.bLengthFinal && !this.bPendingRequest && !this.bLengthRequested) {
this._getLength();
this.bLengthRequested = true;
}
//this.bInitialized = true;
this._updateLastStartAndLength(iStartIndex, iLength, iMaximumPrefetchSize, bKeepCurrent);
if (!iStartIndex) {
iStartIndex = 0;
}
if (!iLength) {
iLength = this._getMaximumLength();
}
if (!iMaximumPrefetchSize) {
iMaximumPrefetchSize = 0;
}
// re-set the threshold in OperationMode.Auto
if (this.sOperationMode == OperationMode.Auto) {
if (this.iThreshold >= 0) {
iMaximumPrefetchSize = Math.max(this.iThreshold, iMaximumPrefetchSize);
}
}
aContexts = this._getContexts(iStartIndex, iLength);
if (this.oCombinedFilter === Filter.NONE || this._hasTransientParentContext()) {
// skip #loadData
} else if (this.useClientMode()) {
if (!this.aAllKeys && !this.bPendingRequest && this.oModel.getServiceMetadata()) {
this.loadData();
aContexts.dataRequested = true;
}
} else {
oSkipAndTop = this._getSkipAndTop(iStartIndex, iLength, iMaximumPrefetchSize);
// check if metadata are already available
if (this.oModel.getServiceMetadata()) {
// If rows are missing send a request
if (!this.bPendingRequest && oSkipAndTop) {
this.loadData(oSkipAndTop.skip, oSkipAndTop.top);
aContexts.dataRequested = true;
}
}
}
// Do not return created contexts at end if data request is pending
if (this.isFirstCreateAtEnd()
&& this.bPendingRequest
&& aContexts.length && aContexts[0].isTransient() !== undefined) {
aContexts.length = 0; // only reset length => still keep properties like dataRequested
}
if (this.bRefresh) {
this.bRefresh = false;
// if we do not need to load data after a refresh event (e.g. we have enough created
// contexts) we need to fire a change event to fulfill the contract that after a refresh
// event a change event is triggered when the data is available.
if (!aContexts.dataRequested && aContexts.length > 0) {
this._fireChange({reason : ChangeReason.Change});
}
} else if (!bKeepCurrent) {
// Do not create context data and diff in case of refresh, only if real data has been received
// The current behaviour is wrong and makes diff detection useless for OData in case of refresh
aContextData = [];
for (var i = 0; i < aContexts.length; i++) {
aContextData.push(this.getContextData(aContexts[i]));
}
if (this.bUseExtendedChangeDetection) {
//Check diff
if (this.aLastContexts && iStartIndex < this.iLastEndIndex) {
aContexts.diff = this.diffData(this.aLastContextData, aContextData);
}
}
this.iLastEndIndex = iStartIndex + iLength;
this.aLastContexts = aContexts.slice(0);
this.aLastContextData = aContextData;
}
return aContexts;
};
ODataListBinding.prototype.getCurrentContexts = function() {
return this.aLastContexts || [];
};
/**
* Returns the entry key for the given context.
*
* As in OData all entities have a unique ID in the URL, the path of the
* context is suitable here.
*
* @param {sap.ui.model.Context} oContext The context
* @returns {string} The entry key for the given context
*
* @private
*/
ODataListBinding.prototype.getEntryKey = function(oContext) {
return oContext.getPath();
};
/**
* Returns the entry data as required for change detection/diff.
*
* This is a JSON serialization of the entity, in case select/expand were used with only the
* selected/expanded parts.
*
* @param {sap.ui.model.Context} oContext
* The context
* @returns {any}
* The value for the given context or <code>undefined</code> if data or entity type
* cannot be found or if not all selected properties are available
*
* @private
*/
ODataListBinding.prototype.getEntryData = function(oContext) {
return JSON.stringify(oContext.getObject(this.mParameters));
};
/**
* Returns contexts for the list without gaps.
*
* @param {number} [iStartIndex=0]
* The start index of the requested contexts
* @param {number} [iLength]
* The requested amount of contexts
* @return {sap.ui.model.odata.v2.Context[]}
* The available contexts for the given range; if there is no context for an index in this
* range, the succeeding indexes are not considered so that the returned array has no gaps
*
* @private
*/
ODataListBinding.prototype._getContexts = function (iStartIndex, iLength) {
var oContext, i, iEndIndex, sKey,
bAtEnd = this.isFirstCreateAtEnd(),
aContexts = [],
aCreatedContexts = this._getCreatedContexts(),
iCreated = aCreatedContexts.length,
sDeepPath = this.oModel.resolveDeep(this.sPath, this.oContext);
if (!iStartIndex) {
iStartIndex = 0;
}
if (!iLength) {
iLength = this._getMaximumLength();
}
iEndIndex = iStartIndex + iLength;
for (i = iStartIndex; i < iEndIndex; i += 1) {
if (!bAtEnd && i < iCreated) { // creation area at the start
oContext = aCreatedContexts[i];
} else if (bAtEnd && i >= this.iLength) { // creation area at the end
if (i - this.iLength >= iCreated) {
break;
}
oContext = aCreatedContexts[i - this.iLength];
} else { // backend contexts
sKey = this.aKeys[bAtEnd ? i : i - iCreated];
if (!sKey) {
break; // avoid gaps
}
oContext = this.oModel.getContext('/' + sKey,
sDeepPath + sKey.substr(sKey.indexOf("(")));
}
aContexts.push(oContext);
}
return aContexts;
};
/**
* Setter for context.
*
* Entities that have been created via {@link #create} and saved in the back end are removed
* from the creation rows area and inserted at the right position based on the current filters
* and sorters.
*
* @param {Object} oContext
* The new context object
* @throws {Error}
* If the context was changed and this binding has transient contexts; see {@link #create} and
* {@link sap.ui.model.odata.v2.Context#isTransient}
*/
ODataListBinding.prototype.setContext = function (oContext) {
var bHadNonTransientContext, sResolvedPath,
bForceUpdate = oContext && oContext.isRefreshForced(),
bPreliminary = oContext && oContext.isPreliminary(),
bUpdated = oContext && oContext.isUpdated();
// If binding is initial or not a relative binding, nothing to do here
if (this.bInitial || !this.isRelative()) {
return;
}
// If context is preliminary and usePreliminary is not set, exit here
if (bPreliminary && !this.bUsePreliminaryContext) {
return;
}
if (bUpdated && this.bUsePreliminaryContext && this.oContext === oContext) {
this._fireChange({ reason: ChangeReason.Context });
return;
}
if (Context.hasChanged(this.oContext, oContext)) {
bHadNonTransientContext = this.isResolved()
&& !this._hasTransientParentWithoutSubContexts();
this.oContext = oContext;
sResolvedPath = this.getResolvedPath(); // resolved path with the new context
this.sDeepPath = this.oModel.resolveDeep(this.sPath, this.oContext);
if (!this._checkPathType()) {
Log.error("List Binding is not bound against a list for " + sResolvedPath, undefined, sClassName);
}
// ensure that data state is updated with each change of the context
this.checkDataState();
if (!sResolvedPath || this._hasTransientParentWithoutSubContexts()) {
this.aAllKeys = null;
this.aKeys = [];
this.iLength = 0;
this.bLengthFinal = true;
this.abortPendingRequest();
if (bHadNonTransientContext) {
this._fireChange({reason : ChangeReason.Context});
}
return;
}
// get new entity type with new context and init filters now correctly
this._initSortersFilters();
if (this.checkExpandedList() && !bForceUpdate) {
// if there are pending requests e.g. previous context requested data which returns
// null the pending requests need to be aborted such that the responded (previous)
// data doesn't overwrite the current one
this.abortPendingRequest();
this._fireChange({reason : ChangeReason.Context});
} else {
this._removePersistedCreatedContexts();
this._refresh();
}
}
};
/**
* In side-effects scenarios, iterates all created persisted contexts of this list binding and
* removes those entities (with its context, pending changes, messages, ...) which are not
* included in the latest back-end response for an expanded list. If this list binding is
* suspended, the affected entity keys are temporarily stored to remove those entities later
* after the list binding has been resumed.
*
* @returns {boolean}
* Whether created persisted contexts have been removed
*
* @private
*/
ODataListBinding.prototype._cleanupCreatedPersisted = function () {
var bCreatedPersistedRemoved = false,
aList = this.oModel._getObject(this.sPath, this.oContext),
that = this;
function removeItem(sEntityKey) {
that.oModel._discardEntityChanges(sEntityKey, true);
bCreatedPersistedRemoved = true;
}
if (this.oCreatedPersistedToRemove.size && !this.bSuspended) {
this.oCreatedPersistedToRemove.forEach(removeItem);
this.oCreatedPersistedToRemove.clear();
}
if (aList && aList.sideEffects) {
this._getCreatedPersistedContexts().forEach(function (oContext) {
var sEntityKey = that.oModel.getKey(oContext);
if (!aList.includes(sEntityKey)) { // entity has been deleted on the server
if (that.bSuspended) {
that.oCreatedPersistedToRemove.add(sEntityKey);
} else {
removeItem(sEntityKey);
}
}
});
}
return bCreatedPersistedRemoved;
};
/**
* Checks whether expanded list data is available and can be used.
*
* @param {boolean} bSkipReloadNeeded
* Don't check whether reload of expanded data is needed
* @return {boolean}
* Whether expanded data is available and is used
*
* @private
*/
ODataListBinding.prototype.checkExpandedList = function(bSkipReloadNeeded) {
// if nested list is already available and no filters or sorters are set, use the data and
// don't send additional requests
// $expand loads all associated entities, no paging parameters possible, so we can safely
// assume all data is available
var aCreatedPersistedKeys,
aList = this.oModel._getObject(this.sPath, this.oContext),
bOldUseExpandedList = this.bUseExpandedList,
that = this;
if (!this.isResolved() || aList === undefined || !this._isExpandedListUsable()) {
this.bUseExpandedList = false;
this.aExpandRefs = undefined;
return false;
} else {
this.bUseExpandedList = true;
if (Array.isArray(aList)) {
// For performance, only check first and last entry, whether reload is needed
if (!bSkipReloadNeeded
&& (this.oModel._isReloadNeeded("/" + aList[0], this.mParameters)
|| this.oModel._isReloadNeeded("/" + aList[aList.length - 1],
this.mParameters))) {
this.bUseExpandedList = false;
this.aExpandRefs = undefined;
return false;
}
this.aExpandRefs = aList;
if (aList.sideEffects) {
aCreatedPersistedKeys = this._getCreatedPersistedContexts()
.map(function (oContext) {
return that.oModel.getKey(oContext);
});
if (aCreatedPersistedKeys.length) {
aList = aList.filter(function (sEntityKey) {
return !aCreatedPersistedKeys.includes(sEntityKey);
});
}
}
this.aAllKeys = aList;
this.iLength = aList.length;
this.bLengthFinal = true;
this.bDataAvailable = true;
// ensure sorters/filters for an expanded list are initialized
this._initSortersFilters();
this.applyFilter();
this.applySort();
if (this.aExpandRefs.sideEffects && !bOldUseExpandedList) {
// don't switch expanded list mode if data is read via a side effect
this.aExpandRefs = undefined;
this.bUseExpandedList = false;
return this.bUseExpandedList;
}
} else { // means that expanded data has no data available e.g. for 0..n relations
this.aExpandRefs = undefined;
this.aAllKeys = null;
this.aKeys = [];
this.iLength = 0;
this.bLengthFinal = true;
this.bDataAvailable = true;
}
return true;
}
};
/**
* In case the list is currently based on expanded data, update the original data array
* if new data has been loaded
*
* @private
* @param {array} aKeys the new key array
*/
ODataListBinding.prototype.updateExpandedList = function(aKeys) {
if (this.aExpandRefs) {
// update each entity within the array to update the model data
for (var i = 0; i < aKeys.length; i++) {
this.aExpandRefs[i] = aKeys[i];
}
this.aExpandRefs.length = aKeys.length;
}
};
/**
* Check whether client mode is active. This is either the case if it has
* been explicitly activated by the application, it has been detected
* that all data is available or expanded data is available.
*
* @private
* @return {boolean} Whether clientmode should be used
*/
ODataListBinding.prototype.useClientMode = function() {
return (this.sOperationMode === OperationMode.Client ||
this.sOperationMode === OperationMode.Auto && !this.bThresholdRejected ||
this.sOperationMode !== OperationMode.Server && this.bUseExpandedList);
};
/**
* Adds the $filter query option to the given array of URL parameters if needed.
* The application/control filters, as stored in <code>this.sFilterParams</code> are considered
* only if the given <code>bUseFilterParams</code> is set. The exclude filter for created
* persisted entities is always considered to avoid duplicates or a wrong count.
*
* @param {string[]} aURLParams The array of URL parameters
* @param {boolean} bUseFilterParams Whether to consider <code>this.sFilterParams</code>
*
* @private
*/
ODataListBinding.prototype._addFilterQueryOption = function (aURLParams, bUseFilterParams) {
var sExcludeFilter = this._getCreatedPersistedExcludeFilter();
if (this.sFilterParams && bUseFilterParams) {
if (sExcludeFilter) {
// this.sFilterParams starts with $filter=, so slice it
aURLParams.push("$filter=(" + this.sFilterParams.slice(8) + ")%20and%20"
+ sExcludeFilter);
} else {
aURLParams.push(this.sFilterParams);
}
} else if (sExcludeFilter) {
aURLParams.push("$filter=" + sExcludeFilter);
}
};
/**
* Gets the created and persisted contexts of this list binding.
*
* @returns {sap.ui.model.odata.v2.Context[]} The created and persisted contexts
*
* @private
*/
ODataListBinding.prototype._getCreatedPersistedContexts = function () {
return this._getCreatedContexts().filter(function (oContext) {
return !oContext.isTransient();
});
};
/**
* Gets the exclude filter for the created and persisted contexts of this list binding.
*
* @returns {string|undefined} The exclude filter or <code>undefined</code> if there are no
* created and persisted contexts in the cache.
*
* @private
*/
ODataListBinding.prototype._getCreatedPersistedExcludeFilter = function () {
var sExcludeFilter, aExcludeFilters,
aCreatedPersistedContexts = this._getCreatedPersistedContexts(),
that = this;
if (aCreatedPersistedContexts.length > 0) {
aExcludeFilters = aCreatedPersistedContexts.map(function (oContext) {
var sPath = oContext.getPath();
return that._getFilterForPredicate(sPath.slice(sPath.indexOf("(")));
});
sExcludeFilter = "not("
+ ODataUtils._createFilterParams(aExcludeFilters.length === 1
? aExcludeFilters[0]
: new Filter({filters : aExcludeFilters}),
this.oModel.oMetadata, this.oEntityType)
+ ")";
}
return sExcludeFilter;
};
/**
* Load data for the given range from server.
*
* @param {int} [iStartIndex] The start index
* @param {int} [iLength] The amount of data to be requested
* @private
*/
ODataListBinding.prototype.loadData = function(iStartIndex, iLength) {
var sGroupId, oReadParameters,
sGuid = uid(),
bInlineCountRequested = false,
iLimit = this.oModel.iSizeLimit,
sPath = this.sPath,
bRemovePersistedCreatedAfterRefresh = this.bRemovePersistedCreatedAfterRefresh,
aResultPages = [],
bUseClientMode = this.useClientMode(),
that = this;
function getUrlParameters() {
var aParameters = [];
// create range parameters and store start index for sort/filter requests
if (iLength) {
aParameters.push("$skip=" + iStartIndex + "&$top=" + iLength);
} else {
// For OperationMode.Client and OperationMode.Auto (if the threshold was sufficient)
// loadData is called without iStartIndex and iLength, try reading all data without
// $skip and $top
iStartIndex = 0;
}
if (that.sSortParams) {
aParameters.push(that.sSortParams);
}
that._addFilterQueryOption(aParameters, !bUseClientMode);
if (that.sCustomParams) {
aParameters.push(that.sCustomParams);
}
if (that.sCountMode == CountMode.InlineRepeat
|| !that.bLengthFinal
&& (that.sCountMode === CountMode.Inline || that.sCountMode === CountMode.Both)) {
aParameters.push("$inlinecount=allpages");
bInlineCountRequested = true;
} else {
bInlineCountRequested = false;
}
return aParameters;
}
function fnSuccess(oData) {
// update iLength (only when the inline count was requested and is available)
if (bInlineCountRequested && oData.__count !== undefined) {
that.iLength = parseInt(oData.__count);
that.bLengthFinal = true;
// in the OpertionMode.Auto, we check if the count is LE than the given threshold (which also was requested!)
if (that.sOperationMode == OperationMode.Auto) {
if (that.iLength <= that.mParameters.threshold) {
//the requested data is enough to satisfy the threshold
that.bThresholdRejected = false;
} else {
that.bThresholdRejected = true;
//clean up successful request
delete that.mRequestHandles[sGuid];
that.bPendingRequest = false;
// If request is originating from this binding, change must be fired afterwards
that.bNeedsUpdate = true;
// return since we can't do anything here anymore,
// we have to trigger the loading again, this time with application filters
return;
}
}
}
if (bUseClientMode) {
// For clients mode, store all keys separately and set length to final
if (!iStartIndex) {
that.aKeys = [];
}
each(oData.results, function(i, entry) {
that.aKeys[iStartIndex + i] = that.oModel._getKey(entry);
});
aResultPages.push(oData.results);
if (oData.__next && that.aKeys.length < iLimit /*first request may return enough*/) {
// continue reading
iStartIndex = that.aKeys.length;
iLength = iLimit - iStartIndex; // read up to model size limit
oReadParameters.urlParameters = getUrlParameters();
that.mRequestHandles[sGuid] = that.oModel.read(that.sPath, oReadParameters);
return;
}
that.updateExpandedList(that.aKeys);
that.aAllKeys = that.aKeys.slice();
that.iLength = that.aKeys.length;
that.bLengthFinal = true;
that.applyFilter();
that.applySort();
// For server mode, update data and or length dependent on the current result
} else if (oData.results.length > 0) {
// Collecting contexts, after the <code>$inlinecount</code> was evaluated, so we do
// not have to clear it again when Auto modes initial threshold <> count check
// failed.
each(oData.results, function(i, entry) {
that.aKeys[iStartIndex + i] = that.oModel._getKey(entry);
});
// if we got data and the results + startindex is larger than the
// length we just apply this value to the length
if (that.iLength < iStartIndex + oData.results.length) {
that.iLength = iStartIndex + oData.results.length;
that.bLengthFinal = false;
}
// if less entries are returned than have been requested set length accordingly
if (!oData.__next && (oData.results.length < iLength || iLength === undefined)) {
that.iLength = iStartIndex + oData.results.length;
that.bLengthFinal = true;
}
} else {
// In fault tolerance mode, if an empty array and next link is returned,
// finalize the length accordingly
if (that.bFaultTolerant && oData.__next) {
that.iLength = iStartIndex;
that.bLengthFinal = true;
}
// check if there are any results at all...
if (iStartIndex === 0) {
that.iLength = 0;
that.aKeys = [];
that.bLengthFinal = true;
}
// if next requested page has no results, and startindex = actual length
// we could set lengthFinal true as we know the length.
if (iStartIndex === that.iLength) {
that.bLengthFinal = true;
}
}
delete that.mRequestHandles[sGuid];
that.bPendingRequest = false;
// If request is originating from this binding, change must be fired afterwards
that.bNeedsUpdate = true;
that.bIgnoreSuspend = true;
if (bRemovePersistedCreatedAfterRefresh) {
that._removePersistedCreatedContexts();
}
that.oModel.callAfterUpdate(function () {
if (aResultPages.length > 1) {
that.fireDataReceived({
data: {
__count: String(that.iLength),
results: Array.prototype.concat.apply([], aResultPages)
}
});
} else {
that.fireDataReceived({data: oData});
}
});
}
function fnError(oError) {
var bAborted = oError.statusCode == 0;
delete that.mRequestHandles[sGuid];
that.bPendingRequest = false;
if (that.bFaultTolerant) {
// In case of fault tolerance, don't reset data, but keep the already loaded
// data and set the length to final to prevent further requests
that.iLength = that.aKeys.length;
that.bLengthFinal = true;
that.bDataAvailable = true;
} else if (!bAborted) {
// reset data and trigger update
that.aKeys = [];
that.aAllKeys = [];
that.iLength = 0;
that.bLengthFinal = true;
that.bDataAvailable = true;
that._fireChange({reason: ChangeReason.Change});
}
if (!that.bSkipDataEvents) {
that.fireDataReceived();
}
}
if (this.isRelative()){
sPath = this.getResolvedPath();
}
if (sPath) {
// Execute the request and use the metadata if available
this.bPendingRequest = true;
if (!this.bSkipDataEvents) {
this.fireDataRequested();
}
this.bSkipDataEvents = false;
//if load is triggered by a refresh we have to check the refreshGroup
sGroupId = this.sRefreshGroupId ? this.sRefreshGroupId : this.sGroupId;
oReadParameters = {
headers: this.bTransitionMessagesOnly
? {"sap-messages" : "transientOnly"}
: undefined,