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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <cstdio>

#include <com/sun/star/beans/IllegalTypeException.hpp>
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <com/sun/star/document/CmisProperty.hpp>
#include <com/sun/star/io/XActiveDataSink.hpp>
#include <com/sun/star/io/XActiveDataStreamer.hpp>
#include <com/sun/star/lang/IllegalAccessException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
#include <com/sun/star/task/InteractionClassification.hpp>
#include <com/sun/star/ucb/ContentInfo.hpp>
#include <com/sun/star/ucb/ContentInfoAttribute.hpp>
#include <com/sun/star/ucb/InsertCommandArgument2.hpp>
#include <com/sun/star/ucb/InteractiveBadTransferURLException.hpp>
#include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp>
#include <com/sun/star/ucb/MissingInputStreamException.hpp>
#include <com/sun/star/ucb/OpenMode.hpp>
#include <com/sun/star/ucb/UnsupportedCommandException.hpp>
#include <com/sun/star/ucb/UnsupportedDataSinkException.hpp>
#include <com/sun/star/ucb/UnsupportedOpenModeException.hpp>
#include <com/sun/star/ucb/XCommandInfo.hpp>
#include <com/sun/star/ucb/XDynamicResultSet.hpp>
#ifndef SYSTEM_CURL
#include <com/sun/star/xml/crypto/XDigestContext.hpp>
#include <com/sun/star/xml/crypto/DigestID.hpp>
#include <com/sun/star/xml/crypto/NSSInitializer.hpp>
#endif

#include <comphelper/processfactory.hxx>
#include <comphelper/sequence.hxx>
#include <cppuhelper/exc_hlp.hxx>
#include <cppuhelper/queryinterface.hxx>
#include <config_oauth2.h>
#include <o3tl/runtimetooustring.hxx>
#include <sal/log.hxx>
#include <tools/urlobj.hxx>
#include <ucbhelper/cancelcommandexecution.hxx>
#include <ucbhelper/content.hxx>
#include <ucbhelper/contentidentifier.hxx>
#include <ucbhelper/propertyvalueset.hxx>
#include <ucbhelper/proxydecider.hxx>
#include <ucbhelper/macros.hxx>
#include <sax/tools/converter.hxx>

#include "auth_provider.hxx"
#include "certvalidation_handler.hxx"
#include "cmis_content.hxx"
#include "cmis_provider.hxx"
#include "cmis_resultset.hxx"
#include "cmis_strings.hxx"
#include "std_inputstream.hxx"
#include "std_outputstream.hxx"

#define OUSTR_TO_STDSTR(s) string( OUStringToOString( s, RTL_TEXTENCODING_UTF8 ).getStr() )
#define STD_TO_OUSTR( str ) OUString( str.c_str(), str.length( ), RTL_TEXTENCODING_UTF8 )

using namespace com::sun::star;
using namespace std;

namespace
{
    util::DateTime lcl_boostToUnoTime(const boost::posix_time::ptime& boostTime)
    {
        util::DateTime unoTime;
        unoTime.Year = boostTime.date().year();
        unoTime.Month = boostTime.date().month();
        unoTime.Day = boostTime.date().day();
        unoTime.Hours = boostTime.time_of_day().hours();
        unoTime.Minutes = boostTime.time_of_day().minutes();
        unoTime.Seconds = boostTime.time_of_day().seconds();

        // TODO FIXME maybe we should compile with BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG
        //            to actually get nanosecond precision in boostTime?
        // use this way rather than total_nanos to avoid overflows with 32-bit long
        const long ticks = boostTime.time_of_day().fractional_seconds();
        long nanoSeconds = ticks * ( 1000000000 / boost::posix_time::time_duration::ticks_per_second());

        unoTime.NanoSeconds = nanoSeconds;

        return unoTime;
    }

    uno::Any lcl_cmisPropertyToUno( const libcmis::PropertyPtr& pProperty )
    {
        uno::Any aValue;
        switch ( pProperty->getPropertyType( )->getType( ) )
        {
            default:
            case libcmis::PropertyType::String:
                {
                    vector< string > aCmisStrings = pProperty->getStrings( );
                    uno::Sequence< OUString > aStrings( aCmisStrings.size( ) );
                    OUString* aStringsArr = aStrings.getArray( );
                    sal_Int32 i = 0;
                    for ( const auto& rCmisStr : aCmisStrings )
                    {
                        aStringsArr[i++] = STD_TO_OUSTR( rCmisStr );
                    }
                    aValue <<= aStrings;
                }
                break;
            case libcmis::PropertyType::Integer:
                {
                    vector< long > aCmisLongs = pProperty->getLongs( );
                    uno::Sequence< sal_Int64 > aLongs( aCmisLongs.size( ) );
                    sal_Int64* aLongsArr = aLongs.getArray( );
                    sal_Int32 i = 0;
                    for ( const auto& rCmisLong : aCmisLongs )
                    {
                        aLongsArr[i++] = rCmisLong;
                    }
                    aValue <<= aLongs;
                }
                break;
            case libcmis::PropertyType::Decimal:
                {
                    vector< double > aCmisDoubles = pProperty->getDoubles( );
                    uno::Sequence< double > aDoubles = comphelper::containerToSequence(aCmisDoubles);
                    aValue <<= aDoubles;
                }
                break;
            case libcmis::PropertyType::Bool:
                {
                    vector< bool > aCmisBools = pProperty->getBools( );
                    uno::Sequence< sal_Bool > aBools( aCmisBools.size( ) );
                    sal_Bool* aBoolsArr = aBools.getArray( );
                    sal_Int32 i = 0;
                    for ( bool bCmisBool : aCmisBools )
                    {
                        aBoolsArr[i++] = bCmisBool;
                    }
                    aValue <<= aBools;
                }
                break;
            case libcmis::PropertyType::DateTime:
                {
                    vector< boost::posix_time::ptime > aCmisTimes = pProperty->getDateTimes( );
                    uno::Sequence< util::DateTime > aTimes( aCmisTimes.size( ) );
                    util::DateTime* aTimesArr = aTimes.getArray( );
                    sal_Int32 i = 0;
                    for ( const auto& rCmisTime : aCmisTimes )
                    {
                        aTimesArr[i++] = lcl_boostToUnoTime( rCmisTime );
                    }
                    aValue <<= aTimes;
                }
                break;
        }
        return aValue;
    }

    libcmis::PropertyPtr lcl_unoToCmisProperty(const document::CmisProperty& prop )
    {
        libcmis::PropertyTypePtr propertyType( new libcmis::PropertyType( ) );

        OUString id = prop.Id;
        OUString name = prop.Name;
        bool bUpdatable = prop.Updatable;
        bool bRequired = prop.Required;
        bool bMultiValued = prop.MultiValued;
        bool bOpenChoice = prop.OpenChoice;
        uno::Any value = prop.Value;<--- Variable 'value' is assigned a value that is never used.
        std::vector< std::string > values;

        libcmis::PropertyType::Type type = libcmis::PropertyType::String;
        if ( prop.Type == CMIS_TYPE_STRING )
        {
            uno::Sequence< OUString > seqValue;
            value >>= seqValue;<--- Variable 'value' is assigned a value that is never used.
            std::transform(seqValue.begin(), seqValue.end(), std::back_inserter(values),
                [](const OUString& rValue) -> std::string { return OUSTR_TO_STDSTR( rValue ); });
            type = libcmis::PropertyType::String;
        }
        else if ( prop.Type == CMIS_TYPE_BOOL )
        {
            uno::Sequence< sal_Bool > seqValue;
            value >>= seqValue;
            std::transform(seqValue.begin(), seqValue.end(), std::back_inserter(values),
                [](const bool nValue) -> std::string { return OUSTR_TO_STDSTR( OUString::boolean( nValue ) ); });
            type = libcmis::PropertyType::Bool;
        }
        else if ( prop.Type == CMIS_TYPE_INTEGER )
        {
            uno::Sequence< sal_Int64 > seqValue;
            value >>= seqValue;
            std::transform(seqValue.begin(), seqValue.end(), std::back_inserter(values),
                [](const sal_Int64 nValue) -> std::string { return OUSTR_TO_STDSTR( OUString::number( nValue ) ); });
            type = libcmis::PropertyType::Integer;
        }
        else if ( prop.Type == CMIS_TYPE_DECIMAL )
        {
            uno::Sequence< double > seqValue;
            value >>= seqValue;
            std::transform(seqValue.begin(), seqValue.end(), std::back_inserter(values),
                [](const double fValue) -> std::string { return OUSTR_TO_STDSTR( OUString::number( fValue ) ); });
            type = libcmis::PropertyType::Decimal;
        }
        else if ( prop.Type == CMIS_TYPE_DATETIME )
        {
            uno::Sequence< util::DateTime > seqValue;
            value >>= seqValue;
            std::transform(seqValue.begin(), seqValue.end(), std::back_inserter(values),
                [](const util::DateTime& rValue) -> std::string {
                    OUStringBuffer aBuffer;
                    ::sax::Converter::convertDateTime( aBuffer, rValue, nullptr );
                    return OUSTR_TO_STDSTR( aBuffer.makeStringAndClear( ) );
                });
            type = libcmis::PropertyType::DateTime;
        }

        propertyType->setId( OUSTR_TO_STDSTR( id ));
        propertyType->setDisplayName( OUSTR_TO_STDSTR( name ) );
        propertyType->setUpdatable( bUpdatable );
        propertyType->setRequired( bRequired );
        propertyType->setMultiValued( bMultiValued );
        propertyType->setOpenChoice( bOpenChoice );
        propertyType->setType( type );

        libcmis::PropertyPtr property( new libcmis::Property( propertyType, values ) );

        return property;
    }

    uno::Sequence< uno::Any > generateErrorArguments( const cmis::URL & rURL )
    {
        uno::Sequence< uno::Any > aArguments(3);

        size_t i = 0;
        aArguments[i++] <<= beans::PropertyValue(
            "Binding URL",
            - 1,
            uno::makeAny( rURL.getBindingUrl() ),
            beans::PropertyState_DIRECT_VALUE );

        aArguments[i++] <<= beans::PropertyValue(
            "Username",
            -1,
            uno::makeAny( rURL.getUsername() ),
            beans::PropertyState_DIRECT_VALUE );

        aArguments[i++] <<= beans::PropertyValue(
            "Repository Id",
            -1,
            uno::makeAny( rURL.getRepositoryId() ),
            beans::PropertyState_DIRECT_VALUE );

        return aArguments;
    }
}

namespace cmis
{
    Content::Content( const uno::Reference< uno::XComponentContext >& rxContext,
        ContentProvider *pProvider, const uno::Reference< ucb::XContentIdentifier >& Identifier,
        libcmis::ObjectPtr const & pObject )
        : ContentImplHelper( rxContext, pProvider, Identifier ),
        m_pProvider( pProvider ),
        m_pSession( nullptr ),
        m_pObject( pObject ),
        m_sURL( Identifier->getContentIdentifier( ) ),
        m_aURL( Identifier->getContentIdentifier( ) ),
        m_bTransient( false ),
        m_bIsFolder( false )
    {
        SAL_INFO( "ucb.ucp.cmis", "Content::Content() " << m_sURL );

        m_sObjectPath = m_aURL.getObjectPath( );
        m_sObjectId = m_aURL.getObjectId( );
    }

    Content::Content( const uno::Reference< uno::XComponentContext >& rxContext, ContentProvider *pProvider,
        const uno::Reference< ucb::XContentIdentifier >& Identifier,
        bool bIsFolder )
        : ContentImplHelper( rxContext, pProvider, Identifier ),
        m_pProvider( pProvider ),
        m_pSession( nullptr ),
        m_sURL( Identifier->getContentIdentifier( ) ),
        m_aURL( Identifier->getContentIdentifier( ) ),
        m_bTransient( true ),
        m_bIsFolder( bIsFolder )
    {
        SAL_INFO( "ucb.ucp.cmis", "Content::Content() " << m_sURL );

        m_sObjectPath = m_aURL.getObjectPath( );
        m_sObjectId = m_aURL.getObjectId( );
    }

    Content::~Content()
    {
    }

    libcmis::Session* Content::getSession( const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        // Set the proxy if needed. We are doing that all times as the proxy data shouldn't be cached.
        ucbhelper::InternetProxyDecider aProxyDecider( m_xContext );
        INetURLObject aBindingUrl( m_aURL.getBindingUrl( ) );
        const ucbhelper::InternetProxyServer& rProxy = aProxyDecider.getProxy(
                INetURLObject::GetScheme( aBindingUrl.GetProtocol( ) ), aBindingUrl.GetHost(), aBindingUrl.GetPort() );
        OUString sProxy = rProxy.aName;
        if ( rProxy.nPort > 0 )
            sProxy += ":" + OUString::number( rProxy.nPort );
        libcmis::SessionFactory::setProxySettings( OUSTR_TO_STDSTR( sProxy ), string(), string(), string() );

        // Look for a cached session, key is binding url + repo id
        OUString sSessionId = m_aURL.getBindingUrl( ) + m_aURL.getRepositoryId( );
        if ( nullptr == m_pSession )
            m_pSession = m_pProvider->getSession( sSessionId, m_aURL.getUsername( ) );

        if ( nullptr == m_pSession )
        {
#ifndef SYSTEM_CURL
            // Initialize NSS library to make sure libcmis (and curl) can access CACERTs using NSS
            // when using internal libcurl.
            uno::Reference< css::xml::crypto::XNSSInitializer >
                xNSSInitializer = css::xml::crypto::NSSInitializer::create( m_xContext );

            uno::Reference< css::xml::crypto::XDigestContext > xDigestContext(
                    xNSSInitializer->getDigestContext( css::xml::crypto::DigestID::SHA256,
                                                              uno::Sequence< beans::NamedValue >() ),
                                                              uno::UNO_SET_THROW );
#endif

            // Set the SSL Validation handler
            libcmis::CertValidationHandlerPtr certHandler(
                    new CertValidationHandler( xEnv, m_xContext, aBindingUrl.GetHost( ) ) );
            libcmis::SessionFactory::setCertificateValidationHandler( certHandler );

            // Get the auth credentials
            AuthProvider aAuthProvider(xEnv, m_xIdentifier->getContentIdentifier(), m_aURL.getBindingUrl());
            AuthProvider::setXEnv( xEnv );

            string rUsername = OUSTR_TO_STDSTR( m_aURL.getUsername( ) );
            string rPassword = OUSTR_TO_STDSTR( m_aURL.getPassword( ) );

            bool bIsDone = false;

            while ( !bIsDone )
            {
                if (aAuthProvider.authenticationQuery(rUsername, rPassword))
                {
                    // Initiate a CMIS session and register it as we found nothing
                    libcmis::OAuth2DataPtr oauth2Data;
                    if ( m_aURL.getBindingUrl( ) == GDRIVE_BASE_URL )
                    {
                        libcmis::SessionFactory::setOAuth2AuthCodeProvider(AuthProvider::gdriveAuthCodeFallback);
                        oauth2Data.reset( new libcmis::OAuth2Data(
                            GDRIVE_AUTH_URL, GDRIVE_TOKEN_URL,
                            GDRIVE_SCOPE, GDRIVE_REDIRECT_URI,
                            GDRIVE_CLIENT_ID, GDRIVE_CLIENT_SECRET ) );
                    }
                    if ( m_aURL.getBindingUrl().startsWith( ALFRESCO_CLOUD_BASE_URL ) )
                        oauth2Data.reset( new libcmis::OAuth2Data(
                            ALFRESCO_CLOUD_AUTH_URL, ALFRESCO_CLOUD_TOKEN_URL,
                            ALFRESCO_CLOUD_SCOPE, ALFRESCO_CLOUD_REDIRECT_URI,
                            ALFRESCO_CLOUD_CLIENT_ID, ALFRESCO_CLOUD_CLIENT_SECRET ) );
                    if ( m_aURL.getBindingUrl( ) == ONEDRIVE_BASE_URL )
                    {
                        libcmis::SessionFactory::setOAuth2AuthCodeProvider(AuthProvider::onedriveAuthCodeFallback);
                        oauth2Data.reset( new libcmis::OAuth2Data(
                            ONEDRIVE_AUTH_URL, ONEDRIVE_TOKEN_URL,
                            ONEDRIVE_SCOPE, ONEDRIVE_REDIRECT_URI,
                            ONEDRIVE_CLIENT_ID, ONEDRIVE_CLIENT_SECRET ) );
                    }
                    try
                    {
                        m_pSession = libcmis::SessionFactory::createSession(
                            OUSTR_TO_STDSTR( m_aURL.getBindingUrl( ) ),
                            rUsername, rPassword, OUSTR_TO_STDSTR( m_aURL.getRepositoryId( ) ), false, oauth2Data );

                        if ( m_pSession == nullptr )
                        {
                            // Fail: session was not created
                            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_INVALID_DEVICE,
                                generateErrorArguments(m_aURL),
                                xEnv);
                        }
                        else if ( m_pSession->getRepository() == nullptr )
                        {
                            // Fail: no repository or repository is invalid
                            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_INVALID_DEVICE,
                                generateErrorArguments(m_aURL),
                                xEnv,
                                "error accessing a repository");
                        }
                        else
                        {
                            m_pProvider->registerSession(sSessionId, m_aURL.getUsername( ), m_pSession);
                        }

                        bIsDone = true;
                    }
                    catch( const libcmis::Exception & e )
                    {
                        if ( e.getType() != "permissionDenied" )
                            throw;
                    }
                }
                else
                {
                    // Silently fail as the user cancelled the authentication
                    ucbhelper::cancelCommandExecution(
                                        ucb::IOErrorCode_ABORT,
                                        uno::Sequence< uno::Any >( 0 ),
                                        xEnv );
                    throw uno::RuntimeException( );
                }
            }
        }
        return m_pSession;
    }

    libcmis::ObjectTypePtr const & Content::getObjectType( const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        if ( nullptr == m_pObjectType.get( ) && m_bTransient )
        {
            string typeId = m_bIsFolder ? "cmis:folder" : "cmis:document";
            // The type to create needs to be fetched from the possible children types
            // defined in the parent folder. Then, we'll pick up the first one we find matching
            // cmis:folder or cmis:document (depending what we need to create).
            // The easy case will work in most cases, but not on some servers (like Lotus Live)
            libcmis::Folder* pParent = nullptr;
            bool bTypeRestricted = false;
            try
            {
                pParent = dynamic_cast< libcmis::Folder* >( getObject( xEnv ).get( ) );
            }
            catch ( const libcmis::Exception& )
            {
            }

            if ( pParent )
            {
                map< string, libcmis::PropertyPtr >& aProperties = pParent->getProperties( );
                map< string, libcmis::PropertyPtr >::iterator it = aProperties.find( "cmis:allowedChildObjectTypeIds" );
                if ( it != aProperties.end( ) )
                {
                    libcmis::PropertyPtr pProperty = it->second;
                    if ( pProperty )
                    {
                        vector< string > typesIds = pProperty->getStrings( );
                        for ( const auto& rType : typesIds )
                        {
                            bTypeRestricted = true;
                            libcmis::ObjectTypePtr type = getSession( xEnv )->getType( rType );

                            // FIXME Improve performances by adding getBaseTypeId( ) method to libcmis
                            if ( type->getBaseType( )->getId( ) == typeId )
                            {
                                m_pObjectType = type;
                                break;
                            }
                        }
                    }
                }
            }

            if ( !bTypeRestricted )
                m_pObjectType = getSession( xEnv )->getType( typeId );
        }
        return m_pObjectType;
    }


    libcmis::ObjectPtr const & Content::getObject( const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        // can't get the session for some reason
        // the recent file opening at start up is an example.
        try
        {
            if ( !getSession( xEnv ) )
                return m_pObject;
        }
        catch ( uno::RuntimeException& )
        {
            return m_pObject;
        }
        if ( !m_pObject.get() )
        {
            if ( !m_sObjectId.isEmpty( ) )
            {
                try
                {
                    m_pObject = getSession( xEnv )->getObject( OUSTR_TO_STDSTR( m_sObjectId ) );
                }
                catch ( const libcmis::Exception& )
                {
                    throw libcmis::Exception( "Object not found" );
                }
            }
            else if (!(m_sObjectPath.isEmpty() || m_sObjectPath == "/"))
            {
                try
                {
                    m_pObject = getSession( xEnv )->getObjectByPath( OUSTR_TO_STDSTR( m_sObjectPath ) );
                }
                catch ( const libcmis::Exception& )
                {
                    // In some cases, getting the object from the path doesn't work,
                    // but getting the parent from its path and the get the child in the list is OK.
                    // It's weird, but needed to handle case where the path isn't the folders/files
                    // names separated by '/' (as in Lotus Live)
                    INetURLObject aParentUrl( m_sURL );
                    string sName = OUSTR_TO_STDSTR( aParentUrl.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DecodeMechanism::WithCharset ) );
                    aParentUrl.removeSegment( );
                    OUString sParentUrl = aParentUrl.GetMainURL( INetURLObject::DecodeMechanism::NONE );
                    // Avoid infinite recursion if sParentUrl == m_sURL
                    if (sParentUrl != m_sURL)
                    {
                        rtl::Reference<Content> xParent(new Content(m_xContext, m_pProvider, new ucbhelper::ContentIdentifier(sParentUrl)));
                        libcmis::FolderPtr pParentFolder = boost::dynamic_pointer_cast< libcmis::Folder >(xParent->getObject(xEnv));
                        if (pParentFolder)
                        {
                            vector< libcmis::ObjectPtr > children = pParentFolder->getChildren();
                            auto it = std::find_if(children.begin(), children.end(),
                                [&sName](const libcmis::ObjectPtr& rChild) { return rChild->getName() == sName; });
                            if (it != children.end())
                                m_pObject = *it;
                        }
                    }

                    if ( !m_pObject )
                        throw libcmis::Exception( "Object not found" );
                }
            }
            else
            {
                m_pObject = getSession( xEnv )->getRootFolder( );
                m_sObjectPath = "/";
                m_sObjectId = OUString( );
            }
        }

        return m_pObject;
    }

    bool Content::isFolder(const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        bool bIsFolder = false;
        try
        {
            libcmis::ObjectPtr obj = getObject( xEnv );
            if ( obj )
                bIsFolder = obj->getBaseType( ) == "cmis:folder";
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );

            ucbhelper::cancelCommandExecution(
                            ucb::IOErrorCode_GENERAL,
                            uno::Sequence< uno::Any >( 0 ),
                            xEnv,
                            OUString::createFromAscii( e.what( ) ) );

        }
        return bIsFolder;
    }

    uno::Any Content::getBadArgExcept()
    {
        return uno::makeAny( lang::IllegalArgumentException(
            "Wrong argument type!",
            static_cast< cppu::OWeakObject * >( this ), -1) );
    }

    libcmis::ObjectPtr Content::updateProperties(
         const uno::Any& iCmisProps,
         const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        // Convert iCmisProps to Cmis Properties;
        uno::Sequence< document::CmisProperty > aPropsSeq;
        iCmisProps >>= aPropsSeq;
        map< string, libcmis::PropertyPtr > aProperties;

        for ( const auto& rProp : std::as_const(aPropsSeq) )
        {
            std::string id = OUSTR_TO_STDSTR( rProp.Id );
            libcmis::PropertyPtr prop = lcl_unoToCmisProperty( rProp );
            aProperties.insert( std::pair<string, libcmis::PropertyPtr>( id, prop ) );
        }
        libcmis::ObjectPtr updateObj;
        try
        {
            updateObj = getObject( xEnv )->updateProperties( aProperties );
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: "<< e.what( ) );
        }

        return updateObj;
    }

    uno::Reference< sdbc::XRow > Content::getPropertyValues(
            const uno::Sequence< beans::Property >& rProperties,
            const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        rtl::Reference< ::ucbhelper::PropertyValueSet > xRow = new ::ucbhelper::PropertyValueSet( m_xContext );

        for( const beans::Property& rProp : rProperties )
        {
            try
            {
                if ( rProp.Name == "IsDocument" )
                {
                    try
                    {
                        libcmis::ObjectPtr obj = getObject( xEnv );
                        if ( obj )
                            xRow->appendBoolean( rProp, obj->getBaseType( ) == "cmis:document" );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        if ( m_pObjectType.get( ) )
                            xRow->appendBoolean( rProp, getObjectType( xEnv )->getBaseType()->getId( ) == "cmis:document" );
                        else
                            xRow->appendVoid( rProp );
                    }
                }
                else if ( rProp.Name == "IsFolder" )
                {
                    try
                    {
                        libcmis::ObjectPtr obj = getObject( xEnv );
                        if ( obj )
                            xRow->appendBoolean( rProp, obj->getBaseType( ) == "cmis:folder" );
                        else
                            xRow->appendBoolean( rProp, false );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        if ( m_pObjectType.get( ) )
                            xRow->appendBoolean( rProp, getObjectType( xEnv )->getBaseType()->getId( ) == "cmis:folder" );
                        else
                            xRow->appendVoid( rProp );
                    }
                }
                else if ( rProp.Name == "Title" )
                {
                    OUString sTitle;
                    try
                    {
                        sTitle = STD_TO_OUSTR( getObject( xEnv )->getName() );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        if ( !m_pObjectProps.empty() )
                        {
                            map< string, libcmis::PropertyPtr >::iterator it = m_pObjectProps.find( "cmis:name" );
                            if ( it != m_pObjectProps.end( ) )
                            {
                                vector< string > values = it->second->getStrings( );
                                if ( !values.empty() )
                                    sTitle = STD_TO_OUSTR( values.front( ) );
                            }
                        }
                    }

                    // Nothing worked... get it from the path
                    if ( sTitle.isEmpty( ) )
                    {
                        OUString sPath = m_sObjectPath;

                        // Get rid of the trailing slash problem
                        if ( sPath.endsWith("/") )
                            sPath = sPath.copy( 0, sPath.getLength() - 1 );

                        // Get the last segment
                        sal_Int32 nPos = sPath.lastIndexOf( '/' );
                        if ( nPos >= 0 )
                            sTitle = sPath.copy( nPos + 1 );
                    }

                    if ( !sTitle.isEmpty( ) )
                        xRow->appendString( rProp, sTitle );
                    else
                        xRow->appendVoid( rProp );
                }
                else if ( rProp.Name == "ObjectId" )
                {
                    OUString sId;
                    try
                    {
                        sId = STD_TO_OUSTR( getObject( xEnv )->getId() );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        if ( !m_pObjectProps.empty() )
                        {
                            map< string, libcmis::PropertyPtr >::iterator it = m_pObjectProps.find( "cmis:objectId" );
                            if ( it != m_pObjectProps.end( ) )
                            {
                                vector< string > values = it->second->getStrings( );
                                if ( !values.empty() )
                                    sId = STD_TO_OUSTR( values.front( ) );
                            }
                        }
                    }

                    if ( !sId.isEmpty( ) )
                        xRow->appendString( rProp, sId );
                    else
                        xRow->appendVoid( rProp );
                }
                else if ( rProp.Name == "TitleOnServer" )
                {
                    xRow->appendString( rProp, m_sObjectPath);
                }
                else if ( rProp.Name == "IsReadOnly" )
                {
                    boost::shared_ptr< libcmis::AllowableActions > allowableActions = getObject( xEnv )->getAllowableActions( );
                    bool bReadOnly = false;
                    if ( !allowableActions->isAllowed( libcmis::ObjectAction::SetContentStream ) &&
                         !allowableActions->isAllowed( libcmis::ObjectAction::CheckIn ) )
                        bReadOnly = true;

                    xRow->appendBoolean( rProp, bReadOnly );
                }
                else if ( rProp.Name == "DateCreated" )
                {
                    util::DateTime aTime = lcl_boostToUnoTime( getObject( xEnv )->getCreationDate( ) );
                    xRow->appendTimestamp( rProp, aTime );
                }
                else if ( rProp.Name == "DateModified" )
                {
                    util::DateTime aTime = lcl_boostToUnoTime( getObject( xEnv )->getLastModificationDate( ) );
                    xRow->appendTimestamp( rProp, aTime );
                }
                else if ( rProp.Name == "Size" )
                {
                    try
                    {
                        libcmis::Document* document = dynamic_cast< libcmis::Document* >( getObject( xEnv ).get( ) );
                        if ( nullptr != document )
                            xRow->appendLong( rProp, document->getContentLength() );
                        else
                            xRow->appendVoid( rProp );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        xRow->appendVoid( rProp );
                    }
                }
                else if ( rProp.Name == "CreatableContentsInfo" )
                {
                    xRow->appendObject( rProp, uno::makeAny( queryCreatableContentsInfo( xEnv ) ) );
                }
                else if ( rProp.Name == "MediaType" )
                {
                    try
                    {
                        libcmis::Document* document = dynamic_cast< libcmis::Document* >( getObject( xEnv ).get( ) );
                        if ( nullptr != document )
                            xRow->appendString( rProp, STD_TO_OUSTR( document->getContentType() ) );
                        else
                            xRow->appendVoid( rProp );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        xRow->appendVoid( rProp );
                    }
                }
                else if ( rProp.Name == "IsVolume" )
                {
                    xRow->appendBoolean( rProp, false );
                }
                else if ( rProp.Name == "IsRemote" )
                {
                    xRow->appendBoolean( rProp, false );
                }
                else if ( rProp.Name == "IsRemoveable" )
                {
                    xRow->appendBoolean( rProp, false );
                }
                else if ( rProp.Name == "IsFloppy" )
                {
                    xRow->appendBoolean( rProp, false );
                }
                else if ( rProp.Name == "IsCompactDisc" )
                {
                    xRow->appendBoolean( rProp, false );
                }
                else if ( rProp.Name == "IsHidden" )
                {
                    xRow->appendBoolean( rProp, false );
                }
                else if ( rProp.Name == "TargetURL" )
                {
                    xRow->appendString( rProp, "" );
                }
                else if ( rProp.Name == "BaseURI" )
                {
                    xRow->appendString( rProp, m_aURL.getBindingUrl( ) );
                }
                else if ( rProp.Name == "CmisProperties" )
                {
                    try
                    {
                        libcmis::ObjectPtr object = getObject( xEnv );
                        map< string, libcmis::PropertyPtr >& aProperties = object->getProperties( );
                        uno::Sequence< document::CmisProperty > aCmisProperties( aProperties.size( ) );
                        document::CmisProperty* pCmisProps = aCmisProperties.getArray( );
                        sal_Int32 i = 0;
                        for ( const auto& [sId, rProperty] : aProperties )
                        {
                            string sDisplayName = rProperty->getPropertyType()->getDisplayName( );
                            bool bUpdatable = rProperty->getPropertyType()->isUpdatable( );
                            bool bRequired = rProperty->getPropertyType()->isRequired( );
                            bool bMultiValued = rProperty->getPropertyType()->isMultiValued();
                            bool bOpenChoice = rProperty->getPropertyType()->isOpenChoice();

                            pCmisProps[i].Id = STD_TO_OUSTR( sId );
                            pCmisProps[i].Name = STD_TO_OUSTR( sDisplayName );
                            pCmisProps[i].Updatable = bUpdatable;
                            pCmisProps[i].Required = bRequired;
                            pCmisProps[i].MultiValued = bMultiValued;
                            pCmisProps[i].OpenChoice = bOpenChoice;
                            pCmisProps[i].Value = lcl_cmisPropertyToUno( rProperty );
                            switch ( rProperty->getPropertyType( )->getType( ) )
                            {
                                default:
                                case libcmis::PropertyType::String:
                                    pCmisProps[i].Type = CMIS_TYPE_STRING;
                                break;
                                case libcmis::PropertyType::Integer:
                                    pCmisProps[i].Type = CMIS_TYPE_INTEGER;
                                break;
                                case libcmis::PropertyType::Decimal:
                                    pCmisProps[i].Type = CMIS_TYPE_DECIMAL;
                                break;
                                case libcmis::PropertyType::Bool:
                                    pCmisProps[i].Type = CMIS_TYPE_BOOL;
                                break;
                                case libcmis::PropertyType::DateTime:
                                    pCmisProps[i].Type = CMIS_TYPE_DATETIME;
                                break;
                            }
                            ++i;
                        }
                        xRow->appendObject( rProp.Name, uno::makeAny( aCmisProperties ) );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        xRow->appendVoid( rProp );
                    }
                }
                else if ( rProp.Name == "IsVersionable" )
                {
                    try
                    {
                        libcmis::ObjectPtr object = getObject( xEnv );
                        bool bIsVersionable = object->getTypeDescription( )->isVersionable( );
                        xRow->appendBoolean( rProp, bIsVersionable );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        xRow->appendVoid( rProp );
                    }
                }
                else if ( rProp.Name == "CanCheckOut" )
                {
                    try
                    {
                        libcmis::ObjectPtr pObject = getObject( xEnv );
                        libcmis::AllowableActionsPtr aAllowables = pObject->getAllowableActions( );
                        bool bAllowed = false;
                        if ( aAllowables )
                        {
                            bAllowed = aAllowables->isAllowed( libcmis::ObjectAction::CheckOut );
                        }
                        xRow->appendBoolean( rProp, bAllowed );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        xRow->appendVoid( rProp );
                    }
                }
                else if ( rProp.Name == "CanCancelCheckOut" )
                {
                    try
                    {
                        libcmis::ObjectPtr pObject = getObject( xEnv );
                        libcmis::AllowableActionsPtr aAllowables = pObject->getAllowableActions( );
                        bool bAllowed = false;
                        if ( aAllowables )
                        {
                            bAllowed = aAllowables->isAllowed( libcmis::ObjectAction::CancelCheckOut );
                        }
                        xRow->appendBoolean( rProp, bAllowed );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        xRow->appendVoid( rProp );
                    }
                }
                else if ( rProp.Name == "CanCheckIn" )
                {
                    try
                    {
                        libcmis::ObjectPtr pObject = getObject( xEnv );
                        libcmis::AllowableActionsPtr aAllowables = pObject->getAllowableActions( );
                        bool bAllowed = false;
                        if ( aAllowables )
                        {
                            bAllowed = aAllowables->isAllowed( libcmis::ObjectAction::CheckIn );
                        }
                        xRow->appendBoolean( rProp, bAllowed );
                    }
                    catch ( const libcmis::Exception& )
                    {
                        xRow->appendVoid( rProp );
                    }
                }
                else
                    SAL_INFO( "ucb.ucp.cmis", "Looking for unsupported property " << rProp.Name );
            }
            catch (const libcmis::Exception&)
            {
                xRow->appendVoid( rProp );
            }
        }

        return uno::Reference< sdbc::XRow >( xRow.get() );
    }

    uno::Any Content::open(const ucb::OpenCommandArgument2 & rOpenCommand,
        const uno::Reference< ucb::XCommandEnvironment > & xEnv )
    {
        bool bIsFolder = isFolder( xEnv );

        // Handle the case of the non-existing file
        if ( !getObject( xEnv ) )
        {
            uno::Sequence< uno::Any > aArgs( 1 );
            aArgs[ 0 ] <<= m_xIdentifier->getContentIdentifier();
            uno::Any aErr = uno::makeAny(
                ucb::InteractiveAugmentedIOException(OUString(), static_cast< cppu::OWeakObject * >( this ),
                    task::InteractionClassification_ERROR,
                    bIsFolder ? ucb::IOErrorCode_NOT_EXISTING_PATH : ucb::IOErrorCode_NOT_EXISTING, aArgs)
            );

            ucbhelper::cancelCommandExecution(aErr, xEnv);
        }

        uno::Any aRet;

        bool bOpenFolder = (
            ( rOpenCommand.Mode == ucb::OpenMode::ALL ) ||
            ( rOpenCommand.Mode == ucb::OpenMode::FOLDERS ) ||
            ( rOpenCommand.Mode == ucb::OpenMode::DOCUMENTS )
         );

        if ( bOpenFolder && bIsFolder )
        {
            uno::Reference< ucb::XDynamicResultSet > xSet
                = new DynamicResultSet(m_xContext, this, rOpenCommand, xEnv );
            aRet <<= xSet;
        }
        else if ( rOpenCommand.Sink.is() )
        {
            if (
                ( rOpenCommand.Mode == ucb::OpenMode::DOCUMENT_SHARE_DENY_NONE ) ||
                ( rOpenCommand.Mode == ucb::OpenMode::DOCUMENT_SHARE_DENY_WRITE )
               )
            {
                ucbhelper::cancelCommandExecution(
                    uno::makeAny ( ucb::UnsupportedOpenModeException
                        ( OUString(), static_cast< cppu::OWeakObject * >( this ),
                          sal_Int16( rOpenCommand.Mode ) ) ),
                        xEnv );
            }

            if ( !feedSink( rOpenCommand.Sink, xEnv ) )
            {
                // Note: rOpenCommand.Sink may contain an XStream
                //       implementation. Support for this type of
                //       sink is optional...
                SAL_INFO( "ucb.ucp.cmis", "Failed to copy data to sink" );

                ucbhelper::cancelCommandExecution(
                    uno::makeAny (ucb::UnsupportedDataSinkException
                        ( OUString(), static_cast< cppu::OWeakObject * >( this ),
                          rOpenCommand.Sink ) ),
                        xEnv );
            }
        }
        else
            SAL_INFO( "ucb.ucp.cmis", "Open falling through ..." );

        return aRet;
    }

    OUString Content::checkIn( const ucb::CheckinArgument& rArg,
        const uno::Reference< ucb::XCommandEnvironment > & xEnv )
    {
        ucbhelper::Content aSourceContent( rArg.SourceURL, xEnv, comphelper::getProcessComponentContext( ) );
        uno::Reference< io::XInputStream > xIn = aSourceContent.openStream( );

        libcmis::ObjectPtr object;
        try
        {
            object = getObject( xEnv );
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_GENERAL,
                                uno::Sequence< uno::Any >( 0 ),
                                xEnv,
                                OUString::createFromAscii( e.what() ) );
        }

        libcmis::Document* pPwc = dynamic_cast< libcmis::Document* >( object.get( ) );
        if ( !pPwc )
        {
            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_GENERAL,
                                uno::Sequence< uno::Any >( 0 ),
                                xEnv,
                                "Checkin only supported by documents" );
        }

        boost::shared_ptr< ostream > pOut( new ostringstream ( ios_base::binary | ios_base::in | ios_base::out ) );
        uno::Reference < io::XOutputStream > xOutput = new StdOutputStream( pOut );
        copyData( xIn, xOutput );

        map< string, libcmis::PropertyPtr > newProperties;
        libcmis::DocumentPtr pDoc;

        try
        {
            pDoc = pPwc->checkIn( rArg.MajorVersion, OUSTR_TO_STDSTR( rArg.VersionComment ), newProperties,
                                  pOut, OUSTR_TO_STDSTR( rArg.MimeType ), OUSTR_TO_STDSTR( rArg.NewTitle ) );
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_GENERAL,
                                uno::Sequence< uno::Any >( 0 ),
                                xEnv,
                                OUString::createFromAscii( e.what() ) );
        }

        // Get the URL and send it back as a result
        URL aCmisUrl( m_sURL );
        vector< string > aPaths = pDoc->getPaths( );
        if ( !aPaths.empty() )
        {
            string sPath = aPaths.front( );
            aCmisUrl.setObjectPath( STD_TO_OUSTR( sPath ) );
        }
        else
        {
            // We may have unfiled document depending on the server, those
            // won't have any path, use their ID instead
            string sId = pDoc->getId( );
            aCmisUrl.setObjectId( STD_TO_OUSTR( sId ) );
        }
        return aCmisUrl.asString( );
    }

    OUString Content::checkOut( const uno::Reference< ucb::XCommandEnvironment > & xEnv )
    {
        OUString aRet;
        try
        {
            // Checkout the document if possible
            libcmis::DocumentPtr pDoc = boost::dynamic_pointer_cast< libcmis::Document >( getObject( xEnv ) );
            if ( pDoc.get( ) == nullptr )
            {
                ucbhelper::cancelCommandExecution(
                                    ucb::IOErrorCode_GENERAL,
                                    uno::Sequence< uno::Any >( 0 ),
                                    xEnv,
                                    "Checkout only supported by documents" );
            }
            libcmis::DocumentPtr pPwc = pDoc->checkOut( );

            // Compute the URL of the Private Working Copy (PWC)
            URL aCmisUrl( m_sURL );
            vector< string > aPaths = pPwc->getPaths( );
            if ( !aPaths.empty() )
            {
                string sPath = aPaths.front( );
                aCmisUrl.setObjectPath( STD_TO_OUSTR( sPath ) );
            }
            else
            {
                // We may have unfiled PWC depending on the server, those
                // won't have any path, use their ID instead
                string sId = pPwc->getId( );
                aCmisUrl.setObjectId( STD_TO_OUSTR( sId ) );
            }
            aRet = aCmisUrl.asString( );
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_GENERAL,
                                uno::Sequence< uno::Any >( 0 ),
                                xEnv,
                                o3tl::runtimeToOUString(e.what()));
        }
        return aRet;
    }

    OUString Content::cancelCheckOut( const uno::Reference< ucb::XCommandEnvironment > & xEnv )
    {
        OUString aRet;
        try
        {
            libcmis::DocumentPtr pPwc = boost::dynamic_pointer_cast< libcmis::Document >( getObject( xEnv ) );
            if ( pPwc.get( ) == nullptr )
            {
                ucbhelper::cancelCommandExecution(
                                    ucb::IOErrorCode_GENERAL,
                                    uno::Sequence< uno::Any >( 0 ),
                                    xEnv,
                                    "CancelCheckout only supported by documents" );
            }
            pPwc->cancelCheckout( );

            // Get the Original document (latest version)
            vector< libcmis::DocumentPtr > aVersions = pPwc->getAllVersions( );
            for ( const auto& rVersion : aVersions )
            {
                libcmis::DocumentPtr pVersion = rVersion;
                map< string, libcmis::PropertyPtr > aProps = pVersion->getProperties( );
                bool bIsLatestVersion = false;
                map< string, libcmis::PropertyPtr >::iterator propIt = aProps.find( string( "cmis:isLatestVersion" ) );
                if ( propIt != aProps.end( ) && !propIt->second->getBools( ).empty( ) )
                {
                    bIsLatestVersion = propIt->second->getBools( ).front( );
                }

                if ( bIsLatestVersion )
                {
                    // Compute the URL of the Document
                    URL aCmisUrl( m_sURL );
                    vector< string > aPaths = pVersion->getPaths( );
                    if ( !aPaths.empty() )
                    {
                        string sPath = aPaths.front( );
                        aCmisUrl.setObjectPath( STD_TO_OUSTR( sPath ) );
                    }
                    else
                    {
                        // We may have unfiled doc depending on the server, those
                        // won't have any path, use their ID instead
                        string sId = pVersion->getId( );
                        aCmisUrl.setObjectId( STD_TO_OUSTR( sId ) );
                    }
                    aRet = aCmisUrl.asString( );
                    break;
                }
            }
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_GENERAL,
                                uno::Sequence< uno::Any >( 0 ),
                                xEnv,
                                o3tl::runtimeToOUString(e.what()));
        }
        return aRet;
    }

    uno::Sequence< document::CmisVersion> Content::getAllVersions( const uno::Reference< ucb::XCommandEnvironment > & xEnv )
    {
        try
        {
            // get the document
            libcmis::DocumentPtr pDoc = boost::dynamic_pointer_cast< libcmis::Document >( getObject( xEnv ) );
            if ( pDoc.get( ) == nullptr )
            {
                ucbhelper::cancelCommandExecution(
                                    ucb::IOErrorCode_GENERAL,
                                    uno::Sequence< uno::Any >( 0 ),
                                    xEnv,
                                    "Can not get the document" );
            }
            vector< libcmis::DocumentPtr > aCmisVersions = pDoc->getAllVersions( );
            uno::Sequence< document::CmisVersion > aVersions( aCmisVersions.size( ) );
            int i = 0;
            for ( const auto& rVersion : aCmisVersions )
            {
                libcmis::DocumentPtr pVersion = rVersion;
                aVersions[i].Id = STD_TO_OUSTR( pVersion->getId( ) );
                aVersions[i].Author = STD_TO_OUSTR( pVersion->getCreatedBy( ) );
                aVersions[i].TimeStamp = lcl_boostToUnoTime( pVersion->getLastModificationDate( ) );
                aVersions[i].Comment = STD_TO_OUSTR( pVersion->getStringProperty("cmis:checkinComment") );
                ++i;
            }
            return aVersions;
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
            ucbhelper::cancelCommandExecution(
                    ucb::IOErrorCode_GENERAL,
                    uno::Sequence< uno::Any >( 0 ),
                    xEnv,
                    o3tl::runtimeToOUString(e.what()));
        }
        return uno::Sequence< document::CmisVersion > ( );
    }

    void Content::transfer( const ucb::TransferInfo& rTransferInfo,
        const uno::Reference< ucb::XCommandEnvironment > & xEnv )
    {
        // If the source isn't on the same CMIS repository, then simply copy
        INetURLObject aSourceUrl( rTransferInfo.SourceURL );
        if ( aSourceUrl.GetProtocol() != INetProtocol::Cmis )
        {
            OUString sSrcBindingUrl = URL( rTransferInfo.SourceURL ).getBindingUrl( );
            if ( sSrcBindingUrl != m_aURL.getBindingUrl( ) )
            {
                ucbhelper::cancelCommandExecution(
                    uno::makeAny(
                        ucb::InteractiveBadTransferURLException(
                            "Unsupported URL scheme!",
                            static_cast< cppu::OWeakObject * >( this ) ) ),
                    xEnv );
            }
        }

        SAL_INFO( "ucb.ucp.cmis", "TODO - Content::transfer()" );
    }

    void Content::insert( const uno::Reference< io::XInputStream > & xInputStream,
        bool bReplaceExisting, const OUString& rMimeType,
        const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        if ( !xInputStream.is() )
        {
            ucbhelper::cancelCommandExecution( uno::makeAny
                ( ucb::MissingInputStreamException
                  ( OUString(), static_cast< cppu::OWeakObject * >( this ) ) ),
                xEnv );
        }

        // For transient content, the URL is the one of the parent
        if ( m_bTransient )
        {
            OUString sNewPath;

            // Try to get the object from the server if there is any
            libcmis::FolderPtr pFolder;
            try
            {
                pFolder = boost::dynamic_pointer_cast< libcmis::Folder >( getObject( xEnv ) );
            }
            catch ( const libcmis::Exception& )
            {
            }

            if ( pFolder != nullptr )
            {
                libcmis::ObjectPtr object;
                map< string, libcmis::PropertyPtr >::iterator it = m_pObjectProps.find( "cmis:name" );
                if ( it == m_pObjectProps.end( ) )
                {
                    ucbhelper::cancelCommandExecution( uno::makeAny
                        ( uno::RuntimeException( "Missing name property",
                            static_cast< cppu::OWeakObject * >( this ) ) ),
                        xEnv );
                }
                string newName = it->second->getStrings( ).front( );
                string newPath = OUSTR_TO_STDSTR( m_sObjectPath );
                if ( !newPath.empty( ) && newPath[ newPath.size( ) - 1 ] != '/' )
                    newPath += "/";
                newPath += newName;
                try
                {
                    if ( !m_sObjectId.isEmpty( ) )
                        object = getSession( xEnv )->getObject( OUSTR_TO_STDSTR( m_sObjectId) );
                    else
                        object = getSession( xEnv )->getObjectByPath( newPath );
                    sNewPath = STD_TO_OUSTR( newPath );
                }
                catch ( const libcmis::Exception& )
                {
                    // Nothing matched the path
                }

                if ( nullptr != object.get( ) )
                {
                    // Are the base type matching?
                    if ( object->getBaseType( ) != m_pObjectType->getBaseType( )->getId() )
                    {
                        ucbhelper::cancelCommandExecution( uno::makeAny
                            ( uno::RuntimeException( "Can't change a folder into a document and vice-versa.",
                                static_cast< cppu::OWeakObject * >( this ) ) ),
                            xEnv );
                    }

                    // Update the existing object if it's a document
                    libcmis::Document* document = dynamic_cast< libcmis::Document* >( object.get( ) );
                    if ( nullptr != document )
                    {
                        boost::shared_ptr< ostream > pOut( new ostringstream ( ios_base::binary | ios_base::in | ios_base::out ) );
                        uno::Reference < io::XOutputStream > xOutput = new StdOutputStream( pOut );
                        copyData( xInputStream, xOutput );
                        try
                        {
                            document->setContentStream( pOut, OUSTR_TO_STDSTR( rMimeType ), string( ), bReplaceExisting );
                        }
                        catch ( const libcmis::Exception& )
                        {
                            ucbhelper::cancelCommandExecution( uno::makeAny
                                ( uno::RuntimeException( "Error when setting document content",
                                    static_cast< cppu::OWeakObject * >( this ) ) ),
                                xEnv );
                        }
                    }
                }
                else
                {
                    // We need to create a brand new object... either folder or document
                    bool bIsFolder = getObjectType( xEnv )->getBaseType( )->getId( ) == "cmis:folder";
                    setCmisProperty( "cmis:objectTypeId", getObjectType( xEnv )->getId( ), xEnv );

                    if ( bIsFolder )
                    {
                        try
                        {
                            pFolder->createFolder( m_pObjectProps );
                            sNewPath = STD_TO_OUSTR( newPath );
                        }
                        catch ( const libcmis::Exception& )
                        {
                            ucbhelper::cancelCommandExecution( uno::makeAny
                                ( uno::RuntimeException( "Error when creating folder",
                                    static_cast< cppu::OWeakObject * >( this ) ) ),
                                xEnv );
                        }
                    }
                    else
                    {
                        boost::shared_ptr< ostream > pOut( new ostringstream ( ios_base::binary | ios_base::in | ios_base::out ) );
                        uno::Reference < io::XOutputStream > xOutput = new StdOutputStream( pOut );
                        copyData( xInputStream, xOutput );
                        try
                        {
                            pFolder->createDocument( m_pObjectProps, pOut, OUSTR_TO_STDSTR( rMimeType ), string() );
                            sNewPath = STD_TO_OUSTR( newPath );
                        }
                        catch ( const libcmis::Exception& )
                        {
                            ucbhelper::cancelCommandExecution( uno::makeAny
                                ( uno::RuntimeException( "Error when creating document",
                                    static_cast< cppu::OWeakObject * >( this ) ) ),
                                xEnv );
                        }
                    }
                }

                if ( !sNewPath.isEmpty( ) || !m_sObjectId.isEmpty( ) )
                {
                    // Update the current content: it's no longer transient
                    m_sObjectPath = sNewPath;
                    URL aUrl( m_sURL );
                    aUrl.setObjectPath( m_sObjectPath );
                    aUrl.setObjectId( m_sObjectId );
                    m_sURL = aUrl.asString( );
                    m_pObject.reset( );
                    m_pObjectType.reset( );
                    m_pObjectProps.clear( );
                    m_bTransient = false;
                    inserted();
                }
            }
        }
    }

    const int TRANSFER_BUFFER_SIZE = 65536;

    void Content::copyData(
        const uno::Reference< io::XInputStream >& xIn,
        const uno::Reference< io::XOutputStream >& xOut )
    {
        uno::Sequence< sal_Int8 > theData( TRANSFER_BUFFER_SIZE );

        while ( xIn->readBytes( theData, TRANSFER_BUFFER_SIZE ) > 0 )
            xOut->writeBytes( theData );

        xOut->closeOutput();
    }

    uno::Sequence< uno::Any > Content::setPropertyValues(
            const uno::Sequence< beans::PropertyValue >& rValues,
            const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        try
        {
            // Get the already set properties if possible
            if ( !m_bTransient && getObject( xEnv ).get( ) )
            {
                m_pObjectProps.clear( );
                m_pObjectType = getObject( xEnv )->getTypeDescription();
            }
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_GENERAL,
                                uno::Sequence< uno::Any >( 0 ),
                                xEnv,
                                o3tl::runtimeToOUString(e.what()));
        }

        sal_Int32 nCount = rValues.getLength();
        uno::Sequence< uno::Any > aRet( nCount );

        bool bChanged = false;
        const beans::PropertyValue* pValues = rValues.getConstArray();
        for ( sal_Int32 n = 0; n < nCount; ++n )
        {
            const beans::PropertyValue& rValue = pValues[ n ];
            if ( rValue.Name == "ContentType" ||
                 rValue.Name == "MediaType" ||
                 rValue.Name == "IsDocument" ||
                 rValue.Name == "IsFolder" ||
                 rValue.Name == "Size" ||
                 rValue.Name == "CreatableContentsInfo" )
            {
                lang::IllegalAccessException e ( "Property is read-only!",
                       static_cast< cppu::OWeakObject* >( this ) );
                aRet[ n ] <<= e;
            }
            else if ( rValue.Name == "Title" )
            {
                OUString aNewTitle;
                if (!( rValue.Value >>= aNewTitle ))
                {
                    aRet[ n ] <<= beans::IllegalTypeException
                        ( "Property value has wrong type!",
                          static_cast< cppu::OWeakObject * >( this ) );
                    continue;
                }

                if ( aNewTitle.getLength() <= 0 )
                {
                    aRet[ n ] <<= lang::IllegalArgumentException
                        ( "Empty title not allowed!",
                          static_cast< cppu::OWeakObject * >( this ), -1 );
                    continue;

                }

                setCmisProperty( "cmis:name", OUSTR_TO_STDSTR( aNewTitle ), xEnv );
                bChanged = true;
            }
            else
            {
                SAL_INFO( "ucb.ucp.cmis", "Couldn't set property: " << rValue.Name );
                lang::IllegalAccessException e ( "Property is read-only!",
                       static_cast< cppu::OWeakObject* >( this ) );
                aRet[ n ] <<= e;
            }
        }

        try
        {
            if ( !m_bTransient && bChanged )
            {
                getObject( xEnv )->updateProperties( m_pObjectProps );
            }
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_GENERAL,
                                uno::Sequence< uno::Any >( 0 ),
                                xEnv,
                                o3tl::runtimeToOUString(e.what()));
        }

        return aRet;
    }

    bool Content::feedSink( const uno::Reference< uno::XInterface>& xSink,
        const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        if ( !xSink.is() )
            return false;

        uno::Reference< io::XOutputStream > xOut(xSink, uno::UNO_QUERY );
        uno::Reference< io::XActiveDataSink > xDataSink(xSink, uno::UNO_QUERY );
        uno::Reference< io::XActiveDataStreamer > xDataStreamer( xSink, uno::UNO_QUERY );

        if ( !xOut.is() && !xDataSink.is() && ( !xDataStreamer.is() || !xDataStreamer->getStream().is() ) )
            return false;

        if ( xDataStreamer.is() && !xOut.is() )
            xOut = xDataStreamer->getStream()->getOutputStream();

        try
        {
            libcmis::Document* document = dynamic_cast< libcmis::Document* >( getObject( xEnv ).get() );

            if (!document)
                return false;

            boost::shared_ptr< istream > aIn = document->getContentStream( );

            uno::Reference< io::XInputStream > xIn = new StdInputStream( aIn );
            if( !xIn.is( ) )
                return false;

            if ( xDataSink.is() )
                xDataSink->setInputStream( xIn );
            else if ( xOut.is() )
                copyData( xIn, xOut );
        }
        catch ( const libcmis::Exception& e )
        {
            SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
            ucbhelper::cancelCommandExecution(
                                ucb::IOErrorCode_GENERAL,
                                uno::Sequence< uno::Any >( 0 ),
                                xEnv,
                                o3tl::runtimeToOUString(e.what()));
        }

        return true;
    }

    uno::Sequence< beans::Property > Content::getProperties(
            const uno::Reference< ucb::XCommandEnvironment > & )
    {
        static const beans::Property aGenericProperties[] =
        {
            beans::Property( "IsDocument",
                -1, cppu::UnoType<bool>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "IsFolder",
                -1, cppu::UnoType<bool>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "Title",
                -1, cppu::UnoType<OUString>::get(),
                beans::PropertyAttribute::BOUND ),
            beans::Property( "ObjectId",
                -1, cppu::UnoType<OUString>::get(),
                beans::PropertyAttribute::BOUND ),
            beans::Property( "TitleOnServer",
                -1, cppu::UnoType<OUString>::get(),
                beans::PropertyAttribute::BOUND ),
            beans::Property( "IsReadOnly",
                -1, cppu::UnoType<bool>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "DateCreated",
                -1, cppu::UnoType<util::DateTime>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "DateModified",
                -1, cppu::UnoType<util::DateTime>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "Size",
                -1, cppu::UnoType<sal_Int64>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "CreatableContentsInfo",
                -1, cppu::UnoType<uno::Sequence< ucb::ContentInfo >>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "MediaType",
                -1, cppu::UnoType<OUString>::get(),
                beans::PropertyAttribute::BOUND ),
            beans::Property( "CmisProperties",
                -1, cppu::UnoType<uno::Sequence< document::CmisProperty>>::get(),
                beans::PropertyAttribute::BOUND ),
            beans::Property( "IsVersionable",
                -1, cppu::UnoType<bool>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "CanCheckOut",
                -1, cppu::UnoType<bool>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "CanCancelCheckOut",
                -1, cppu::UnoType<bool>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
            beans::Property( "CanCheckIn",
                -1, cppu::UnoType<bool>::get(),
                beans::PropertyAttribute::BOUND | beans::PropertyAttribute::READONLY ),
        };

        const int nProps = SAL_N_ELEMENTS(aGenericProperties);
        return uno::Sequence< beans::Property > ( aGenericProperties, nProps );
    }

    uno::Sequence< ucb::CommandInfo > Content::getCommands(
            const uno::Reference< ucb::XCommandEnvironment > & xEnv )
    {
        static const ucb::CommandInfo aCommandInfoTable[] =
        {
            // Required commands
            ucb::CommandInfo
            ( "getCommandInfo",
              -1, cppu::UnoType<void>::get() ),
            ucb::CommandInfo
            ( "getPropertySetInfo",
              -1, cppu::UnoType<void>::get() ),
            ucb::CommandInfo
            ( "getPropertyValues",
              -1, cppu::UnoType<uno::Sequence< beans::Property >>::get() ),
            ucb::CommandInfo
            ( "setPropertyValues",
              -1, cppu::UnoType<uno::Sequence< beans::PropertyValue >>::get() ),

            // Optional standard commands
            ucb::CommandInfo
            ( "delete",
              -1, cppu::UnoType<bool>::get() ),
            ucb::CommandInfo
            ( "insert",
              -1, cppu::UnoType<ucb::InsertCommandArgument2>::get() ),
            ucb::CommandInfo
            ( "open",
              -1, cppu::UnoType<ucb::OpenCommandArgument2>::get() ),

            // Mandatory CMIS-only commands
            ucb::CommandInfo ( "checkout", -1, cppu::UnoType<void>::get() ),
            ucb::CommandInfo ( "cancelCheckout", -1, cppu::UnoType<void>::get() ),
            ucb::CommandInfo ( "checkIn", -1,
                    cppu::UnoType<ucb::TransferInfo>::get() ),
            ucb::CommandInfo ( "updateProperties", -1, cppu::UnoType<void>::get() ),
            ucb::CommandInfo
            ( "getAllVersions",
              -1, cppu::UnoType<uno::Sequence< document::CmisVersion >>::get() ),


            // Folder Only, omitted if not a folder
            ucb::CommandInfo
            ( "transfer",
              -1, cppu::UnoType<ucb::TransferInfo>::get() ),
            ucb::CommandInfo
            ( "createNewContent",
              -1, cppu::UnoType<ucb::ContentInfo>::get() )
        };

        const int nProps = SAL_N_ELEMENTS( aCommandInfoTable );
        return uno::Sequence< ucb::CommandInfo >(aCommandInfoTable, isFolder( xEnv ) ? nProps : nProps - 2);
    }

    OUString Content::getParentURL( )
    {
        SAL_INFO( "ucb.ucp.cmis", "Content::getParentURL()" );
        OUString parentUrl = "/";
        if ( m_sObjectPath == "/" )
            return parentUrl;
        else
        {
            INetURLObject aUrl( m_sURL );
            if ( aUrl.getSegmentCount( ) > 0 )
            {
                URL aCmisUrl( m_sURL );
                aUrl.removeSegment( );
                aCmisUrl.setObjectPath( aUrl.GetURLPath( INetURLObject::DecodeMechanism::WithCharset ) );
                parentUrl = aCmisUrl.asString( );
            }
        }
        return parentUrl;
    }

    XTYPEPROVIDER_COMMON_IMPL( Content );

    void SAL_CALL Content::acquire() throw()
    {
        ContentImplHelper::acquire();
    }

    void SAL_CALL Content::release() throw()
    {
        ContentImplHelper::release();
    }

    uno::Any SAL_CALL Content::queryInterface( const uno::Type & rType )
    {
        uno::Any aRet = cppu::queryInterface( rType, static_cast< ucb::XContentCreator * >( this ) );
        return aRet.hasValue() ? aRet : ContentImplHelper::queryInterface(rType);
    }

    OUString SAL_CALL Content::getImplementationName()
    {
       return "com.sun.star.comp.CmisContent";
    }

    uno::Sequence< OUString > SAL_CALL Content::getSupportedServiceNames()
    {
           uno::Sequence<OUString> aSNS { "com.sun.star.ucb.CmisContent" };
           return aSNS;
    }

    OUString SAL_CALL Content::getContentType()
    {
        OUString sRet;
        try
        {
            sRet = isFolder( uno::Reference< ucb::XCommandEnvironment >() )
                ? OUStringLiteral(CMIS_FOLDER_TYPE)
                : OUStringLiteral(CMIS_FILE_TYPE);
        }
        catch (const uno::RuntimeException&)
        {
            throw;
        }
        catch (const uno::Exception& e)
        {
            uno::Any a(cppu::getCaughtException());
            throw lang::WrappedTargetRuntimeException(
                "wrapped Exception " + e.Message,
                uno::Reference<uno::XInterface>(), a);
        }
        return sRet;
    }

    uno::Any SAL_CALL Content::execute(
        const ucb::Command& aCommand,
        sal_Int32 /*CommandId*/,
        const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        SAL_INFO( "ucb.ucp.cmis", "Content::execute( ) - " << aCommand.Name );
        uno::Any aRet;

        if ( aCommand.Name == "getPropertyValues" )
        {
            uno::Sequence< beans::Property > Properties;
            if ( !( aCommand.Argument >>= Properties ) )
                ucbhelper::cancelCommandExecution ( getBadArgExcept (), xEnv );
            aRet <<= getPropertyValues( Properties, xEnv );
        }
        else if ( aCommand.Name == "getPropertySetInfo" )
            aRet <<= getPropertySetInfo( xEnv, false );
        else if ( aCommand.Name == "getCommandInfo" )
            aRet <<= getCommandInfo( xEnv, false );
        else if ( aCommand.Name == "open" )
        {
            ucb::OpenCommandArgument2 aOpenCommand;
            if ( !( aCommand.Argument >>= aOpenCommand ) )
                ucbhelper::cancelCommandExecution ( getBadArgExcept (), xEnv );
            aRet = open( aOpenCommand, xEnv );
        }
        else if ( aCommand.Name == "transfer" )
        {
            ucb::TransferInfo transferArgs;
            if ( !( aCommand.Argument >>= transferArgs ) )
                ucbhelper::cancelCommandExecution ( getBadArgExcept (), xEnv );
            transfer( transferArgs, xEnv );
        }
        else if ( aCommand.Name == "setPropertyValues" )
        {
            uno::Sequence< beans::PropertyValue > aProperties;
            if ( !( aCommand.Argument >>= aProperties ) || !aProperties.hasElements() )
                ucbhelper::cancelCommandExecution ( getBadArgExcept (), xEnv );
            aRet <<= setPropertyValues( aProperties, xEnv );
        }
        else if (aCommand.Name == "createNewContent"
                 && isFolder( xEnv ) )
        {
            ucb::ContentInfo arg;
            if ( !( aCommand.Argument >>= arg ) )
                    ucbhelper::cancelCommandExecution ( getBadArgExcept (), xEnv );
            aRet <<= createNewContent( arg );
        }
        else if ( aCommand.Name == "insert" )
        {
            ucb::InsertCommandArgument2 arg;
            if ( !( aCommand.Argument >>= arg ) )
            {
                ucb::InsertCommandArgument insertArg;
                if ( !( aCommand.Argument >>= insertArg ) )
                    ucbhelper::cancelCommandExecution ( getBadArgExcept (), xEnv );

                arg.Data = insertArg.Data;
                arg.ReplaceExisting = insertArg.ReplaceExisting;
            }
            // store the document id
            m_sObjectId = arg.DocumentId;
            insert( arg.Data, arg.ReplaceExisting, arg.MimeType, xEnv );
        }
        else if ( aCommand.Name == "delete" )
        {
            try
            {
                if ( !isFolder( xEnv ) )
                {
                    getObject( xEnv )->remove( );
                }
                else
                {
                    libcmis::Folder* folder = dynamic_cast< libcmis::Folder* >( getObject( xEnv ).get() );
                    if (folder)
                        folder->removeTree( );
                }
            }
            catch ( const libcmis::Exception& e )
            {
                SAL_INFO( "ucb.ucp.cmis", "Unexpected libcmis exception: " << e.what( ) );
                ucbhelper::cancelCommandExecution(
                                    ucb::IOErrorCode_GENERAL,
                                    uno::Sequence< uno::Any >( 0 ),
                                    xEnv,
                                    o3tl::runtimeToOUString(e.what()));
            }
        }
        else if ( aCommand.Name == "checkout" )
        {
            aRet <<= checkOut( xEnv );
        }
        else if ( aCommand.Name == "cancelCheckout" )
        {
            aRet <<= cancelCheckOut( xEnv );
        }
        else if ( aCommand.Name == "checkin" )
        {
            ucb::CheckinArgument aArg;
            if ( !( aCommand.Argument >>= aArg ) )
            {
                ucbhelper::cancelCommandExecution ( getBadArgExcept(), xEnv );
            }
            aRet <<= checkIn( aArg, xEnv );
        }
        else if ( aCommand.Name == "getAllVersions" )
        {
            aRet <<= getAllVersions( xEnv );
        }
        else if ( aCommand.Name == "updateProperties" )
        {
            updateProperties( aCommand.Argument, xEnv );
        }
        else
        {
            SAL_INFO( "ucb.ucp.cmis", "Unknown command to execute" );

            ucbhelper::cancelCommandExecution
                ( uno::makeAny( ucb::UnsupportedCommandException
                  ( OUString(),
                    static_cast< cppu::OWeakObject * >( this ) ) ),
                  xEnv );
        }

        return aRet;
    }

    void SAL_CALL Content::abort( sal_Int32 /*CommandId*/ )
    {
        SAL_INFO( "ucb.ucp.cmis", "TODO - Content::abort()" );
        // TODO Implement me
    }

    uno::Sequence< ucb::ContentInfo > SAL_CALL Content::queryCreatableContentsInfo()
    {
        return queryCreatableContentsInfo( uno::Reference< ucb::XCommandEnvironment >() );
    }

    uno::Reference< ucb::XContent > SAL_CALL Content::createNewContent(
            const ucb::ContentInfo& Info )
    {
        bool create_document;

        if ( Info.Type == CMIS_FILE_TYPE )
            create_document = true;
        else if ( Info.Type == CMIS_FOLDER_TYPE )
            create_document = false;
        else
        {
            SAL_INFO( "ucb.ucp.cmis", "Unknown type of content to create" );
            return uno::Reference< ucb::XContent >();
        }

        OUString sParentURL = m_xIdentifier->getContentIdentifier();

        // Set the parent URL for the transient objects
        uno::Reference< ucb::XContentIdentifier > xId(new ::ucbhelper::ContentIdentifier(sParentURL));

        try
        {
            return new ::cmis::Content( m_xContext, m_pProvider, xId, !create_document );
        }
        catch ( ucb::ContentCreationException & )
        {
            return uno::Reference< ucb::XContent >();
        }
    }

    uno::Sequence< uno::Type > SAL_CALL Content::getTypes()
    {
        try
        {
            if ( isFolder( uno::Reference< ucb::XCommandEnvironment >() ) )
            {
                static cppu::OTypeCollection s_aFolderCollection
                    (CPPU_TYPE_REF( lang::XTypeProvider ),
                     CPPU_TYPE_REF( lang::XServiceInfo ),
                     CPPU_TYPE_REF( lang::XComponent ),
                     CPPU_TYPE_REF( ucb::XContent ),
                     CPPU_TYPE_REF( ucb::XCommandProcessor ),
                     CPPU_TYPE_REF( beans::XPropertiesChangeNotifier ),
                     CPPU_TYPE_REF( ucb::XCommandInfoChangeNotifier ),
                     CPPU_TYPE_REF( beans::XPropertyContainer ),
                     CPPU_TYPE_REF( beans::XPropertySetInfoChangeNotifier ),
                     CPPU_TYPE_REF( container::XChild ),
                     CPPU_TYPE_REF( ucb::XContentCreator ) );
                return s_aFolderCollection.getTypes();
            }
        }
        catch (const uno::RuntimeException&)
        {
            throw;
        }
        catch (const uno::Exception& e)
        {
            uno::Any a(cppu::getCaughtException());
            throw lang::WrappedTargetRuntimeException(
                "wrapped Exception " + e.Message,
                uno::Reference<uno::XInterface>(), a);
        }

        static cppu::OTypeCollection s_aFileCollection
            (CPPU_TYPE_REF( lang::XTypeProvider ),
             CPPU_TYPE_REF( lang::XServiceInfo ),
             CPPU_TYPE_REF( lang::XComponent ),
             CPPU_TYPE_REF( ucb::XContent ),
             CPPU_TYPE_REF( ucb::XCommandProcessor ),
             CPPU_TYPE_REF( beans::XPropertiesChangeNotifier ),
             CPPU_TYPE_REF( ucb::XCommandInfoChangeNotifier ),
             CPPU_TYPE_REF( beans::XPropertyContainer ),
             CPPU_TYPE_REF( beans::XPropertySetInfoChangeNotifier ),
             CPPU_TYPE_REF( container::XChild ) );

        return s_aFileCollection.getTypes();
    }

    uno::Sequence< ucb::ContentInfo > Content::queryCreatableContentsInfo(
        const uno::Reference< ucb::XCommandEnvironment >& xEnv)
    {
        try
        {
            if ( isFolder( xEnv ) )
            {
                uno::Sequence< ucb::ContentInfo > seq(2);

                // Minimum set of props we really need
                uno::Sequence< beans::Property > props( 1 );
                props[0] = beans::Property(
                    "Title",
                    -1,
                    cppu::UnoType<OUString>::get(),
                    beans::PropertyAttribute::MAYBEVOID | beans::PropertyAttribute::BOUND );

                // file
                seq[0].Type       =  CMIS_FILE_TYPE;
                seq[0].Attributes = ( ucb::ContentInfoAttribute::INSERT_WITH_INPUTSTREAM |
                                      ucb::ContentInfoAttribute::KIND_DOCUMENT );
                seq[0].Properties = props;

                // folder
                seq[1].Type       = CMIS_FOLDER_TYPE;
                seq[1].Attributes = ucb::ContentInfoAttribute::KIND_FOLDER;
                seq[1].Properties = props;

                return seq;
            }
        }
        catch (const uno::RuntimeException&)
        {
            throw;
        }
        catch (const uno::Exception& e)
        {
            uno::Any a(cppu::getCaughtException());
            throw lang::WrappedTargetRuntimeException(
                "wrapped Exception " + e.Message,
                uno::Reference<uno::XInterface>(), a);
        }
        return uno::Sequence< ucb::ContentInfo >();
    }

    std::vector< uno::Reference< ucb::XContent > > Content::getChildren( )
    {
        std::vector< uno::Reference< ucb::XContent > > results;
        SAL_INFO( "ucb.ucp.cmis", "Content::getChildren() " << m_sURL );

        libcmis::FolderPtr pFolder = boost::dynamic_pointer_cast< libcmis::Folder >( getObject( uno::Reference< ucb::XCommandEnvironment >() ) );
        if ( nullptr != pFolder )
        {
            // Get the children from pObject
            try
            {
                vector< libcmis::ObjectPtr > children = pFolder->getChildren( );

                // Loop over the results
                for ( const auto& rChild : children )
                {
                    // TODO Cache the objects

                    INetURLObject aURL( m_sURL );
                    OUString sUser = aURL.GetUser( INetURLObject::DecodeMechanism::WithCharset );

                    URL aUrl( m_sURL );
                    OUString sPath( m_sObjectPath );
                    if ( !sPath.endsWith("/") )
                        sPath += "/";
                    sPath += STD_TO_OUSTR( rChild->getName( ) );
                    OUString sId = STD_TO_OUSTR( rChild->getId( ) );

                    aUrl.setObjectId( sId );
                    aUrl.setObjectPath( sPath );
                    aUrl.setUsername( sUser );

                    uno::Reference< ucb::XContentIdentifier > xId = new ucbhelper::ContentIdentifier( aUrl.asString( ) );
                    uno::Reference< ucb::XContent > xContent = new Content( m_xContext, m_pProvider, xId, rChild );

                    results.push_back( xContent );
                }
            }
            catch ( const libcmis::Exception& e )
            {
                SAL_INFO( "ucb.ucp.cmis", "Exception thrown: " << e.what() );
            }
        }

        return results;
    }

    void Content::setCmisProperty(const std::string& rName, const std::string& rValue, const uno::Reference< ucb::XCommandEnvironment >& xEnv )
    {
        if ( getObjectType( xEnv ).get( ) )
        {
            map< string, libcmis::PropertyPtr >::iterator propIt = m_pObjectProps.find(rName);
            vector< string > values;
            values.push_back(rValue);

            if ( propIt == m_pObjectProps.end( ) && getObjectType( xEnv ).get( ) )
            {
                map< string, libcmis::PropertyTypePtr > propsTypes = getObjectType( xEnv )->getPropertiesTypes( );
                map< string, libcmis::PropertyTypePtr >::iterator typeIt = propsTypes.find(rName);

                if ( typeIt != propsTypes.end( ) )
                {
                    libcmis::PropertyTypePtr propType = typeIt->second;
                    libcmis::PropertyPtr property( new libcmis::Property( propType, values ) );
                    m_pObjectProps.insert(pair< string, libcmis::PropertyPtr >(rName, property));
                }
            }
            else if ( propIt != m_pObjectProps.end( ) )
            {
                propIt->second->setValues( values );
            }
        }
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */