Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 37b00d69bd08f3f4dacaf2119b975a2d16be6ac8 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
/*
 * Copyright (c) 2010-2015 Eike Stepper (Berlin, Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Eike Stepper - initial API and implementation
 *    Simon McDuff - maintenance
 *    Victor Roldan Betancort - maintenance
 */
package org.eclipse.emf.internal.cdo.view;

import org.eclipse.emf.cdo.CDOObject;
import org.eclipse.emf.cdo.CDOObjectHistory;
import org.eclipse.emf.cdo.CDOObjectReference;
import org.eclipse.emf.cdo.CDOState;
import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.branch.CDOBranchManager;
import org.eclipse.emf.cdo.common.branch.CDOBranchPoint;
import org.eclipse.emf.cdo.common.commit.CDOChangeSetData;
import org.eclipse.emf.cdo.common.commit.CDOCommitHistory;
import org.eclipse.emf.cdo.common.commit.CDOCommitInfoManager;
import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.id.CDOIDExternal;
import org.eclipse.emf.cdo.common.id.CDOIDUtil;
import org.eclipse.emf.cdo.common.id.CDOWithID;
import org.eclipse.emf.cdo.common.model.CDOClassifierRef;
import org.eclipse.emf.cdo.common.model.CDOModelUtil;
import org.eclipse.emf.cdo.common.protocol.CDOProtocolConstants;
import org.eclipse.emf.cdo.common.revision.CDOIDAndVersion;
import org.eclipse.emf.cdo.common.revision.CDOList;
import org.eclipse.emf.cdo.common.revision.CDORevision;
import org.eclipse.emf.cdo.common.revision.CDORevisionData;
import org.eclipse.emf.cdo.common.revision.CDORevisionKey;
import org.eclipse.emf.cdo.common.revision.delta.CDOContainerFeatureDelta;
import org.eclipse.emf.cdo.common.revision.delta.CDOFeatureDelta;
import org.eclipse.emf.cdo.common.revision.delta.CDOListFeatureDelta;
import org.eclipse.emf.cdo.common.revision.delta.CDORevisionDelta;
import org.eclipse.emf.cdo.common.security.CDOPermission;
import org.eclipse.emf.cdo.common.util.CDOCommonUtil;
import org.eclipse.emf.cdo.common.util.CDOException;
import org.eclipse.emf.cdo.eresource.CDOBinaryResource;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.eresource.CDOResourceFolder;
import org.eclipse.emf.cdo.eresource.CDOResourceNode;
import org.eclipse.emf.cdo.eresource.CDOTextResource;
import org.eclipse.emf.cdo.eresource.EresourcePackage;
import org.eclipse.emf.cdo.eresource.impl.CDOResourceImpl;
import org.eclipse.emf.cdo.eresource.impl.CDOResourceNodeImpl;
import org.eclipse.emf.cdo.internal.common.commit.CDOCommitHistoryProviderImpl;
import org.eclipse.emf.cdo.internal.common.revision.delta.CDORevisionDeltaImpl;
import org.eclipse.emf.cdo.session.CDOSession;
import org.eclipse.emf.cdo.spi.common.branch.CDOBranchUtil;
import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.util.CDOURIUtil;
import org.eclipse.emf.cdo.util.CDOUtil;
import org.eclipse.emf.cdo.util.DanglingReferenceException;
import org.eclipse.emf.cdo.util.InvalidURIException;
import org.eclipse.emf.cdo.util.ObjectNotFoundException;
import org.eclipse.emf.cdo.util.ReadOnlyException;
import org.eclipse.emf.cdo.view.CDOAdapterPolicy;
import org.eclipse.emf.cdo.view.CDOObjectHandler;
import org.eclipse.emf.cdo.view.CDOQuery;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.emf.cdo.view.CDOViewAdaptersNotifiedEvent;
import org.eclipse.emf.cdo.view.CDOViewEvent;
import org.eclipse.emf.cdo.view.CDOViewProvider;
import org.eclipse.emf.cdo.view.CDOViewTargetChangedEvent;

import org.eclipse.emf.internal.cdo.bundle.OM;
import org.eclipse.emf.internal.cdo.messages.Messages;
import org.eclipse.emf.internal.cdo.object.CDOLegacyAdapter;
import org.eclipse.emf.internal.cdo.query.CDOQueryImpl;
import org.eclipse.emf.internal.cdo.transaction.CDOTransactionImpl;

import org.eclipse.net4j.util.AdapterUtil;
import org.eclipse.net4j.util.CheckUtil;
import org.eclipse.net4j.util.ImplementationError;
import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
import org.eclipse.net4j.util.StringUtil;
import org.eclipse.net4j.util.WrappedException;
import org.eclipse.net4j.util.collection.CloseableIterator;
import org.eclipse.net4j.util.collection.ConcurrentArray;
import org.eclipse.net4j.util.collection.Pair;
import org.eclipse.net4j.util.concurrent.DelegableReentrantLock;
import org.eclipse.net4j.util.container.IContainerDelta;
import org.eclipse.net4j.util.container.IContainerEvent;
import org.eclipse.net4j.util.container.SelfAttachingContainerListener.DoNotDescend;
import org.eclipse.net4j.util.container.SingleDeltaContainerEvent;
import org.eclipse.net4j.util.event.IListener;
import org.eclipse.net4j.util.lifecycle.LifecycleException;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.om.log.OMLogger;
import org.eclipse.net4j.util.om.trace.ContextTracer;
import org.eclipse.net4j.util.ref.KeyedReference;
import org.eclipse.net4j.util.ref.ReferenceType;
import org.eclipse.net4j.util.ref.ReferenceValueMap2;
import org.eclipse.net4j.util.registry.HashMapRegistry;
import org.eclipse.net4j.util.registry.IRegistry;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.impl.AdapterImpl;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.spi.cdo.CDOStore;
import org.eclipse.emf.spi.cdo.FSMUtil;
import org.eclipse.emf.spi.cdo.InternalCDOObject;
import org.eclipse.emf.spi.cdo.InternalCDOSession;
import org.eclipse.emf.spi.cdo.InternalCDOView;
import org.eclipse.emf.spi.cdo.InternalCDOViewSet;

import org.eclipse.core.runtime.IProgressMonitor;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author Eike Stepper
 */
public abstract class AbstractCDOView extends CDOCommitHistoryProviderImpl<CDOObject, CDOObjectHistory>
    implements InternalCDOView, DoNotDescend
{
  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_VIEW, AbstractCDOView.class);

  private static final String REPOSITORY_NAME_KEY = "cdo.repository.name";

  private static final ThreadLocal<Lock> NEXT_VIEW_LOCK = new ThreadLocal<Lock>();

  private final ViewAndState[] viewAndStates = ViewAndState.create(this);

  private final CDOURIHandler uriHandler = new CDOURIHandler(this);

  protected final Lock viewLock;

  protected final Condition viewLockCondition;

  private CDOBranchPoint branchPoint;

  private CDOBranchPoint normalizedBranchPoint;

  private CDOViewProvider provider;

  private InternalCDOViewSet viewSet;

  private Map<CDOID, InternalCDOObject> objects;

  private CDOStore store = new CDOStoreImpl(this);

  private CDOResourceImpl rootResource;

  private CDOID rootResourceID;

  private final ConcurrentArray<CDOObjectHandler> objectHandlers = new ConcurrentArray<CDOObjectHandler>()
  {
    @Override
    protected CDOObjectHandler[] newArray(int length)
    {
      return new CDOObjectHandler[length];
    }
  };

  private final IRegistry<String, Object> properties = new HashMapRegistry<String, Object>()
  {
    @Override
    public void setAutoCommit(boolean autoCommit)
    {
      throw new UnsupportedOperationException();
    }
  };

  @ExcludeFromDump
  private transient Map<String, CDOID> resourcePathCache = new HashMap<String, CDOID>();

  @ExcludeFromDump
  private transient CDOID lastLookupID;

  @ExcludeFromDump
  private transient InternalCDOObject lastLookupObject;

  public AbstractCDOView(CDOSession session, CDOBranchPoint branchPoint)
  {
    this(session);
    basicSetBranchPoint(branchPoint);
  }

  public AbstractCDOView(CDOSession session)
  {
    Lock lock = NEXT_VIEW_LOCK.get();
    if (lock != null)
    {
      NEXT_VIEW_LOCK.remove();
    }
    else if (session != null && session.options().isDelegableViewLockEnabled())
    {
      lock = new DelegableReentrantLock();
    }

    viewLock = lock;
    viewLockCondition = viewLock != null ? viewLock.newCondition() : null;

    initObjectsMap(ReferenceType.SOFT);
  }

  public final IRegistry<String, Object> properties()
  {
    return properties;
  }

  public String getRepositoryName()
  {
    Object repositoryName = properties.get(REPOSITORY_NAME_KEY);
    if (repositoryName instanceof String)
    {
      return (String)repositoryName;
    }

    return getSession().getRepositoryInfo().getName();
  }

  public void setRepositoryName(String repositoryName)
  {
    properties.put(REPOSITORY_NAME_KEY, repositoryName);
  }

  public boolean isReadOnly()
  {
    return true;
  }

  @Deprecated
  public boolean isLegacyModeEnabled()
  {
    return true;
  }

  protected final Map<CDOID, InternalCDOObject> getModifiableObjects()
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return objects;
      }
      finally
      {
        unlockView();
      }
    }
  }

  public Map<CDOID, InternalCDOObject> getObjects()
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (objects == null)
        {
          return Collections.emptyMap();
        }

        return Collections.unmodifiableMap(objects);
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected final void setObjects(Map<CDOID, InternalCDOObject> objects)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        this.objects = objects;
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected boolean initObjectsMap(ReferenceType referenceType)
  {
    ReferenceValueMap2<CDOID, InternalCDOObject> newObjects;

    switch (referenceType)
    {
    case STRONG:
    {
      if (objects instanceof ReferenceValueMap2.Strong<?, ?>)
      {
        return false;
      }

      Map<CDOID, KeyedReference<CDOID, InternalCDOObject>> map = CDOIDUtil.createMap();
      newObjects = new ReferenceValueMap2.Strong<CDOID, InternalCDOObject>(map);
      break;
    }

    case SOFT:
    {
      if (objects instanceof ReferenceValueMap2.Soft<?, ?>)
      {
        return false;
      }

      Map<CDOID, KeyedReference<CDOID, InternalCDOObject>> map = CDOIDUtil.createMap();
      newObjects = new ReferenceValueMap2.Soft<CDOID, InternalCDOObject>(map);
      break;
    }

    case WEAK:
    {
      if (objects instanceof ReferenceValueMap2.Weak<?, ?>)
      {
        return false;
      }

      Map<CDOID, KeyedReference<CDOID, InternalCDOObject>> map = CDOIDUtil.createMap();
      newObjects = new ReferenceValueMap2.Weak<CDOID, InternalCDOObject>(map);
      break;
    }

    default:
      throw new IllegalArgumentException(Messages.getString("CDOViewImpl.29")); //$NON-NLS-1$
    }

    if (objects == null)
    {
      setObjects(newObjects);
    }
    else
    {
      for (Entry<CDOID, InternalCDOObject> entry : objects.entrySet())
      {
        InternalCDOObject object = entry.getValue();
        if (object != null)
        {
          newObjects.put(entry.getKey(), object);
        }
      }

      Map<CDOID, InternalCDOObject> oldObjects = objects;
      setObjects(newObjects);
      oldObjects.clear();
    }

    return true;
  }

  public ViewAndState getViewAndState(CDOState state)
  {
    return viewAndStates[state.ordinal()];
  }

  public CDOStore getStore()
  {
    checkActive();
    return store;
  }

  public ResourceSet getResourceSet()
  {
    return getViewSet().getResourceSet();
  }

  /**
   * @since 2.0
   */
  public InternalCDOViewSet getViewSet()
  {
    return viewSet;
  }

  /**
   * @since 2.0
   */
  public void setViewSet(InternalCDOViewSet viewSet)
  {
    this.viewSet = viewSet;
    if (viewSet != null)
    {
      viewSet.getResourceSet().getURIConverter().getURIHandlers().add(0, getURIHandler());
    }
  }

  public final Object getViewMonitor()
  {
    if (viewLock != null)
    {
      return new NOOPMonitor();
    }

    return this;
  }

  public final Lock getViewLock()
  {
    return viewLock;
  }

  public final void lockView()
  {
    if (viewLock != null)
    {
      viewLock.lock();
    }
  }

  public final void unlockView()
  {
    if (viewLock != null)
    {
      viewLock.unlock();
    }
  }

  public void syncExec(Runnable runnable)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        runnable.run();
      }
      finally
      {
        unlockView();
      }
    }
  }

  public <V> V syncExec(Callable<V> callable) throws Exception
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return callable.call();
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CDOViewProvider getProvider()
  {
    return provider;
  }

  public void setProvider(CDOViewProvider provider)
  {
    this.provider = provider;

    if (viewSet != null)
    {
      viewSet.remapView(this);
    }
  }

  public void setSession(InternalCDOSession session)
  {
    rootResourceID = session.getRepositoryInfo().getRootResourceID();
    if (rootResourceID == null || rootResourceID.isNull())
    {
      throw new IllegalStateException("RootResourceID is null; is the repository not yet initialized?");
    }
  }

  public CDOResourceImpl getRootResource()
  {
    checkActive();

    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (rootResource == null)
        {
          getObject(rootResourceID);
          CheckUtil.checkState(rootResource, "rootResource");
        }

        return rootResource;
      }
      finally
      {
        unlockView();
      }
    }
  }

  private void setRootResource(CDOResourceImpl resource)
  {
    rootResource = resource;
    rootResource.setRoot(true);
    registerObject(rootResource);

    try
    {
      rootResource.load(null);
    }
    catch (IOException ex)
    {
      throw WrappedException.wrap(ex);
    }
  }

  @SuppressWarnings("deprecation")
  public URI createResourceURI(String path)
  {
    if (provider != null)
    {
      URI uri = provider.getResourceURI(this, path);
      if (uri != null)
      {
        return uri;
      }
    }

    InternalCDOSession session = getSession();
    return CDOURIUtil.createResourceURI(session, path);
  }

  public boolean isEmpty()
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOResource rootResource = getRootResource();
        if (rootResource.cdoPermission() == CDOPermission.NONE)
        {
          return true;
        }

        boolean empty = rootResource.getContents().isEmpty();
        ensureContainerAdapter(rootResource);
        return empty;
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CDOResourceNode[] getElements()
  {
    List<CDOResourceNode> elements = new ArrayList<CDOResourceNode>();
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (isActive())
        {
          CDOResource rootResource = getRootResource();
          EList<EObject> contents = rootResource.getContents();

          for (EObject object : contents)
          {
            if (object instanceof CDOResourceNode)
            {
              CDOResourceNode element = (CDOResourceNode)object;
              elements.add(element);
            }
          }

          ensureContainerAdapter(rootResource);
        }
      }
      finally
      {
        unlockView();
      }

      return elements.toArray(new CDOResourceNode[elements.size()]);
    }
  }

  private void ensureContainerAdapter(final CDOResource rootResource)
  {
    EList<Adapter> adapters = rootResource.eAdapters();
    ContainerAdapter adapter = getContainerAdapter(adapters);
    if (adapter == null)
    {
      adapter = new ContainerAdapter();
      adapters.add(adapter);

      options().addChangeSubscriptionPolicy(new CDOAdapterPolicy()
      {
        public boolean isValid(EObject eObject, Adapter adapter)
        {
          return eObject == rootResource;
        }
      });
    }
  }

  private ContainerAdapter getContainerAdapter(EList<Adapter> adapters)
  {
    for (Adapter adapter : adapters)
    {
      if (adapter instanceof ContainerAdapter && ((ContainerAdapter)adapter).getView() == this)
      {
        return (ContainerAdapter)adapter;
      }
    }

    return null;
  }

  public CDOURIHandler getURIHandler()
  {
    return uriHandler;
  }

  protected CDOBranchPoint getBranchPoint()
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return branchPoint;
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected CDOBranchPoint getNormalizedBranchPoint()
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return normalizedBranchPoint;
      }
      finally
      {
        unlockView();
      }
    }
  }

  public boolean setBranch(CDOBranch branch)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return setBranchPoint(branch, getTimeStamp(), null);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public boolean setBranch(CDOBranch branch, IProgressMonitor monitor)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return setBranchPoint(branch, getTimeStamp(), monitor);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public boolean setTimeStamp(long timeStamp)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return setBranchPoint(getBranch(), timeStamp, null);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public boolean setTimeStamp(long timeStamp, IProgressMonitor monitor)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return setBranchPoint(getBranch(), timeStamp, monitor);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public boolean setBranchPoint(CDOBranch branch, long timeStamp)
  {
    return setBranchPoint(branch, timeStamp, null);
  }

  public boolean setBranchPoint(CDOBranch branch, long timeStamp, IProgressMonitor monitor)
  {
    CDOBranchPoint branchPoint = branch.getPoint(timeStamp);
    return setBranchPoint(branchPoint, monitor);
  }

  public boolean setBranchPoint(CDOBranchPoint branchPoint)
  {
    return setBranchPoint(branchPoint, null);
  }

  protected CDOBranchPoint basicSetBranchPoint(CDOBranchPoint branchPoint)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        this.branchPoint = adjustBranchPoint(branchPoint);
        normalizedBranchPoint = CDOBranchUtil.normalizeBranchPoint(this.branchPoint);
        return this.branchPoint;
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected final CDOBranchPoint adjustBranchPoint(CDOBranchPoint branchPoint)
  {
    CDOSession session = getSession();
    if (session != null)
    {
      CDOBranchManager branchManager = session.getBranchManager();
      branchPoint = CDOBranchUtil.adjustBranchPoint(branchPoint, branchManager);
    }

    return CDOBranchUtil.copyBranchPoint(branchPoint);
  }

  public void waitForUpdate(long updateTime)
  {
    waitForUpdate(updateTime, NO_TIMEOUT);
  }

  public CDOBranch getBranch()
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return branchPoint.getBranch();
      }
      finally
      {
        unlockView();
      }
    }
  }

  public long getTimeStamp()
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return branchPoint.getTimeStamp();
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected void fireViewTargetChangedEvent(CDOBranchPoint oldBranchPoint, IListener[] listeners)
  {
    fireEvent(new ViewTargetChangedEvent(oldBranchPoint, branchPoint), listeners);
  }

  public boolean isDirty()
  {
    return false;
  }

  public boolean hasConflict()
  {
    return false;
  }

  public boolean hasResource(String path)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        checkActive();
        getResourceNodeID(path);
        return true;
      }
      catch (Exception ex)
      {
        return false;
      }
    }
  }

  public CDOQueryImpl createQuery(String language, String queryString)
  {
    return createQuery(language, queryString, null);
  }

  public CDOQueryImpl createQuery(String language, String queryString, Object context)
  {
    checkActive();
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return new CDOQueryImpl(this, language, queryString, context);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CDOResourceNode getResourceNode(String path)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOID id = getResourceNodeID(path);
        if (id != null) // Should always be true
        {
          InternalCDOObject object = getObject(id);
          if (object instanceof CDOResourceNode)
          {
            return (CDOResourceNode)object;
          }
        }

        throw new CDOException("Resource node not found: " + path);
      }
      finally
      {
        unlockView();
      }
    }
  }

  private CDOID getCachedResourceNodeID(String path)
  {
    if (resourcePathCache != null)
    {
      return resourcePathCache.get(path);
    }

    return null;
  }

  private void setCachedResourceNodeID(String path, CDOID id)
  {
    if (resourcePathCache != null)
    {
      if (id == null)
      {
        resourcePathCache.remove(path);
      }
      else
      {
        resourcePathCache.put(path, id);
      }
    }
  }

  public void setResourcePathCache(Map<String, CDOID> resourcePathCache)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        this.resourcePathCache = resourcePathCache;
      }
      finally
      {
        unlockView();
      }
    }
  }

  /**
   * If <code>delta == null</code> the cache is cleared unconditionally.
   * If <code>delta != null</code> the cache is cleared only if the delta can have an impact on the resource tree structure.
   */
  public void clearResourcePathCacheIfNecessary(CDORevisionDelta delta)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (resourcePathCache != null && !resourcePathCache.isEmpty())
        {
          if (delta == null)
          {
            resourcePathCache.clear();
          }
          else
          {
            if (canHaveResourcePathImpact(delta, rootResourceID))
            {
              resourcePathCache.clear();
            }
          }
        }
      }
      finally
      {
        unlockView();
      }
    }
  }

  /**
   * @return never <code>null</code>
   */
  public CDOID getResourceNodeID(String path)
  {
    if (StringUtil.isEmpty(path))
    {
      throw new IllegalArgumentException(Messages.getString("CDOViewImpl.1")); //$NON-NLS-1$
    }

    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOID id = getCachedResourceNodeID(path);
        if (id == null)
        {
          if (CDOURIUtil.SEGMENT_SEPARATOR.equals(path))
          {
            id = getResourceNodeIDChecked(null, null);
            setCachedResourceNodeID(path, id);
          }
          else
          {
            List<String> names = CDOURIUtil.analyzePath(path);
            path = "";

            for (String name : names)
            {
              path = path.length() == 0 ? name : path + "/" + name;

              CDOID cached = getCachedResourceNodeID(path);
              if (cached != null)
              {
                id = cached;
              }
              else
              {
                id = getResourceNodeIDChecked(id, name);
                setCachedResourceNodeID(path, id);
              }
            }
          }
        }

        return id;
      }
      finally
      {
        unlockView();
      }
    }
  }

  /**
   * @return never <code>null</code>
   */
  private CDOID getResourceNodeIDChecked(CDOID folderID, String name)
  {
    CDOID id = getResourceNodeID(folderID, name);
    if (id == null)
    {
      throw new CDOException(MessageFormat.format(Messages.getString("CDOViewImpl.2"), name)); //$NON-NLS-1$
    }

    return id;
  }

  /**
   * @return never <code>null</code>
   */
  protected CDOResourceNode getResourceNode(CDOID folderID, String name)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOID id = getResourceNodeID(folderID, name);
        return (CDOResourceNode)getObject(id);
      }
      catch (CDOException ex)
      {
        throw ex;
      }
      catch (Exception ex)
      {
        throw new CDOException(ex);
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected CDOID getResourceNodeID(CDOID folderID, String name)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (folderID == null)
        {
          return getRootOrTopLevelResourceNodeID(name);
        }

        if (name == null)
        {
          throw new IllegalArgumentException(Messages.getString("CDOViewImpl.3")); //$NON-NLS-1$
        }

        InternalCDORevision folderRevision = getLocalRevision(folderID);
        EClass resourceFolderClass = EresourcePackage.eINSTANCE.getCDOResourceFolder();
        if (folderRevision.getEClass() != resourceFolderClass)
        {
          throw new CDOException(MessageFormat.format(Messages.getString("CDOViewImpl.4"), folderID)); //$NON-NLS-1$
        }

        EReference nodesFeature = EresourcePackage.eINSTANCE.getCDOResourceFolder_Nodes();
        EAttribute nameFeature = EresourcePackage.eINSTANCE.getCDOResourceNode_Name();

        CDOList list;
        boolean bypassPermissionChecks = folderRevision.bypassPermissionChecks(true);

        try
        {
          list = folderRevision.getList(nodesFeature);
        }
        finally
        {
          folderRevision.bypassPermissionChecks(bypassPermissionChecks);
        }

        CDOStore store = getStore();
        int size = list.size();
        for (int i = 0; i < size; i++)
        {
          Object value = list.get(i);
          value = store.resolveProxy(folderRevision, nodesFeature, i, value);

          CDOID childID = (CDOID)convertObjectToID(value);
          InternalCDORevision childRevision = getLocalRevision(childID);
          String childName = (String)childRevision.get(nameFeature, 0);
          if (name.equals(childName))
          {
            return childID;
          }
        }

        throw new CDOException(MessageFormat.format(Messages.getString("CDOViewImpl.5"), name)); //$NON-NLS-1$
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected CDOID getRootOrTopLevelResourceNodeID(String name)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (name == null)
        {
          return rootResourceID;
        }

        CDOQuery resourceQuery = createResourcesQuery(null, name, true);
        resourceQuery.setMaxResults(1);
        List<CDOID> ids = resourceQuery.getResult(CDOID.class);
        if (ids.isEmpty())
        {
          throw new CDOException(MessageFormat.format(Messages.getString("CDOViewImpl.7"), name)); //$NON-NLS-1$
        }

        if (ids.size() > 1)
        {
          // TODO is this still needed since the is resourceQuery.setMaxResults(1) ??
          throw new ImplementationError(Messages.getString("CDOViewImpl.8")); //$NON-NLS-1$
        }

        return ids.get(0);
      }
      finally
      {
        unlockView();
      }
    }
  }

  private InternalCDORevision getLocalRevision(CDOID id)
  {
    InternalCDORevision revision = null;
    InternalCDOObject object = getObject(id, false);
    if (object != null && object.cdoState() != CDOState.PROXY)
    {
      revision = object.cdoRevision();
    }

    if (revision == null)
    {
      revision = getRevision(id, true);
    }

    if (revision == null)
    {
      throw new CDOException(MessageFormat.format(Messages.getString("CDOViewImpl.9"), id)); //$NON-NLS-1$
    }

    return revision;
  }

  public List<InternalCDOObject> getObjectsList()
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        List<InternalCDOObject> result = new ArrayList<InternalCDOObject>();
        for (InternalCDOObject value : objects.values())
        {
          if (value != null)
          {
            result.add(value);
          }
        }

        return result;
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CDOResource getResource(String path)
  {
    return getResource(path, true);
  }

  public CDOResource getResource(String path, boolean loadOnDemand)
  {
    checkActive();
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        URI uri = CDOURIUtil.createResourceURI(this, path);
        ResourceSet resourceSet = getResourceSet();
        ensureURIs(resourceSet); // Bug 337523

        try
        {
          return (CDOResource)resourceSet.getResource(uri, loadOnDemand);
        }
        catch (RuntimeException ex)
        {
          EList<Resource> resources = resourceSet.getResources();
          for (int i = resources.size() - 1; i >= 0; --i)
          {
            Resource resource = resources.get(i);
            if (uri.equals(resource.getURI()))
            {
              resources.remove(i);
              break;
            }
          }

          throw ex;
        }
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CDOTextResource getTextResource(String path)
  {
    return (CDOTextResource)getResourceNode(path);
  }

  public CDOBinaryResource getBinaryResource(String path)
  {
    return (CDOBinaryResource)getResourceNode(path);
  }

  public CDOResourceFolder getResourceFolder(String path)
  {
    return (CDOResourceFolder)getResourceNode(path);
  }

  /**
   * Ensures that the URIs of all resources in this resourceSet, can be fetched without triggering the loading of
   * additional resources. Without calling this first, it is dangerous to iterate over the resources to collect their
   * URI's, because
   */
  private void ensureURIs(ResourceSet resourceSet)
  {
    EList<Resource> resources = resourceSet.getResources();
    Resource[] resourceArr = null;

    int size = 0;
    int i;

    do
    {
      i = size;
      size = resources.size();
      if (size == 0)
      {
        break;
      }

      if (resourceArr == null || resourceArr.length < size)
      {
        resourceArr = new Resource[size * 2];
      }

      resourceArr = resources.toArray(resourceArr);
      for (; i < size; i++)
      {
        resourceArr[i].getURI();
      }
    } while (resources.size() > size);
  }

  public List<CDOResourceNode> queryResources(CDOResourceFolder folder, String name, boolean exactMatch)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOQuery resourceQuery = createResourcesQuery(folder, name, exactMatch);
        return resourceQuery.getResult(CDOResourceNode.class);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CloseableIterator<CDOResourceNode> queryResourcesAsync(CDOResourceFolder folder, String name,
      boolean exactMatch)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOQuery resourceQuery = createResourcesQuery(folder, name, exactMatch);
        return resourceQuery.getResultAsync(CDOResourceNode.class);
      }
      finally
      {
        unlockView();
      }
    }
  }

  private CDOQuery createResourcesQuery(CDOResourceFolder folder, String name, boolean exactMatch)
  {
    checkActive();
    CDOQueryImpl query = createQuery(CDOProtocolConstants.QUERY_LANGUAGE_RESOURCES, name);
    query.setParameter(CDOProtocolConstants.QUERY_LANGUAGE_RESOURCES_FOLDER_ID, folder == null ? null : folder.cdoID());
    query.setParameter(CDOProtocolConstants.QUERY_LANGUAGE_RESOURCES_EXACT_MATCH, exactMatch);
    return query;
  }

  public <T extends EObject> List<T> queryInstances(EClass type)
  {
    CDOQuery query = createInstancesQuery(type);
    return query.getResult();
  }

  public <T extends EObject> CloseableIterator<T> queryInstancesAsync(EClass type)
  {
    CDOQuery query = createInstancesQuery(type);
    return query.getResultAsync();
  }

  private CDOQuery createInstancesQuery(EClass type)
  {
    CDOQuery query = createQuery(CDOProtocolConstants.QUERY_LANGUAGE_INSTANCES, null);
    query.setParameter(CDOProtocolConstants.QUERY_LANGUAGE_INSTANCES_TYPE, type);
    return query;
  }

  public List<CDOObjectReference> queryXRefs(CDOObject targetObject, EReference... sourceReferences)
  {
    return queryXRefs(Collections.singleton(targetObject), sourceReferences);
  }

  public List<CDOObjectReference> queryXRefs(Set<CDOObject> targetObjects, EReference... sourceReferences)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOQuery xrefsQuery = createXRefsQuery(targetObjects, sourceReferences);
        return xrefsQuery.getResult(CDOObjectReference.class);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CloseableIterator<CDOObjectReference> queryXRefsAsync(Set<CDOObject> targetObjects,
      EReference... sourceReferences)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOQuery xrefsQuery = createXRefsQuery(targetObjects, sourceReferences);
        return xrefsQuery.getResultAsync(CDOObjectReference.class);
      }
      finally
      {
        unlockView();
      }
    }
  }

  private CDOQuery createXRefsQuery(Set<CDOObject> targetObjects, EReference... sourceReferences)
  {
    checkActive();

    String string = createXRefsQueryString(targetObjects);
    CDOQuery query = createQuery(CDOProtocolConstants.QUERY_LANGUAGE_XREFS, string);

    if (sourceReferences.length != 0)
    {
      string = createXRefsQueryParameter(sourceReferences);
      query.setParameter(CDOProtocolConstants.QUERY_LANGUAGE_XREFS_SOURCE_REFERENCES, string);
    }

    return query;
  }

  private String createXRefsQueryString(Set<CDOObject> targetObjects)
  {
    StringBuilder builder = new StringBuilder();
    for (CDOObject target : targetObjects)
    {
      CDOID id = getXRefTargetID(target);
      if (isObjectNew(id))
      {
        throw new IllegalArgumentException("Cross referencing for uncommitted new objects not supported " + target);
      }

      if (builder.length() != 0)
      {
        builder.append("|");
      }

      builder.append(id.isExternal() ? "e" : "i");
      builder.append(id.toURIFragment());

      if (!(id instanceof CDOClassifierRef.Provider))
      {
        builder.append("|");
        CDOClassifierRef classifierRef = new CDOClassifierRef(target.eClass());
        builder.append(classifierRef.getURI());
      }
    }

    return builder.toString();
  }

  private String createXRefsQueryParameter(EReference[] sourceReferences)
  {
    StringBuilder builder = new StringBuilder();
    for (EReference sourceReference : sourceReferences)
    {
      if (builder.length() != 0)
      {
        builder.append("|");
      }

      CDOClassifierRef classifierRef = new CDOClassifierRef(sourceReference.getEContainingClass());
      builder.append(classifierRef.getURI());
      builder.append("|");
      builder.append(sourceReference.getName());
    }

    return builder.toString();
  }

  protected CDOID getXRefTargetID(CDOObject target)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (FSMUtil.isTransient(target))
        {
          throw new IllegalArgumentException("Cross referencing for transient objects not supported " + target);
        }

        return target.cdoID();
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CDOResourceImpl getResource(CDOID resourceID)
  {
    if (CDOIDUtil.isNull(resourceID))
    {
      throw new IllegalArgumentException("resourceID: " + resourceID); //$NON-NLS-1$
    }

    return (CDOResourceImpl)getObject(resourceID);
  }

  public InternalCDOObject newInstance(EClass eClass)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        EObject eObject = EcoreUtil.create(eClass);
        return FSMUtil.adapt(eObject, this);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public InternalCDORevision getRevision(CDOID id)
  {
    return getRevision(id, true);
  }

  public InternalCDOObject getObject(CDOID id)
  {
    return getObject(id, true);
  }

  public InternalCDOObject getObject(CDOID id, boolean loadOnDemand)
  {
    checkActive();
    if (CDOIDUtil.isNull(id))
    {
      return null;
    }

    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (rootResource != null && rootResource.cdoID() == id)
        {
          return rootResource;
        }

        if (id == lastLookupID)
        {
          return lastLookupObject;
        }

        lastLookupID = null;
        lastLookupObject = null;
        InternalCDOObject localLookupObject = null;

        if (id.isExternal())
        {
          URI uri = URI.createURI(((CDOIDExternal)id).getURI());
          ResourceSet resourceSet = getResourceSet();

          localLookupObject = (InternalCDOObject)CDOUtil.getCDOObject(resourceSet.getEObject(uri, loadOnDemand));
          if (localLookupObject == null)
          {
            if (!loadOnDemand)
            {
              return null;
            }

            throw new ObjectNotFoundException(id, this);
          }
        }
        else
        {
          // Needed for recursive call to getObject. (from createObject/cleanObject/getResource/getObject)
          localLookupObject = objects.get(id);
          if (localLookupObject == null)
          {
            if (!loadOnDemand)
            {
              return null;
            }

            excludeNewObject(id);
            localLookupObject = createObject(id);

            if (id == rootResourceID)
            {
              setRootResource((CDOResourceImpl)localLookupObject);
            }
          }
        }

        lastLookupID = id;
        lastLookupObject = localLookupObject;
        return lastLookupObject;
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected void excludeNewObject(CDOID id)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (isObjectNew(id))
        {
          throw new ObjectNotFoundException(id, this);
        }
      }
      finally
      {
        unlockView();
      }
    }
  }

  public boolean isObjectNew(CDOID id)
  {
    return id.isTemporary();
  }

  /**
   * @since 2.0
   */
  public <T extends EObject> T getObject(T objectFromDifferentView)
  {
    checkActive();
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOObject object = CDOUtil.getCDOObject(objectFromDifferentView);
        CDOView view = object.cdoView();
        if (view == null)
        {
          return null;
        }

        if (view != this)
        {
          if (!view.getSession().getRepositoryInfo().getUUID().equals(getSession().getRepositoryInfo().getUUID()))
          {
            throw new IllegalArgumentException(
                MessageFormat.format(Messages.getString("CDOViewImpl.11"), objectFromDifferentView)); //$NON-NLS-1$
          }

          CDOID id = object.cdoID();
          InternalCDOObject contextified = getObject(id, true);

          if (objectFromDifferentView instanceof CDOLegacyAdapter)
          {
            @SuppressWarnings("unchecked")
            T cast = (T)contextified;
            return cast;
          }

          @SuppressWarnings("unchecked")
          T cast = (T)CDOUtil.getEObject(contextified);
          return cast;
        }

        return objectFromDifferentView;
      }
      finally
      {
        unlockView();
      }
    }
  }

  public boolean isObjectRegistered(CDOID id)
  {
    checkActive();
    if (CDOIDUtil.isNull(id))
    {
      return false;
    }

    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        return objects.containsKey(id);
      }
      finally
      {
        unlockView();
      }
    }
  }

  public InternalCDOObject removeObject(CDOID id)
  {
    if (id == null)
    {
      return null;
    }

    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (id == lastLookupID)
        {
          lastLookupID = null;
          lastLookupObject = null;
        }

        InternalCDOObject object = objects.remove(id);
        if (object != null)
        {
          objectDeregistered(object);
        }

        return object;
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected void objectDeregistered(InternalCDOObject object)
  {
    // Subclasses may override.
  }

  /**
   * @return Never <code>null</code>
   */
  private InternalCDOObject createObject(CDOID id)
  {
    if (TRACER.isEnabled())
    {
      TRACER.trace("Creating object for " + id); //$NON-NLS-1$
    }

    InternalCDORevision revision = getRevision(id, true);
    if (revision == null)
    {
      throw new ObjectNotFoundException(id, this);
    }

    EClass eClass = revision.getEClass();
    InternalCDOObject object;
    if (CDOModelUtil.isResource(eClass) && id != rootResourceID)
    {
      object = (InternalCDOObject)newResourceInstance(revision);
      // object is PROXY
    }
    else
    {
      object = newInstance(eClass);
      // object is TRANSIENT
    }

    cleanObject(object, revision);
    CDOStateMachine.INSTANCE.dispatchLoadNotification(object);

    // Bug 435198: Have object's resource added to the ResourceSet on call to CDOView.getObject(CDOID)
    if (!CDOModelUtil.isResource(eClass))
    {
      getStore().getResource(object);
    }

    return object;
  }

  private CDOResource newResourceInstance(InternalCDORevision revision)
  {
    String path = getResourcePath(revision);
    URI uri = CDOURIUtil.createResourceURI(this, path);

    // Bug 334995: Check if locally there is already a resource with the same URI
    ResourceSet resourceSet = getResourceSet();
    CDOResource resource1 = (CDOResource)resourceSet.getResource(uri, false);

    String oldName = null;
    if (resource1 != null && !isReadOnly())
    {
      // We have no other option than to change the name of the local resource
      oldName = resource1.getName();
      resource1.setName(oldName + ".renamed");
      OM.LOG.warn("URI clash: resource being instantiated had same URI as a resource already present "
          + "locally; local resource was renamed from " + oldName + " to " + resource1.getName());
    }

    CDOResource resource2 = getResource(path, true);
    return resource2;
  }

  private String getResourcePath(InternalCDORevision revision)
  {
    CDORevisionData data = revision.data();
    CDOID folderID;

    Object containerID = data.getContainerID();
    if (containerID instanceof CDOWithID)
    {
      folderID = ((CDOWithID)containerID).cdoID();
    }
    else
    {
      folderID = (CDOID)containerID;
    }

    String name = (String)revision.data().get(EresourcePackage.Literals.CDO_RESOURCE_NODE__NAME, 0);
    if (CDOIDUtil.isNull(folderID))
    {
      if (name == null)
      {
        return CDOURIUtil.SEGMENT_SEPARATOR;
      }

      return name;
    }

    InternalCDOObject object = getObject(folderID, true);
    if (object instanceof CDOResourceFolder)
    {
      CDOResourceFolder folder = (CDOResourceFolder)object;
      String path = folder.getPath();
      return path + CDOURIUtil.SEGMENT_SEPARATOR + name;
    }

    throw new ImplementationError(MessageFormat.format(Messages.getString("CDOViewImpl.14"), object)); //$NON-NLS-1$
  }

  /**
   * @since 2.0
   */
  protected void cleanObject(InternalCDOObject object, InternalCDORevision revision)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        object.cdoInternalSetView(this);
        object.cdoInternalSetRevision(revision);

        // Before setting the state to CLEAN (that can trigger a duplicate loading and instantiation of the current
        // object)
        // we make sure that object is registered - without throwing exception if it is already the case
        registerObjectIfNotRegistered(object);

        object.cdoInternalSetState(CDOState.CLEAN);
        object.cdoInternalPostLoad();
      }
      finally
      {
        unlockView();
      }
    }
  }

  public CDOID provideCDOID(Object idOrObject)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        Object shouldBeCDOID = convertObjectToID(idOrObject);
        if (shouldBeCDOID instanceof CDOID)
        {
          CDOID id = (CDOID)shouldBeCDOID;
          if (TRACER.isEnabled() && id != idOrObject)
          {
            TRACER.format("Converted object to CDOID: {0} --> {1}", idOrObject, id); //$NON-NLS-1$
          }

          return id;
        }

        if (idOrObject instanceof InternalEObject)
        {
          InternalEObject eObject = (InternalEObject)idOrObject;
          if (eObject instanceof InternalCDOObject)
          {
            InternalCDOObject object = (InternalCDOObject)idOrObject;
            if (object.cdoView() != null && FSMUtil.isNew(object))
            {
              String uri = EcoreUtil.getURI(object.cdoInternalInstance()).toString();
              if (object.cdoID().isTemporary())
              {
                return CDOIDUtil.createTempObjectExternal(uri);
              }
            }
          }

          Resource eResource = eObject.eResource();
          if (eResource != null)
          {
            // Check if eObject is contained by a deleted resource
            if (!(eResource instanceof CDOResource) || ((CDOResource)eResource).cdoState() != CDOState.TRANSIENT)
            {
              String uri = EcoreUtil.getURI(CDOUtil.getEObject(eObject)).toString();
              return CDOIDUtil.createExternal(uri);
            }
          }

          throw new DanglingReferenceException(eObject);
        }

        throw new IllegalStateException(MessageFormat.format(Messages.getString("CDOViewImpl.16"), idOrObject)); //$NON-NLS-1$
      }
      finally
      {
        unlockView();
      }
    }
  }

  public Object convertObjectToID(Object potentialObject)
  {
    return convertObjectToID(potentialObject, false);
  }

  /**
   * @since 2.0
   */
  public Object convertObjectToID(Object potentialObject, boolean onlyPersistedID)
  {
    if (potentialObject instanceof CDOID)
    {
      return potentialObject;
    }

    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (potentialObject instanceof InternalEObject)
        {
          if (potentialObject instanceof InternalCDOObject)
          {
            InternalCDOObject object = (InternalCDOObject)potentialObject;
            CDOID id = getID(object, onlyPersistedID);
            if (id != null)
            {
              return id;
            }
          }
          else
          {
            InternalCDOObject object = (InternalCDOObject)EcoreUtil
                .getAdapter(((InternalEObject)potentialObject).eAdapters(), CDOLegacyAdapter.class);
            if (object != null)
            {
              CDOID id = getID(object, onlyPersistedID);
              if (id != null)
              {
                return id;
              }

              potentialObject = object;
            }
          }
        }

        return potentialObject;
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected CDOID getID(InternalCDOObject object, boolean onlyPersistedID)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (onlyPersistedID)
        {
          if (FSMUtil.isTransient(object) || FSMUtil.isNew(object))
          {
            return null;
          }
        }

        CDOView view = object.cdoView();
        if (view == this)
        {
          return object.cdoID();
        }

        if (view != null && view.getSession() == getSession())
        {
          boolean sameTarget = view.getBranch() == getBranch() && view.getTimeStamp() == getTimeStamp();
          if (sameTarget)
          {
            return object.cdoID();
          }

          throw new IllegalArgumentException(
              "Object " + object + " is managed by a view with different target: " + view);
        }

        return null;
      }
      finally
      {
        unlockView();
      }
    }
  }

  public Object convertIDToObject(Object potentialID)
  {
    if (potentialID instanceof CDOID)
    {
      if (potentialID == CDOID.NULL)
      {
        return null;
      }

      synchronized (getViewMonitor())
      {
        lockView();

        try
        {
          CDOID id = (CDOID)potentialID;
          if (id.isExternal())
          {
            return getResourceSet().getEObject(URI.createURI(id.toURIFragment()), true);
          }

          InternalCDOObject result = getObject(id, true);
          if (result == null)
          {
            throw new ImplementationError(MessageFormat.format(Messages.getString("CDOViewImpl.17"), id)); //$NON-NLS-1$
          }

          return result.cdoInternalInstance();
        }
        finally
        {
          unlockView();
        }
      }
    }

    return potentialID;
  }

  /**
   * @since 2.0
   */
  public void attachResource(CDOResourceImpl resource)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (!resource.isExisting())
        {
          throw new ReadOnlyException(MessageFormat.format(Messages.getString("CDOViewImpl.18"), this)); //$NON-NLS-1$
        }

        // ResourceSet.getResource(uri, true) was called!!
        resource.cdoInternalSetView(this);
        resource.cdoInternalSetState(CDOState.PROXY);
        registerProxyResource2(resource);
      }
      finally
      {
        unlockView();
      }
    }
  }

  private void registerProxyResource2(CDOResourceImpl resource)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        URI uri = resource.getURI();
        String path = CDOURIUtil.extractResourcePath(uri);
        boolean isRoot = "/".equals(path); //$NON-NLS-1$

        try
        {
          CDOID id;
          if (isRoot)
          {
            id = rootResourceID;
          }
          else
          {
            id = getResourceNodeID(path);
          }

          resource.cdoInternalSetID(id);
          registerObject(resource);
          if (isRoot)
          {
            resource.setRoot(true);
            rootResource = resource;
          }
        }
        catch (LifecycleException ex)
        {
          throw ex;
        }
        catch (Exception ex)
        {
          throw new InvalidURIException(uri, ex);
        }
      }
      finally
      {
        unlockView();
      }
    }
  }

  /**
   * @deprecated No longer supported.
   */
  @Deprecated
  public void registerProxyResource(CDOResourceImpl resource)
  {
    registerProxyResource2(resource);
  }

  /**
   * Does the same as {@link AbstractCDOView#registerObject(InternalCDOObject)}, but without
   * throwing any exception if object is already registered (in that case it will simply do nothing).
   *
   * @param object the object to register
   */
  private void registerObjectIfNotRegistered(InternalCDOObject object)
  {
    if (CDOModelUtil.isResource(object.eClass()))
    {
      return;
    }

    if (objects.containsKey(object.cdoID()))
    {
      return;
    }

    registerObject(object);
  }

  public void registerObject(InternalCDOObject object)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (TRACER.isEnabled())
        {
          TRACER.format("Registering {0}", object); //$NON-NLS-1$
        }

        InternalCDOObject old = objects.put(object.cdoID(), object);
        if (old != null)
        {
          if (old != object)
          {
            throw new IllegalStateException(MessageFormat.format(Messages.getString("CDOViewImpl.30"), object.cdoID())); //$NON-NLS-1$
          }

          if (TRACER.isEnabled())
          {
            TRACER.format(Messages.getString("CDOViewImpl.20"), old); //$NON-NLS-1$
          }
        }

        objectRegistered(object);
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected void objectRegistered(InternalCDOObject object)
  {
    // Subclasses may override.
  }

  public void deregisterObject(InternalCDOObject object)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        if (TRACER.isEnabled())
        {
          TRACER.format("Deregistering {0}", object); //$NON-NLS-1$
        }

        removeObject(object.cdoID());
      }
      finally
      {
        unlockView();
      }
    }
  }

  public void remapObject(CDOID oldID)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOID newID;
        InternalCDOObject object = objects.remove(oldID);
        newID = object.cdoID();

        objects.put(newID, object);

        if (lastLookupID == oldID)
        {
          lastLookupID = null;
          lastLookupObject = null;
        }

        if (TRACER.isEnabled())
        {
          TRACER.format("Remapping {0} --> {1}", oldID, newID); //$NON-NLS-1$
        }
      }
      finally
      {
        unlockView();
      }
    }
  }

  public void addObjectHandler(CDOObjectHandler handler)
  {
    objectHandlers.add(handler);
  }

  public void removeObjectHandler(CDOObjectHandler handler)
  {
    objectHandlers.remove(handler);
  }

  public CDOObjectHandler[] getObjectHandlers()
  {
    return objectHandlers.get();
  }

  public void handleObjectStateChanged(InternalCDOObject object, CDOState oldState, CDOState newState)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOObjectHandler[] handlers = getObjectHandlers();
        for (int i = 0; i < handlers.length; i++)
        {
          CDOObjectHandler handler = handlers[i];
          handler.objectStateChanged(this, object, oldState, newState);
        }
      }
      finally
      {
        unlockView();
      }
    }
  }

  /*
   * Synchronized through InvalidationRunner.run()
   */
  protected Map<CDOObject, Pair<CDORevision, CDORevisionDelta>> invalidate(List<CDORevisionKey> allChangedObjects,
      List<CDOIDAndVersion> allDetachedObjects, List<CDORevisionDelta> deltas,
      Map<CDOObject, CDORevisionDelta> revisionDeltas, Set<CDOObject> detachedObjects)
  {
    boolean hasConflictResolvers = this instanceof CDOTransaction
        && ((CDOTransaction)this).options().getConflictResolvers().length != 0;
    Map<CDOObject, Pair<CDORevision, CDORevisionDelta>> conflicts = null;

    // Bug 363355: manage detached objects before changed objects to avoid issue on eContainer
    for (CDOIDAndVersion key : allDetachedObjects)
    {
      InternalCDOObject detachedObject = removeObject(key.getID());
      if (detachedObject != null)
      {
        Pair<CDORevision, CDORevisionDelta> oldInfo = Pair.create((CDORevision)detachedObject.cdoRevision(),
            CDORevisionDelta.DETACHED);
        // if (!isLocked(detachedObject))
        {
          CDOStateMachine.INSTANCE.detachRemote(detachedObject);
        }

        detachedObjects.add(detachedObject);
        if (detachedObject.cdoConflict())
        {
          if (conflicts == null)
          {
            conflicts = new HashMap<CDOObject, Pair<CDORevision, CDORevisionDelta>>();
          }

          conflicts.put(detachedObject, oldInfo);
        }
      }
    }

    for (CDORevisionKey key : allChangedObjects)
    {
      CDORevisionDelta delta = null;
      if (key instanceof CDORevisionDelta)
      {
        delta = (CDORevisionDelta)key;
        // Copy the revision delta so that conflict resolvers can modify it.
        if (hasConflictResolvers)
        {
          delta = new CDORevisionDeltaImpl(delta, true);
        }

        deltas.add(delta);
      }

      CDOObject changedObject = objects.get(key.getID());
      if (changedObject != null)
      {
        Pair<CDORevision, CDORevisionDelta> oldInfo = Pair.create(changedObject.cdoRevision(), delta);
        // if (!isLocked(changedObject))
        {
          CDOStateMachine.INSTANCE.invalidate((InternalCDOObject)changedObject, key);
        }

        if (changedObject instanceof CDOResourceNodeImpl)
        {
          if (delta == null || isResourceNodeContainerOrNameChanged(delta))
          {
            ((CDOResourceNodeImpl)changedObject).recacheURIs();
          }
        }

        revisionDeltas.put(changedObject, delta);
        if (changedObject.cdoConflict())
        {
          if (conflicts == null)
          {
            conflicts = new HashMap<CDOObject, Pair<CDORevision, CDORevisionDelta>>();
          }

          conflicts.put(changedObject, oldInfo);
        }
      }
    }

    return conflicts;
  }

  private boolean isResourceNodeContainerOrNameChanged(CDORevisionDelta delta)
  {
    if (delta.getFeatureDelta(EresourcePackage.Literals.CDO_RESOURCE_NODE__NAME) != null)
    {
      return true;
    }

    if (delta.getFeatureDelta(CDOContainerFeatureDelta.CONTAINER_FEATURE) != null)
    {
      return true;
    }

    return false;
  }

  /**
   * Overridden by {@link CDOTransactionImpl#handleConflicts(long, Map, List)}.
   */
  protected void handleConflicts(long lastUpdateTime, Map<CDOObject, Pair<CDORevision, CDORevisionDelta>> conflicts,
      List<CDORevisionDelta> deltas)
  {
    // Do nothing
  }

  public void fireAdaptersNotifiedEvent(long timeStamp)
  {
    fireEvent(new AdaptersNotifiedEvent(timeStamp));
  }

  /**
   * TODO For this method to be useable locks must be cached locally!
   */
  @SuppressWarnings("unused")
  private boolean isLocked(InternalCDOObject object)
  {
    if (object.cdoWriteLock().isLocked())
    {
      return true;
    }

    if (object.cdoReadLock().isLocked())
    {
      return true;
    }

    return false;
  }

  @Deprecated
  public int reload(CDOObject... objects)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        Collection<InternalCDOObject> internalObjects;
        if (objects != null && objects.length != 0)
        {
          internalObjects = new ArrayList<InternalCDOObject>(objects.length);
          for (CDOObject object : objects)
          {
            if (object instanceof InternalCDOObject)
            {
              internalObjects.add((InternalCDOObject)object);
            }
          }
        }
        else
        {
          internalObjects = new ArrayList<InternalCDOObject>(this.objects.values());
        }

        int result = internalObjects.size();
        if (result != 0)
        {
          CDOStateMachine.INSTANCE.reload(internalObjects.toArray(new InternalCDOObject[result]));
        }

        return result;
      }
      finally
      {
        unlockView();
      }
    }
  }

  public void close()
  {
    LifecycleUtil.deactivate(this, OMLogger.Level.DEBUG);
  }

  /**
   * @since 2.0
   */
  public boolean isClosed()
  {
    return !isActive();
  }

  @SuppressWarnings({ "unchecked", "rawtypes" })
  public Object getAdapter(Class adapter)
  {
    return AdapterUtil.adapt(this, adapter, false);
  }

  @Override
  public String toString()
  {
    if (!isActive())
    {
      return super.toString();
    }

    StringBuilder builder = new StringBuilder();
    if (isReadOnly())
    {
      builder.append("View");
    }
    else
    {
      builder.append("Transaction");
    }

    builder.append(" "); //$NON-NLS-1$
    builder.append(getViewID());

    if (branchPoint != null)
    {
      boolean brackets = false;
      if (getSession().getRepositoryInfo().isSupportingBranches())
      {
        brackets = true;
        builder.append(" ["); //$NON-NLS-1$
        builder.append(branchPoint.getBranch().getPathName()); // Do not synchronize on this view!
      }

      long timeStamp = branchPoint.getTimeStamp(); // Do not synchronize on this view!
      if (timeStamp != CDOView.UNSPECIFIED_DATE)
      {
        if (brackets)
        {
          builder.append(", "); //$NON-NLS-1$
        }
        else
        {
          builder.append(" ["); //$NON-NLS-1$
          brackets = true;
        }

        builder.append(CDOCommonUtil.formatTimeStamp(timeStamp));
      }

      if (brackets)
      {
        builder.append("]"); //$NON-NLS-1$
      }
    }

    return builder.toString();
  }

  protected String getClassName()
  {
    return "CDOView"; //$NON-NLS-1$
  }

  public boolean isAdapterForType(Object type)
  {
    return type instanceof ResourceSet;
  }

  public org.eclipse.emf.common.notify.Notifier getTarget()
  {
    return getResourceSet();
  }

  public void collectViewedRevisions(Map<CDOID, InternalCDORevision> revisions)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        for (InternalCDOObject object : objects.values())
        {
          CDOState state = object.cdoState();
          if (state != CDOState.CLEAN && state != CDOState.DIRTY && state != CDOState.CONFLICT)
          {
            continue;
          }

          CDOID id = object.cdoID();
          if (revisions.containsKey(id))
          {
            continue;
          }

          InternalCDORevision revision = getViewedRevision(object);
          if (revision == null)
          {
            continue;
          }

          revisions.put(id, revision);
        }
      }
      finally
      {
        unlockView();
      }
    }
  }

  protected InternalCDORevision getViewedRevision(InternalCDOObject object)
  {
    return CDOStateMachine.INSTANCE.readNoLoad(object);
  }

  public CDOChangeSetData compareRevisions(CDOBranchPoint source)
  {
    synchronized (getViewMonitor())
    {
      lockView();

      try
      {
        CDOSession session = getSession();
        return session.compareRevisions(source, this);
      }
      finally
      {
        unlockView();
      }
    }
  }

  @Override
  public CDOCommitHistory getHistory()
  {
    CDOBranch branch = getBranch();
    CDOCommitInfoManager commitInfoManager = getSession().getCommitInfoManager();
    return commitInfoManager.getHistory(branch);
  }

  @Override
  protected CDOCommitHistory createHistory(CDOObject key)
  {
    return new CDOObjectHistoryImpl(key);
  }

  @Override
  protected void doActivate() throws Exception
  {
    super.doActivate();

    LifecycleUtil.activate(viewLock);

    if (branchPoint != null)
    {
      basicSetBranchPoint(branchPoint);
    }
  }

  @Override
  protected void doDeactivate() throws Exception
  {
    if (viewSet != null && viewSet.getResourceSet() != null)
    {
      viewSet.getResourceSet().getURIConverter().getURIHandlers().remove(getURIHandler());
    }

    LifecycleUtil.deactivate(viewLock);

    viewSet = null;
    objects = null;
    store = null;
    resourcePathCache = null;
    lastLookupID = null;
    lastLookupObject = null;
    super.doDeactivate();
  }

  public static void setNextViewLock(Lock viewLock)
  {
    if (viewLock != null)
    {
      NEXT_VIEW_LOCK.set(viewLock);
    }
    else
    {
      NEXT_VIEW_LOCK.remove();
    }
  }

  public static boolean canHaveResourcePathImpact(CDORevisionDelta delta, CDOID rootResourceID)
  {
    EClass eClass = delta.getEClass();
    if (EresourcePackage.Literals.CDO_RESOURCE_NODE.isSuperTypeOf(eClass))
    {
      if (delta.getFeatureDelta(EresourcePackage.Literals.CDO_RESOURCE_NODE__NAME) != null)
      {
        return true;
      }
    }

    if (eClass == EresourcePackage.Literals.CDO_RESOURCE_FOLDER)
    {
      CDOListFeatureDelta featureDelta = (CDOListFeatureDelta)delta
          .getFeatureDelta(EresourcePackage.Literals.CDO_RESOURCE_FOLDER__NODES);
      if (canHaveResourcePathImpact(featureDelta))
      {
        return true;
      }
    }

    if (eClass == EresourcePackage.Literals.CDO_RESOURCE)
    {
      if (rootResourceID == delta.getID())
      {
        CDOListFeatureDelta featureDelta = (CDOListFeatureDelta)delta
            .getFeatureDelta(EresourcePackage.Literals.CDO_RESOURCE__CONTENTS);
        if (canHaveResourcePathImpact(featureDelta))
        {
          return true;
        }
      }
    }

    return false;
  }

  private static boolean canHaveResourcePathImpact(CDOListFeatureDelta featureDelta)
  {
    if (featureDelta != null)
    {
      for (CDOFeatureDelta listChange : featureDelta.getListChanges())
      {
        CDOFeatureDelta.Type type = listChange.getType();
        switch (type)
        {
        case REMOVE:
        case CLEAR:
        case SET:
        case UNSET:
          return true;
        }
      }
    }

    return false;
  }

  /**
   * @author Eike Stepper
   */
  protected abstract class Event extends org.eclipse.net4j.util.event.Event implements CDOViewEvent
  {
    private static final long serialVersionUID = 1L;

    public Event()
    {
      super(AbstractCDOView.this);
    }

    @Override
    public AbstractCDOView getSource()
    {
      return (AbstractCDOView)super.getSource();
    }
  }

  /**
   * @author Eike Stepper
   */
  private final class AdaptersNotifiedEvent extends Event implements CDOViewAdaptersNotifiedEvent
  {
    private static final long serialVersionUID = 1L;

    private long timeStamp;

    public AdaptersNotifiedEvent(long timeStamp)
    {
      this.timeStamp = timeStamp;
    }

    public long getTimeStamp()
    {
      return timeStamp;
    }

    @Override
    public String toString()
    {
      return "CDOViewAdaptersNotifiedEvent: " + timeStamp; //$NON-NLS-1$
    }
  }

  /**
   * @author Victor Roldan Betancort
   */
  private final class ViewTargetChangedEvent extends Event implements CDOViewTargetChangedEvent
  {
    private static final long serialVersionUID = 1L;

    private final CDOBranchPoint oldBranchPoint;

    private final CDOBranchPoint branchPoint;

    public ViewTargetChangedEvent(CDOBranchPoint oldBranchPoint, CDOBranchPoint branchPoint)
    {
      this.oldBranchPoint = CDOBranchUtil.copyBranchPoint(oldBranchPoint);
      this.branchPoint = CDOBranchUtil.copyBranchPoint(branchPoint);
    }

    @Override
    public String toString()
    {
      return MessageFormat.format("CDOViewTargetChangedEvent: {0}", branchPoint); //$NON-NLS-1$
    }

    public CDOBranchPoint getOldBranchPoint()
    {
      return oldBranchPoint;
    }

    public CDOBranchPoint getBranchPoint()
    {
      return branchPoint;
    }
  }

  /**
   * @author Eike Stepper
   */
  private final class ContainerAdapter extends AdapterImpl
  {
    public AbstractCDOView getView()
    {
      return AbstractCDOView.this;
    }

    @Override
    public void notifyChanged(Notification msg)
    {
      if (msg.isTouch())
      {
        return;
      }

      if (msg.getFeature() != EresourcePackage.Literals.CDO_RESOURCE__CONTENTS)
      {
        return;
      }

      IListener[] listeners = getListeners();
      if (listeners.length == 0)
      {
        return;
      }

      IContainerEvent<CDOResourceNode> event = null;
      int eventType = msg.getEventType();
      switch (eventType)
      {
      case Notification.ADD:
        event = new SingleDeltaContainerEvent<CDOResourceNode>(AbstractCDOView.this, (CDOResourceNode)msg.getNewValue(),
            IContainerDelta.Kind.ADDED);
        break;

      case Notification.ADD_MANY:
        // TODO
        break;

      case Notification.REMOVE:
        event = new SingleDeltaContainerEvent<CDOResourceNode>(AbstractCDOView.this, (CDOResourceNode)msg.getOldValue(),
            IContainerDelta.Kind.REMOVED);
        break;

      case Notification.REMOVE_MANY:
        // TODO
        break;

      case Notification.UNSET:
        // TODO
        break;

      default:
        break;
      }

      if (event != null)
      {
        fireEvent(event, listeners);
      }
    }
  }

  /**
   * For better debugging.
   *
   * @author Eike Stepper
   */
  private static final class NOOPMonitor
  {
  }
}

Back to the top