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
/* -*- 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/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <commonembobj.hxx>
#include <com/sun/star/embed/Aspects.hpp>
#include <com/sun/star/document/XStorageBasedDocument.hpp>
#include <com/sun/star/embed/EmbedStates.hpp>
#include <com/sun/star/embed/EntryInitModes.hpp>
#include <com/sun/star/embed/StorageWrappedTargetException.hpp>
#include <com/sun/star/embed/WrongStateException.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/embed/XOptimizedStorage.hpp>
#include <com/sun/star/embed/ElementModes.hpp>
#include <com/sun/star/embed/EmbedUpdateModes.hpp>
#include <com/sun/star/embed/StorageFactory.hpp>
#include <com/sun/star/io/IOException.hpp>
#include <com/sun/star/io/TempFile.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/frame/XLoadable.hpp>
#include <com/sun/star/frame/XModule.hpp>
#include <com/sun/star/lang/NoSupportException.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <com/sun/star/util/XModifiable.hpp>

#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XChild.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/IllegalTypeException.hpp>
#include <com/sun/star/chart2/XChartDocument.hpp>

#include <comphelper/fileformat.h>
#include <comphelper/storagehelper.hxx>
#include <comphelper/mimeconfighelper.hxx>
#include <comphelper/namedvaluecollection.hxx>

#include <tools/diagnose_ex.h>
#include <sal/log.hxx>
#include <unotools/configmgr.hxx>
#include "persistence.hxx"

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


uno::Sequence< beans::PropertyValue > GetValuableArgs_Impl( const uno::Sequence< beans::PropertyValue >& aMedDescr,
                                                            bool bCanUseDocumentBaseURL )
{
    uno::Sequence< beans::PropertyValue > aResult;
    sal_Int32 nResLen = 0;

    for ( beans::PropertyValue const & prop : aMedDescr )
    {
        if ( prop.Name == "ComponentData" || prop.Name == "DocumentTitle"
          || prop.Name == "InteractionHandler" || prop.Name == "JumpMark"
          // || prop.Name == "Password" // makes no sense for embedded objects
          || prop.Name == "Preview" || prop.Name == "ReadOnly"
          || prop.Name == "StartPresentation" || prop.Name == "RepairPackage"
          || prop.Name == "StatusIndicator" || prop.Name == "ViewData"
          || prop.Name == "ViewId" || prop.Name == "MacroExecutionMode"
          || prop.Name == "UpdateDocMode"
          || (prop.Name == "DocumentBaseURL" && bCanUseDocumentBaseURL) )
        {
            aResult.realloc( ++nResLen );
            aResult[nResLen-1] = prop;
        }
    }

    return aResult;
}


static uno::Sequence< beans::PropertyValue > addAsTemplate( const uno::Sequence< beans::PropertyValue >& aOrig )
{
    bool bAsTemplateSet = false;
    sal_Int32 nLength = aOrig.getLength();
    uno::Sequence< beans::PropertyValue > aResult( nLength );

    for ( sal_Int32 nInd = 0; nInd < nLength; nInd++ )
    {
        aResult[nInd].Name = aOrig[nInd].Name;
        if ( aResult[nInd].Name == "AsTemplate" )
        {
            aResult[nInd].Value <<= true;
            bAsTemplateSet = true;
        }
        else
            aResult[nInd].Value = aOrig[nInd].Value;
    }

    if ( !bAsTemplateSet )
    {
        aResult.realloc( nLength + 1 );
        aResult[nLength].Name = "AsTemplate";
        aResult[nLength].Value <<= true;
    }

    return aResult;
}


static uno::Reference< io::XInputStream > createTempInpStreamFromStor(
                                                            const uno::Reference< embed::XStorage >& xStorage,
                                                            const uno::Reference< uno::XComponentContext >& xContext )
{
    SAL_WARN_IF( !xStorage.is(), "embeddedobj.common", "The storage can not be empty!" );

    uno::Reference< io::XInputStream > xResult;

    uno::Reference < io::XStream > xTempStream( io::TempFile::create(xContext), uno::UNO_QUERY_THROW );

    uno::Reference < lang::XSingleServiceFactory > xStorageFactory( embed::StorageFactory::create(xContext) );

    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[0] <<= xTempStream;
    aArgs[1] <<= embed::ElementModes::READWRITE;
    uno::Reference< embed::XStorage > xTempStorage( xStorageFactory->createInstanceWithArguments( aArgs ),
                                                    uno::UNO_QUERY_THROW );

    try
    {
        xStorage->copyToStorage( xTempStorage );
    } catch( const uno::Exception& )
    {
        css::uno::Any anyEx = cppu::getCaughtException();
        throw embed::StorageWrappedTargetException(
                    "Can't copy storage!",
                    uno::Reference< uno::XInterface >(),
                    anyEx );
    }

    try {
        if ( xTempStorage.is() )
            xTempStorage->dispose();
    }
    catch ( const uno::Exception& )
    {
    }

    try {
        uno::Reference< io::XOutputStream > xTempOut = xTempStream->getOutputStream();
        if ( xTempOut.is() )
            xTempOut->closeOutput();
    }
    catch ( const uno::Exception& )
    {
    }

    xResult = xTempStream->getInputStream();

    return xResult;

}


static void TransferMediaType( const uno::Reference< embed::XStorage >& i_rSource, const uno::Reference< embed::XStorage >& i_rTarget )
{
    try
    {
        const uno::Reference< beans::XPropertySet > xSourceProps( i_rSource, uno::UNO_QUERY_THROW );
        const uno::Reference< beans::XPropertySet > xTargetProps( i_rTarget, uno::UNO_QUERY_THROW );
        const OUString sMediaTypePropName( "MediaType" );
        xTargetProps->setPropertyValue( sMediaTypePropName, xSourceProps->getPropertyValue( sMediaTypePropName ) );
    }
    catch( const uno::Exception& )
    {
        DBG_UNHANDLED_EXCEPTION("embeddedobj.common");
    }
}


static uno::Reference< util::XCloseable > CreateDocument( const uno::Reference< uno::XComponentContext >& _rxContext,
    const OUString& _rDocumentServiceName, bool _bEmbeddedScriptSupport, const bool i_bDocumentRecoverySupport )
{
    ::comphelper::NamedValueCollection aArguments;
    aArguments.put( "EmbeddedObject", true );
    aArguments.put( "EmbeddedScriptSupport", _bEmbeddedScriptSupport );
    aArguments.put( "DocumentRecoverySupport", i_bDocumentRecoverySupport );

    uno::Reference< uno::XInterface > xDocument;
    try
    {
        xDocument = _rxContext->getServiceManager()->createInstanceWithArgumentsAndContext(
                        _rDocumentServiceName, aArguments.getWrappedPropertyValues(), _rxContext );
    }
    catch( const uno::Exception& )
    {
        // if an embedded object implementation does not support XInitialization,
        // the default factory from cppuhelper will throw an
        // IllegalArgumentException when we try to create the instance with arguments.
        // Okay, so we fall back to creating the instance without any arguments.
        OSL_FAIL("Consider implementing interface XInitialization to avoid duplicate construction");
        xDocument = _rxContext->getServiceManager()->createInstanceWithContext( _rDocumentServiceName, _rxContext );
    }

    SAL_WARN_IF(!xDocument.is(), "embeddedobj.common", "Service " << _rDocumentServiceName << " is not available?");
    return uno::Reference< util::XCloseable >( xDocument, uno::UNO_QUERY );
}


static void SetDocToEmbedded( const uno::Reference< frame::XModel >& rDocument, const OUString& aModuleName )
{
    if (!rDocument.is())
        return;

    uno::Sequence< beans::PropertyValue > aSeq( 1 );
    aSeq[0].Name = "SetEmbedded";
    aSeq[0].Value <<= true;
    rDocument->attachResource( OUString(), aSeq );

    if ( !aModuleName.isEmpty() )
    {
        try
        {
            uno::Reference< frame::XModule > xModule( rDocument, uno::UNO_QUERY_THROW );
            xModule->setIdentifier( aModuleName );
        }
        catch( const uno::Exception& )
        {}
    }
}


void OCommonEmbeddedObject::SwitchOwnPersistence( const uno::Reference< embed::XStorage >& xNewParentStorage,
                                                  const uno::Reference< embed::XStorage >& xNewObjectStorage,
                                                  const OUString& aNewName )
{
    if ( xNewParentStorage == m_xParentStorage && aNewName == m_aEntryName )
    {
        SAL_WARN_IF( xNewObjectStorage != m_xObjectStorage, "embeddedobj.common", "The storage must be the same!" );
        return;
    }

    auto xOldObjectStorage = m_xObjectStorage;
    m_xObjectStorage = xNewObjectStorage;
    m_xParentStorage = xNewParentStorage;
    m_aEntryName = aNewName;

    // the linked document should not be switched
    if ( !m_bIsLink )
    {
        uno::Reference< document::XStorageBasedDocument > xDoc( m_xDocHolder->GetComponent(), uno::UNO_QUERY );
        if ( xDoc.is() )
            SwitchDocToStorage_Impl( xDoc, m_xObjectStorage );
    }

    try {
        if ( xOldObjectStorage.is() )
            xOldObjectStorage->dispose();
    }
    catch ( const uno::Exception& )
    {
    }
}


void OCommonEmbeddedObject::SwitchOwnPersistence( const uno::Reference< embed::XStorage >& xNewParentStorage,
                                                  const OUString& aNewName )
{
    if ( xNewParentStorage == m_xParentStorage && aNewName == m_aEntryName )
        return;

    sal_Int32 nStorageMode = m_bReadOnly ? embed::ElementModes::READ : embed::ElementModes::READWRITE;

    uno::Reference< embed::XStorage > xNewOwnStorage = xNewParentStorage->openStorageElement( aNewName, nStorageMode );
    SAL_WARN_IF( !xNewOwnStorage.is(), "embeddedobj.common", "The method can not return empty reference!" );

    SwitchOwnPersistence( xNewParentStorage, xNewOwnStorage, aNewName );
}


void OCommonEmbeddedObject::EmbedAndReparentDoc_Impl( const uno::Reference< util::XCloseable >& i_rxDocument ) const
{
    SetDocToEmbedded( uno::Reference< frame::XModel >( i_rxDocument, uno::UNO_QUERY ), m_aModuleName );

    try
    {
        uno::Reference < container::XChild > xChild( i_rxDocument, uno::UNO_QUERY );
        if ( xChild.is() )
            xChild->setParent( m_xParent );
    }
    catch( const lang::NoSupportException & )
    {
        SAL_WARN( "embeddedobj.common", "OCommonEmbeddedObject::EmbedAndReparentDoc: cannot set parent at document!" );
    }
}


uno::Reference< util::XCloseable > OCommonEmbeddedObject::InitNewDocument_Impl()
{
    uno::Reference< util::XCloseable > xDocument( CreateDocument( m_xContext, GetDocumentServiceName(),
                                                m_bEmbeddedScriptSupport, m_bDocumentRecoverySupport ) );

    uno::Reference< frame::XModel > xModel( xDocument, uno::UNO_QUERY );
    uno::Reference< frame::XLoadable > xLoadable( xModel, uno::UNO_QUERY_THROW );

    try
    {
        // set the document mode to embedded as the first action on document!!!
        EmbedAndReparentDoc_Impl( xDocument );

        // if we have a storage to recover the document from, do not use initNew, but instead load from that storage
        bool bInitNew = true;
        if ( m_xRecoveryStorage.is() )
        {
            uno::Reference< document::XStorageBasedDocument > xDoc( xLoadable, uno::UNO_QUERY );
            SAL_WARN_IF( !xDoc.is(), "embeddedobj.common", "OCommonEmbeddedObject::InitNewDocument_Impl: cannot recover from a storage when the document is not storage based!" );
            if ( xDoc.is() )
            {
                ::comphelper::NamedValueCollection aLoadArgs;
                FillDefaultLoadArgs_Impl( m_xRecoveryStorage, aLoadArgs );

                xDoc->loadFromStorage( m_xRecoveryStorage, aLoadArgs.getPropertyValues() );
                SwitchDocToStorage_Impl( xDoc, m_xObjectStorage );
                bInitNew = false;
            }
        }

        if ( bInitNew )
        {
            // init document as a new
            xLoadable->initNew();
        }
        xModel->attachResource( xModel->getURL(), m_aDocMediaDescriptor );
    }
    catch( const uno::Exception& )
    {
        if ( xDocument.is() )
        {
            try
            {
                xDocument->close( true );
            }
            catch( const uno::Exception& )
            {
            }
        }

        throw; // TODO
    }

    return xDocument;
}


uno::Reference< util::XCloseable > OCommonEmbeddedObject::LoadLink_Impl()
{
    uno::Reference< util::XCloseable > xDocument( CreateDocument( m_xContext, GetDocumentServiceName(),
                                                m_bEmbeddedScriptSupport, m_bDocumentRecoverySupport ) );

    uno::Reference< frame::XLoadable > xLoadable( xDocument, uno::UNO_QUERY_THROW );

    sal_Int32 nLen = 2;
    uno::Sequence< beans::PropertyValue > aArgs( nLen );
    aArgs[0].Name = "URL";
    aArgs[0].Value <<= m_aLinkURL;
    aArgs[1].Name = "FilterName";
    aArgs[1].Value <<= m_aLinkFilterName;
    if ( m_bLinkHasPassword )
    {
        aArgs.realloc( ++nLen );
        aArgs[nLen-1].Name = "Password";
        aArgs[nLen-1].Value <<= m_aLinkPassword;
    }

    aArgs.realloc( m_aDocMediaDescriptor.getLength() + nLen );
    for ( sal_Int32 nInd = 0; nInd < m_aDocMediaDescriptor.getLength(); nInd++ )
    {
        aArgs[nInd+nLen].Name = m_aDocMediaDescriptor[nInd].Name;
        aArgs[nInd+nLen].Value = m_aDocMediaDescriptor[nInd].Value;
    }

    try
    {
        // the document is not really an embedded one, it is a link
        EmbedAndReparentDoc_Impl( xDocument );

        // load the document
        xLoadable->load( aArgs );

        if ( !m_bLinkHasPassword )
        {
            // check if there is a password to cache
            uno::Reference< frame::XModel > xModel( xLoadable, uno::UNO_QUERY_THROW );
            const uno::Sequence< beans::PropertyValue > aProps = xModel->getArgs();
            for ( beans::PropertyValue const & prop : aProps )
                if ( prop.Name == "Password" && ( prop.Value >>= m_aLinkPassword ) )
                {
                    m_bLinkHasPassword = true;
                    break;
                }
        }
    }
    catch( const uno::Exception& )
    {
        if ( xDocument.is() )
        {
            try
            {
                xDocument->close( true );
            }
            catch( const uno::Exception& )
            {
            }
        }

        throw; // TODO
    }

    return xDocument;

}


OUString OCommonEmbeddedObject::GetFilterName( sal_Int32 nVersion ) const
{
    OUString aFilterName = GetPresetFilterName();
    if ( aFilterName.isEmpty() )
    {
        OUString sDocumentServiceName = GetDocumentServiceName();
        if (utl::ConfigManager::IsFuzzing() && nVersion == SOFFICE_FILEFORMAT_CURRENT &&
            sDocumentServiceName == "com.sun.star.chart2.ChartDocument")
        {
            return "chart8";
        }
        try {
            ::comphelper::MimeConfigurationHelper aHelper( m_xContext );
            aFilterName = aHelper.GetDefaultFilterFromServiceName(sDocumentServiceName, nVersion);

            // If no filter is found, fall back to the FileFormatVersion=6200 filter, Base only has that.
            if (aFilterName.isEmpty() && nVersion == SOFFICE_FILEFORMAT_CURRENT)
                aFilterName = aHelper.GetDefaultFilterFromServiceName(GetDocumentServiceName(), SOFFICE_FILEFORMAT_60);
        } catch( const uno::Exception& )
        {}
    }

    return aFilterName;
}


void OCommonEmbeddedObject::FillDefaultLoadArgs_Impl( const uno::Reference< embed::XStorage >& i_rxStorage,
        ::comphelper::NamedValueCollection& o_rLoadArgs ) const
{
    o_rLoadArgs.put( "DocumentBaseURL", GetBaseURL_Impl() );
    o_rLoadArgs.put( "HierarchicalDocumentName", m_aEntryName );
    o_rLoadArgs.put( "ReadOnly", m_bReadOnly );

    OUString aFilterName = GetFilterName( ::comphelper::OStorageHelper::GetXStorageFormat( i_rxStorage ) );
    SAL_WARN_IF( aFilterName.isEmpty(), "embeddedobj.common", "OCommonEmbeddedObject::FillDefaultLoadArgs_Impl: Wrong document service name!" );
    if ( aFilterName.isEmpty() )
        throw io::IOException();    // TODO: error message/code

    o_rLoadArgs.put( "FilterName", aFilterName );
}


uno::Reference< util::XCloseable > OCommonEmbeddedObject::LoadDocumentFromStorage_Impl()
{
    ENSURE_OR_THROW( m_xObjectStorage.is(), "no object storage" );

    const uno::Reference< embed::XStorage > xSourceStorage( m_xRecoveryStorage.is() ? m_xRecoveryStorage : m_xObjectStorage );

    uno::Reference< util::XCloseable > xDocument( CreateDocument( m_xContext, GetDocumentServiceName(),
                                                m_bEmbeddedScriptSupport, m_bDocumentRecoverySupport ) );

    //#i103460# ODF: take the size given from the parent frame as default
    uno::Reference< chart2::XChartDocument > xChart( xDocument, uno::UNO_QUERY );
    if( xChart.is() )
    {
        uno::Reference< embed::XVisualObject > xChartVisualObject( xChart, uno::UNO_QUERY );
        if( xChartVisualObject.is() )
            xChartVisualObject->setVisualAreaSize( embed::Aspects::MSOLE_CONTENT, m_aDefaultSizeForChart_In_100TH_MM );
    }

    uno::Reference< frame::XLoadable > xLoadable( xDocument, uno::UNO_QUERY );
    uno::Reference< document::XStorageBasedDocument > xDoc( xDocument, uno::UNO_QUERY );
    if ( !xDoc.is() && !xLoadable.is() )
        throw uno::RuntimeException();

    ::comphelper::NamedValueCollection aLoadArgs;
    FillDefaultLoadArgs_Impl( xSourceStorage, aLoadArgs );

    uno::Reference< io::XInputStream > xTempInpStream;
    if ( !xDoc.is() )
    {
        xTempInpStream = createTempInpStreamFromStor( xSourceStorage, m_xContext );
        if ( !xTempInpStream.is() )
            throw uno::RuntimeException();

        OUString aTempFileURL;
        try
        {
            // no need to let the file stay after the stream is removed since the embedded document
            // can not be stored directly
            uno::Reference< beans::XPropertySet > xTempStreamProps( xTempInpStream, uno::UNO_QUERY_THROW );
            xTempStreamProps->getPropertyValue("Uri") >>= aTempFileURL;
        }
        catch( const uno::Exception& )
        {
        }

        SAL_WARN_IF( aTempFileURL.isEmpty(), "embeddedobj.common", "Couldn't retrieve temporary file URL!" );

        aLoadArgs.put( "URL", aTempFileURL );
        aLoadArgs.put( "InputStream", xTempInpStream );
    }


    aLoadArgs.merge( m_aDocMediaDescriptor, true );

    try
    {
        // set the document mode to embedded as the first step!!!
        EmbedAndReparentDoc_Impl( xDocument );

        if ( xDoc.is() )
        {
            xDoc->loadFromStorage( xSourceStorage, aLoadArgs.getPropertyValues() );
            if ( xSourceStorage != m_xObjectStorage )
                SwitchDocToStorage_Impl( xDoc, m_xObjectStorage );
        }
        else
            xLoadable->load( aLoadArgs.getPropertyValues() );
    }
    catch( const uno::Exception& )
    {
        if ( xDocument.is() )
        {
            try
            {
                xDocument->close( true );
            }
            catch( const uno::Exception& )
            {
                DBG_UNHANDLED_EXCEPTION("embeddedobj.common");
            }
        }

        throw; // TODO
    }

    return xDocument;
}


uno::Reference< io::XInputStream > OCommonEmbeddedObject::StoreDocumentToTempStream_Impl(
                                                                            sal_Int32 nStorageFormat,
                                                                            const OUString& aBaseURL,
                                                                            const OUString& aHierarchName )
{
    uno::Reference < io::XOutputStream > xTempOut(
                io::TempFile::create(m_xContext),
                uno::UNO_QUERY_THROW );
    uno::Reference< io::XInputStream > aResult( xTempOut, uno::UNO_QUERY_THROW );

    uno::Reference< frame::XStorable > xStorable;
    {
        osl::MutexGuard aGuard( m_aMutex );
        if ( m_xDocHolder.is() )
            xStorable.set( m_xDocHolder->GetComponent(), uno::UNO_QUERY );
    }

    if( !xStorable.is() )
        throw uno::RuntimeException(); // TODO:

    OUString aFilterName = GetFilterName( nStorageFormat );

    SAL_WARN_IF( aFilterName.isEmpty(), "embeddedobj.common", "Wrong document service name!" );
    if ( aFilterName.isEmpty() )
        throw io::IOException(); // TODO:

    uno::Sequence< beans::PropertyValue > aArgs( 4 );
    aArgs[0].Name = "FilterName";
    aArgs[0].Value <<= aFilterName;
    aArgs[1].Name = "OutputStream";
    aArgs[1].Value <<= xTempOut;
    aArgs[2].Name = "DocumentBaseURL";
    aArgs[2].Value <<= aBaseURL;
    aArgs[3].Name = "HierarchicalDocumentName";
    aArgs[3].Value <<= aHierarchName;

    xStorable->storeToURL( "private:stream", aArgs );
    try
    {
        xTempOut->closeOutput();
    }
    catch( const uno::Exception& )
    {
        SAL_WARN( "embeddedobj.common", "Looks like stream was closed already" );
    }

    return aResult;
}


void OCommonEmbeddedObject::SaveObject_Impl()
{
    if ( !m_xClientSite.is() )
        return;

    try
    {
        // check whether the component is modified,
        // if not there is no need for storing
        uno::Reference< util::XModifiable > xModifiable( m_xDocHolder->GetComponent(), uno::UNO_QUERY );
        if ( xModifiable.is() && !xModifiable->isModified() )
            return;
    }
    catch( const uno::Exception& )
    {}

    try {
        m_xClientSite->saveObject();
    }
    catch( const uno::Exception& )
    {
        SAL_WARN( "embeddedobj.common", "The object was not stored!" );
    }
}


OUString OCommonEmbeddedObject::GetBaseURL_Impl() const
{
    OUString aBaseURL;

    if ( m_xClientSite.is() )
    {
        try
        {
            uno::Reference< frame::XModel > xParentModel( m_xClientSite->getComponent(), uno::UNO_QUERY_THROW );
            const uno::Sequence< beans::PropertyValue > aModelProps = xParentModel->getArgs();
            for ( beans::PropertyValue const & prop : aModelProps )
                if ( prop.Name == "DocumentBaseURL" )
                {<--- Consider using std::find_if algorithm instead of a raw loop.
                    prop.Value >>= aBaseURL;
                    break;
                }
        }
        catch( const uno::Exception& )
        {}
    }

    if ( aBaseURL.isEmpty() )
    {
        for ( beans::PropertyValue const & prop : m_aDocMediaDescriptor )
            if ( prop.Name == "DocumentBaseURL" )
            {<--- Consider using std::find_if algorithm instead of a raw loop.
                prop.Value >>= aBaseURL;
                break;
            }
    }

    if ( aBaseURL.isEmpty() )
        aBaseURL = m_aDefaultParentBaseURL;

    return aBaseURL;
}


OUString OCommonEmbeddedObject::GetBaseURLFrom_Impl(
                    const uno::Sequence< beans::PropertyValue >& lArguments,
                    const uno::Sequence< beans::PropertyValue >& lObjArgs )
{
    OUString aBaseURL;

    for ( beans::PropertyValue const & prop : lArguments )
        if ( prop.Name == "DocumentBaseURL" )
        {<--- Consider using std::find_if algorithm instead of a raw loop.
            prop.Value >>= aBaseURL;
            break;
        }

    if ( aBaseURL.isEmpty() )
    {
        for ( beans::PropertyValue const & prop : lObjArgs )
            if ( prop.Name == "DefaultParentBaseURL" )
            {<--- Consider using std::find_if algorithm instead of a raw loop.
                prop.Value >>= aBaseURL;
                break;
            }
    }

    return aBaseURL;
}


void OCommonEmbeddedObject::SwitchDocToStorage_Impl( const uno::Reference< document::XStorageBasedDocument >& xDoc, const uno::Reference< embed::XStorage >& xStorage )
{
    xDoc->switchToStorage( xStorage );

    uno::Reference< util::XModifiable > xModif( xDoc, uno::UNO_QUERY );
    if ( xModif.is() )
        xModif->setModified( false );

    if ( m_xRecoveryStorage.is() )
        m_xRecoveryStorage.clear();
}

namespace {

OUString getStringPropertyValue( const uno::Sequence<beans::PropertyValue>& rProps, const OUString& rName )
{
    OUString aStr;

    for (beans::PropertyValue const & prop : rProps)
    {
        if (prop.Name == rName)
        {<--- Consider using std::find_if algorithm instead of a raw loop.
            prop.Value >>= aStr;
            break;
        }
    }

    return aStr;
}

}

void OCommonEmbeddedObject::StoreDocToStorage_Impl(
    const uno::Reference<embed::XStorage>& xStorage,
    const uno::Sequence<beans::PropertyValue>& rMediaArgs,
    const uno::Sequence<beans::PropertyValue>& rObjArgs,
    sal_Int32 nStorageFormat,
    const OUString& aHierarchName,
    bool bAttachToTheStorage )
{
    SAL_WARN_IF( !xStorage.is(), "embeddedobj.common", "No storage is provided for storing!" );

    if ( !xStorage.is() )
        throw uno::RuntimeException(); // TODO:

    uno::Reference< document::XStorageBasedDocument > xDoc;
    {
        osl::MutexGuard aGuard( m_aMutex );
        if ( m_xDocHolder.is() )
            xDoc.set( m_xDocHolder->GetComponent(), uno::UNO_QUERY );
    }

    OUString aBaseURL = GetBaseURLFrom_Impl(rMediaArgs, rObjArgs);

    if ( xDoc.is() )
    {
        OUString aFilterName = GetFilterName( nStorageFormat );

        // No filter found? Try the older format, e.g. Base has only that.
        if (aFilterName.isEmpty() && nStorageFormat == SOFFICE_FILEFORMAT_CURRENT)
            aFilterName = GetFilterName( SOFFICE_FILEFORMAT_60 );

        SAL_WARN_IF( aFilterName.isEmpty(), "embeddedobj.common", "Wrong document service name!" );
        if ( aFilterName.isEmpty() )
            throw io::IOException(); // TODO:

        uno::Sequence<beans::PropertyValue> aArgs(5);
        aArgs[0].Name = "FilterName";
        aArgs[0].Value <<= aFilterName;
        aArgs[1].Name = "HierarchicalDocumentName";
        aArgs[1].Value <<= aHierarchName;
        aArgs[2].Name = "DocumentBaseURL";
        aArgs[2].Value <<= aBaseURL;
        aArgs[3].Name = "SourceShellID";
        aArgs[3].Value <<= getStringPropertyValue(rObjArgs, "SourceShellID");
        aArgs[4].Name = "DestinationShellID";
        aArgs[4].Value <<= getStringPropertyValue(rObjArgs, "DestinationShellID");

        xDoc->storeToStorage( xStorage, aArgs );
        if ( bAttachToTheStorage )
            SwitchDocToStorage_Impl( xDoc, xStorage );
    }
    else
    {
        // store document to temporary stream based on temporary file
        uno::Reference < io::XInputStream > xTempIn = StoreDocumentToTempStream_Impl( nStorageFormat, aBaseURL, aHierarchName );

        SAL_WARN_IF( !xTempIn.is(), "embeddedobj.common", "The stream reference can not be empty!" );

        // open storage based on document temporary file for reading
        uno::Reference < lang::XSingleServiceFactory > xStorageFactory = embed::StorageFactory::create(m_xContext);

        uno::Sequence< uno::Any > aArgs(1);
        aArgs[0] <<= xTempIn;
        uno::Reference< embed::XStorage > xTempStorage( xStorageFactory->createInstanceWithArguments( aArgs ),
                                                            uno::UNO_QUERY_THROW );

        // object storage must be committed automatically
        xTempStorage->copyToStorage( xStorage );
    }
}


uno::Reference< util::XCloseable > OCommonEmbeddedObject::CreateDocFromMediaDescr_Impl(
                                        const uno::Sequence< beans::PropertyValue >& aMedDescr )
{
    uno::Reference< util::XCloseable > xDocument( CreateDocument( m_xContext, GetDocumentServiceName(),
                                                m_bEmbeddedScriptSupport, m_bDocumentRecoverySupport ) );

    uno::Reference< frame::XLoadable > xLoadable( xDocument, uno::UNO_QUERY_THROW );

    try
    {
        // set the document mode to embedded as the first action on the document!!!
        EmbedAndReparentDoc_Impl( xDocument );

        xLoadable->load( addAsTemplate( aMedDescr ) );
    }
    catch( const uno::Exception& )
    {
        if ( xDocument.is() )
        {
            try
            {
                xDocument->close( true );
            }
            catch( const uno::Exception& )
            {
            }
        }

        throw; // TODO
    }

    return xDocument;
}


uno::Reference< util::XCloseable > OCommonEmbeddedObject::CreateTempDocFromLink_Impl()
{
    uno::Reference< util::XCloseable > xResult;

    SAL_WARN_IF( !m_bIsLink, "embeddedobj.common", "The object is not a linked one!" );

    uno::Sequence< beans::PropertyValue > aTempMediaDescr;

    sal_Int32 nStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
    try {
        nStorageFormat = ::comphelper::OStorageHelper::GetXStorageFormat( m_xParentStorage );
    }
    catch ( const beans::IllegalTypeException& )
    {
        // the container just has an unknown type, use current file format
    }
    catch ( const uno::Exception& )
    {
        SAL_WARN( "embeddedobj.common", "Can not retrieve storage media type!" );
    }

    if ( m_xDocHolder->GetComponent().is() )
    {
        aTempMediaDescr.realloc( 4 );

        // TODO/LATER: may be private:stream should be used as target URL
        OUString aTempFileURL;
        uno::Reference< io::XInputStream > xTempStream = StoreDocumentToTempStream_Impl( SOFFICE_FILEFORMAT_CURRENT,
                                                                                         OUString(),
                                                                                         OUString() );
        try
        {
            // no need to let the file stay after the stream is removed since the embedded document
            // can not be stored directly
            uno::Reference< beans::XPropertySet > xTempStreamProps( xTempStream, uno::UNO_QUERY_THROW );
            xTempStreamProps->getPropertyValue("Uri") >>= aTempFileURL;
        }
        catch( const uno::Exception& )
        {
        }

        SAL_WARN_IF( aTempFileURL.isEmpty(), "embeddedobj.common", "Couldn't retrieve temporary file URL!" );

        aTempMediaDescr[0].Name = "URL";
        aTempMediaDescr[0].Value <<= aTempFileURL;
        aTempMediaDescr[1].Name = "InputStream";
        aTempMediaDescr[1].Value <<= xTempStream;
        aTempMediaDescr[2].Name = "FilterName";
        aTempMediaDescr[2].Value <<= GetFilterName( nStorageFormat );
        aTempMediaDescr[3].Name = "AsTemplate";
        aTempMediaDescr[3].Value <<= true;
    }
    else
    {
        aTempMediaDescr.realloc( 2 );
        aTempMediaDescr[0].Name = "URL";
        aTempMediaDescr[0].Value <<= m_aLinkURL;
        aTempMediaDescr[1].Name = "FilterName";
        aTempMediaDescr[1].Value <<= m_aLinkFilterName;
    }

    xResult = CreateDocFromMediaDescr_Impl( aTempMediaDescr );

    return xResult;
}


void SAL_CALL OCommonEmbeddedObject::setPersistentEntry(
                    const uno::Reference< embed::XStorage >& xStorage,
                    const OUString& sEntName,
                    sal_Int32 nEntryConnectionMode,
                    const uno::Sequence< beans::PropertyValue >& lArguments,
                    const uno::Sequence< beans::PropertyValue >& lObjArgs )
{
    // the type of the object must be already set
    // a kind of typedetection should be done in the factory

    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( "No parent storage is provided!",
                                            static_cast< ::cppu::OWeakObject* >(this),
                                            1 );

    if ( sEntName.isEmpty() )
        throw lang::IllegalArgumentException( "Empty element name is provided!",
                                            static_cast< ::cppu::OWeakObject* >(this),
                                            2 );

    // May be LOADED should be forbidden here ???
    if ( ( m_nObjectState != -1 || nEntryConnectionMode == embed::EntryInitModes::NO_INIT )
      && ( m_nObjectState == -1 || nEntryConnectionMode != embed::EntryInitModes::NO_INIT ) )
    {
        // if the object is not loaded
        // it can not get persistent representation without initialization

        // if the object is loaded
        // it can switch persistent representation only without initialization

        throw embed::WrongStateException(
                    "Can't change persistent representation of activated object!",
                     static_cast< ::cppu::OWeakObject* >(this) );
    }

    if ( m_bWaitSaveCompleted )
    {
        if ( nEntryConnectionMode != embed::EntryInitModes::NO_INIT )
            throw embed::WrongStateException(
                        "The object waits for saveCompleted() call!",
                        static_cast< ::cppu::OWeakObject* >(this) );
        // saveCompleted is expected, handle it accordingly
        if ( m_xNewParentStorage == xStorage && m_aNewEntryName == sEntName )
        {
            saveCompleted( true );
            return;
        }

        // if a completely different entry is provided, switch first back to the old persistence in saveCompleted
        // and then switch to the target persistence
        bool bSwitchFurther = ( m_xParentStorage != xStorage || m_aEntryName != sEntName );
        saveCompleted( false );
        if ( !bSwitchFurther )
            return;
    }

    // for now support of this interface is required to allow breaking of links and converting them to normal embedded
    // objects, so the persist name must be handled correctly ( althowgh no real persist entry is used )
    // OSL_ENSURE( !m_bIsLink, "This method implementation must not be used for links!" );
    if ( m_bIsLink )
    {
        m_aEntryName = sEntName;
        return;
    }

    uno::Reference< container::XNameAccess > xNameAccess( xStorage, uno::UNO_QUERY_THROW );

    // detect entry existence
    bool bElExists = xNameAccess->hasByName( sEntName );

    m_aDocMediaDescriptor = GetValuableArgs_Impl( lArguments,
                                                  nEntryConnectionMode != embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT );

    m_bReadOnly = false;
    for ( beans::PropertyValue const & prop : lArguments )
        if ( prop.Name == "ReadOnly" )
            prop.Value >>= m_bReadOnly;

    // TODO: use lObjArgs for StoreVisualReplacement
    for ( beans::PropertyValue const & prop : lObjArgs )
        if ( prop.Name == "OutplaceDispatchInterceptor" )
        {
            uno::Reference< frame::XDispatchProviderInterceptor > xDispatchInterceptor;
            if ( prop.Value >>= xDispatchInterceptor )
                m_xDocHolder->SetOutplaceDispatchInterceptor( xDispatchInterceptor );
        }
        else if ( prop.Name == "DefaultParentBaseURL" )
        {
            prop.Value >>= m_aDefaultParentBaseURL;
        }
        else if ( prop.Name == "Parent" )
        {
            prop.Value >>= m_xParent;
        }
        else if ( prop.Name == "IndividualMiscStatus" )
        {
            sal_Int64 nMiscStatus=0;
            prop.Value >>= nMiscStatus;
            m_nMiscStatus |= nMiscStatus;
        }
        else if ( prop.Name == "CloneFrom" )
        {
            uno::Reference < embed::XEmbeddedObject > xObj;
            prop.Value >>= xObj;
            if ( xObj.is() )
            {
                m_bHasClonedSize = true;
                m_aClonedSize = xObj->getVisualAreaSize( embed::Aspects::MSOLE_CONTENT );
                m_nClonedMapUnit = xObj->getMapUnit( embed::Aspects::MSOLE_CONTENT );
            }
        }
        else if ( prop.Name == "OutplaceFrameProperties" )
        {
            uno::Sequence< uno::Any > aOutFrameProps;
            uno::Sequence< beans::NamedValue > aOutFramePropsTyped;
            if ( prop.Value >>= aOutFrameProps )
            {
                m_xDocHolder->SetOutplaceFrameProperties( aOutFrameProps );
            }
            else if ( prop.Value >>= aOutFramePropsTyped )
            {
                aOutFrameProps.realloc( aOutFramePropsTyped.getLength() );
                uno::Any* pProp = aOutFrameProps.getArray();
                for (   const beans::NamedValue* pTypedProp = aOutFramePropsTyped.getConstArray();
                        pTypedProp != aOutFramePropsTyped.getConstArray() + aOutFramePropsTyped.getLength();
                        ++pTypedProp, ++pProp
                    )
                {
                    *pProp <<= *pTypedProp;
                }
                m_xDocHolder->SetOutplaceFrameProperties( aOutFrameProps );
            }
            else
                SAL_WARN( "embeddedobj.common", "OCommonEmbeddedObject::setPersistentEntry: illegal type for argument 'OutplaceFrameProperties'!" );
        }
        else if ( prop.Name == "ModuleName" )
        {
            prop.Value >>= m_aModuleName;
        }
        else if ( prop.Name == "EmbeddedScriptSupport" )
        {
            OSL_VERIFY( prop.Value >>= m_bEmbeddedScriptSupport );
        }
        else if ( prop.Name == "DocumentRecoverySupport" )
        {
            OSL_VERIFY( prop.Value >>= m_bDocumentRecoverySupport );
        }
        else if ( prop.Name == "RecoveryStorage" )
        {
            OSL_VERIFY( prop.Value >>= m_xRecoveryStorage );
        }


    sal_Int32 nStorageMode = m_bReadOnly ? embed::ElementModes::READ : embed::ElementModes::READWRITE;

    SwitchOwnPersistence( xStorage, sEntName );

    if ( nEntryConnectionMode == embed::EntryInitModes::DEFAULT_INIT )
    {
        if ( bElExists )
        {
            // the initialization from existing storage allows to leave object in loaded state
            m_nObjectState = embed::EmbedStates::LOADED;
        }
        else
        {
            m_xDocHolder->SetComponent( InitNewDocument_Impl(), m_bReadOnly );
            if ( !m_xDocHolder->GetComponent().is() )
                throw io::IOException(); // TODO: can not create document

            m_nObjectState = embed::EmbedStates::RUNNING;
        }
    }
    else
    {
        if ( ( nStorageMode & embed::ElementModes::READWRITE ) != embed::ElementModes::READWRITE )
            throw io::IOException();

        if ( nEntryConnectionMode == embed::EntryInitModes::NO_INIT )
        {
            // the document just already changed its storage to store to
            // the links to OOo documents for now ignore this call
            // TODO: OOo links will have persistence so it will be switched here
        }
        else if ( nEntryConnectionMode == embed::EntryInitModes::TRUNCATE_INIT )
        {
            if ( m_xRecoveryStorage.is() )
                TransferMediaType( m_xRecoveryStorage, m_xObjectStorage );

            // TODO:
            m_xDocHolder->SetComponent( InitNewDocument_Impl(), m_bReadOnly );

            if ( !m_xDocHolder->GetComponent().is() )
                throw io::IOException(); // TODO: can not create document

            m_nObjectState = embed::EmbedStates::RUNNING;
        }
        else if ( nEntryConnectionMode == embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT )
        {
            m_xDocHolder->SetComponent( CreateDocFromMediaDescr_Impl( lArguments ), m_bReadOnly );
            m_nObjectState = embed::EmbedStates::RUNNING;
        }
        //else if ( nEntryConnectionMode == embed::EntryInitModes::TRANSFERABLE_INIT )
        //{
            //TODO:
        //}
        else
            throw lang::IllegalArgumentException( "Wrong connection mode is provided!",
                                        static_cast< ::cppu::OWeakObject* >(this),
                                        3 );
    }
}


void SAL_CALL OCommonEmbeddedObject::storeToEntry( const uno::Reference< embed::XStorage >& xStorage,
                            const OUString& sEntName,
                            const uno::Sequence< beans::PropertyValue >& lArguments,
                            const uno::Sequence< beans::PropertyValue >& lObjArgs )
{
    ::osl::ResettableMutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_nObjectState == -1 )
    {
        // the object is still not loaded
        throw embed::WrongStateException( "Can't store object without persistence!",
                                        static_cast< ::cppu::OWeakObject* >(this) );
    }

    if ( m_bWaitSaveCompleted )
        throw embed::WrongStateException(
                    "The object waits for saveCompleted() call!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    // for now support of this interface is required to allow breaking of links and converting them to normal embedded
    // objects, so the persist name must be handled correctly ( althowgh no real persist entry is used )
    // OSL_ENSURE( !m_bIsLink, "This method implementation must not be used for links!" );
    if ( m_bIsLink )
        return;

    OSL_ENSURE( m_xParentStorage.is() && m_xObjectStorage.is(), "The object has no valid persistence!" );

    sal_Int32 nTargetStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
    sal_Int32 nOriginalStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
    try {
        nTargetStorageFormat = ::comphelper::OStorageHelper::GetXStorageFormat( xStorage );
    }
    catch ( const beans::IllegalTypeException& )
    {
        // the container just has an unknown type, use current file format
    }
    catch ( const uno::Exception& )
    {
        SAL_WARN( "embeddedobj.common", "Can not retrieve target storage media type!" );
    }
    if (nTargetStorageFormat == SOFFICE_FILEFORMAT_60)
    {
        SAL_INFO("embeddedobj.common", "fdo#78159: Storing OOoXML as ODF");
        nTargetStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
        // setting MediaType is done later anyway, no need to do it here
    }

    try
    {
        nOriginalStorageFormat = ::comphelper::OStorageHelper::GetXStorageFormat( m_xParentStorage );
    }
    catch ( const beans::IllegalTypeException& )
    {
        // the container just has an unknown type, use current file format
    }
    catch ( const uno::Exception& )
    {
        SAL_WARN( "embeddedobj.common", "Can not retrieve own storage media type!" );
    }

    bool bTryOptimization = false;<--- Assignment 'bTryOptimization=false', assigned value is 0
    for ( beans::PropertyValue const & prop : lObjArgs )
    {
        // StoreVisualReplacement and VisualReplacement args have no sense here
        if ( prop.Name == "CanTryOptimization" )
            prop.Value >>= bTryOptimization;
    }

    bool bSwitchBackToLoaded = false;

    // Storing to different format can be done only in running state.
    if ( m_nObjectState == embed::EmbedStates::LOADED )<--- First condition
    {
        // TODO/LATER: copying is not legal for documents with relative links.
        if ( nTargetStorageFormat == nOriginalStorageFormat )
        {
            bool bOptimizationWorks = false;<--- Assignment 'bOptimizationWorks=false', assigned value is 0
            if ( bTryOptimization )<--- Condition 'bTryOptimization' is always false
            {
                try
                {
                    // try to use optimized copying
                    uno::Reference< embed::XOptimizedStorage > xSource( m_xParentStorage, uno::UNO_QUERY_THROW );
                    uno::Reference< embed::XOptimizedStorage > xTarget( xStorage, uno::UNO_QUERY_THROW );
                    xSource->copyElementDirectlyTo( m_aEntryName, xTarget, sEntName );
                    bOptimizationWorks = true;
                }
                catch( const uno::Exception& )
                {
                }
            }

            if ( !bOptimizationWorks )<--- Condition '!bOptimizationWorks' is always true
                m_xParentStorage->copyElementTo( m_aEntryName, xStorage, sEntName );
        }
        else
        {
            changeState( embed::EmbedStates::RUNNING );
            bSwitchBackToLoaded = true;
        }
    }

    if ( m_nObjectState == embed::EmbedStates::LOADED )<--- Second condition
        return;

    uno::Reference< embed::XStorage > xSubStorage =
                xStorage->openStorageElement( sEntName, embed::ElementModes::READWRITE );

    if ( !xSubStorage.is() )
        throw uno::RuntimeException(); //TODO

    aGuard.clear();
    // TODO/LATER: support hierarchical name for embedded objects in embedded objects
    StoreDocToStorage_Impl(
        xSubStorage, lArguments, lObjArgs, nTargetStorageFormat, sEntName, false );
    aGuard.reset();

    if ( bSwitchBackToLoaded )
        changeState( embed::EmbedStates::LOADED );

    // TODO: should the listener notification be done?
}


void SAL_CALL OCommonEmbeddedObject::storeAsEntry( const uno::Reference< embed::XStorage >& xStorage,
                            const OUString& sEntName,
                            const uno::Sequence< beans::PropertyValue >& lArguments,
                            const uno::Sequence< beans::PropertyValue >& lObjArgs )
{
    // TODO: use lObjArgs

    ::osl::ResettableMutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_nObjectState == -1 )
    {
        // the object is still not loaded
        throw embed::WrongStateException( "Can't store object without persistence!",
                                        static_cast< ::cppu::OWeakObject* >(this) );
    }

    if ( m_bWaitSaveCompleted )
        throw embed::WrongStateException(
                    "The object waits for saveCompleted() call!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    // for now support of this interface is required to allow breaking of links and converting them to normal embedded
    // objects, so the persist name must be handled correctly ( althowgh no real persist entry is used )
    // OSL_ENSURE( !m_bIsLink, "This method implementation must not be used for links!" );
    if ( m_bIsLink )
    {
        m_aNewEntryName = sEntName;
        return;
    }

    OSL_ENSURE( m_xParentStorage.is() && m_xObjectStorage.is(), "The object has no valid persistence!" );

    sal_Int32 nTargetStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
    sal_Int32 nOriginalStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
    try {
        nTargetStorageFormat = ::comphelper::OStorageHelper::GetXStorageFormat( xStorage );
    }
    catch ( const beans::IllegalTypeException& )
    {
        // the container just has an unknown type, use current file format
    }
    catch ( const uno::Exception& )
    {
        SAL_WARN( "embeddedobj.common", "Can not retrieve target storage media type!" );
    }
    if (nTargetStorageFormat == SOFFICE_FILEFORMAT_60)
    {
        SAL_INFO("embeddedobj.common", "fdo#78159: Storing OOoXML as ODF");
        nTargetStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
        // setting MediaType is done later anyway, no need to do it here
    }

    try
    {
        nOriginalStorageFormat = ::comphelper::OStorageHelper::GetXStorageFormat( m_xParentStorage );
    }
    catch ( const beans::IllegalTypeException& )
    {
        // the container just has an unknown type, use current file format
    }
    catch ( const uno::Exception& )
    {
        SAL_WARN( "embeddedobj.common", "Can not retrieve own storage media type!" );
    }

    PostEvent_Impl( "OnSaveAs" );

    bool bTryOptimization = false;<--- Assignment 'bTryOptimization=false', assigned value is 0
    for ( beans::PropertyValue const & prop : lObjArgs )
    {
        // StoreVisualReplacement and VisualReplacement args have no sense here
        if ( prop.Name == "CanTryOptimization" )
            prop.Value >>= bTryOptimization;
    }

    bool bSwitchBackToLoaded = false;

    // Storing to different format can be done only in running state.
    if ( m_nObjectState == embed::EmbedStates::LOADED )
    {
        // TODO/LATER: copying is not legal for documents with relative links.
        if ( nTargetStorageFormat == nOriginalStorageFormat )
        {
            bool bOptimizationWorks = false;<--- Assignment 'bOptimizationWorks=false', assigned value is 0
            if ( bTryOptimization )<--- Condition 'bTryOptimization' is always false
            {
                try
                {
                    // try to use optimized copying
                    uno::Reference< embed::XOptimizedStorage > xSource( m_xParentStorage, uno::UNO_QUERY_THROW );
                    uno::Reference< embed::XOptimizedStorage > xTarget( xStorage, uno::UNO_QUERY_THROW );
                    xSource->copyElementDirectlyTo( m_aEntryName, xTarget, sEntName );
                    bOptimizationWorks = true;
                }
                catch( const uno::Exception& )
                {
                }
            }

            if ( !bOptimizationWorks )<--- Condition '!bOptimizationWorks' is always true
                m_xParentStorage->copyElementTo( m_aEntryName, xStorage, sEntName );
        }
        else
        {
            changeState( embed::EmbedStates::RUNNING );
            bSwitchBackToLoaded = true;
        }
    }

    uno::Reference< embed::XStorage > xSubStorage =
                xStorage->openStorageElement( sEntName, embed::ElementModes::READWRITE );

    if ( !xSubStorage.is() )
        throw uno::RuntimeException(); //TODO

    if ( m_nObjectState != embed::EmbedStates::LOADED )
    {
        aGuard.clear();
        // TODO/LATER: support hierarchical name for embedded objects in embedded objects
        StoreDocToStorage_Impl(
            xSubStorage, lArguments, lObjArgs, nTargetStorageFormat, sEntName, false );
        aGuard.reset();

        if ( bSwitchBackToLoaded )
            changeState( embed::EmbedStates::LOADED );
    }

    m_bWaitSaveCompleted = true;
    m_xNewObjectStorage = xSubStorage;
    m_xNewParentStorage = xStorage;
    m_aNewEntryName = sEntName;
    m_aNewDocMediaDescriptor = GetValuableArgs_Impl( lArguments, true );

    // TODO: register listeners for storages above, in case they are disposed
    //       an exception will be thrown on saveCompleted( true )

    // TODO: should the listener notification be done here or in saveCompleted?
}


void SAL_CALL OCommonEmbeddedObject::saveCompleted( sal_Bool bUseNew )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_nObjectState == -1 )
    {
        // the object is still not loaded
        throw embed::WrongStateException( "Can't store object without persistence!",
                                        static_cast< ::cppu::OWeakObject* >(this) );
    }

    // for now support of this interface is required to allow breaking of links and converting them to normal embedded
    // objects, so the persist name must be handled correctly ( althowgh no real persist entry is used )
    // OSL_ENSURE( !m_bIsLink, "This method implementation must not be used for links!" );
    if ( m_bIsLink )
    {
        if ( bUseNew )
            m_aEntryName = m_aNewEntryName;
        m_aNewEntryName.clear();
        return;
    }

    // it is allowed to call saveCompleted( false ) for nonstored objects
    if ( !m_bWaitSaveCompleted && !bUseNew )
        return;

    SAL_WARN_IF( !m_bWaitSaveCompleted, "embeddedobj.common", "Unexpected saveCompleted() call!" );
    if ( !m_bWaitSaveCompleted )
        throw io::IOException(); // TODO: illegal call

    OSL_ENSURE( m_xNewObjectStorage.is() && m_xNewParentStorage.is() , "Internal object information is broken!" );
    if ( !m_xNewObjectStorage.is() || !m_xNewParentStorage.is() )
        throw uno::RuntimeException(); // TODO: broken internal information

    if ( bUseNew )
    {
        SwitchOwnPersistence( m_xNewParentStorage, m_xNewObjectStorage, m_aNewEntryName );
        m_aDocMediaDescriptor = m_aNewDocMediaDescriptor;

        uno::Reference< util::XModifiable > xModif( m_xDocHolder->GetComponent(), uno::UNO_QUERY );
        if ( xModif.is() )
            xModif->setModified( false );

        PostEvent_Impl( "OnSaveAsDone");
    }
    else
    {
        try {
            m_xNewObjectStorage->dispose();
        }
        catch ( const uno::Exception& )
        {
        }
    }

    m_xNewObjectStorage.clear();
    m_xNewParentStorage.clear();
    m_aNewEntryName.clear();
    m_aNewDocMediaDescriptor.realloc( 0 );
    m_bWaitSaveCompleted = false;

    if ( bUseNew )
    {
        // TODO: notify listeners

        if ( m_nUpdateMode == embed::EmbedUpdateModes::ALWAYS_UPDATE )
        {
            // TODO: update visual representation
        }
    }
}


sal_Bool SAL_CALL OCommonEmbeddedObject::hasEntry()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_bWaitSaveCompleted )
        throw embed::WrongStateException(
                    "The object waits for saveCompleted() call!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    if ( m_xObjectStorage.is() )
        return true;

    return false;
}


OUString SAL_CALL OCommonEmbeddedObject::getEntryName()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_nObjectState == -1 )
    {
        // the object is still not loaded
        throw embed::WrongStateException( "The object persistence is not initialized!",
                                        static_cast< ::cppu::OWeakObject* >(this) );
    }

    if ( m_bWaitSaveCompleted )
        throw embed::WrongStateException(
                    "The object waits for saveCompleted() call!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    return m_aEntryName;
}


void SAL_CALL OCommonEmbeddedObject::storeOwn()
{
    // during switching from Activated to Running and from Running to Loaded states the object will
    // ask container to store the object, the container has to make decision
    // to do so or not

    ::osl::ResettableMutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_nObjectState == -1 )
    {
        // the object is still not loaded
        throw embed::WrongStateException( "Can't store object without persistence!",
                                    static_cast< ::cppu::OWeakObject* >(this) );
    }

    if ( m_bWaitSaveCompleted )
        throw embed::WrongStateException(
                    "The object waits for saveCompleted() call!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    if ( m_bReadOnly )
        throw io::IOException(); // TODO: access denied

    // nothing to do, if the object is in loaded state
    if ( m_nObjectState == embed::EmbedStates::LOADED )
        return;

    PostEvent_Impl( "OnSave" );

    SAL_WARN_IF( !m_xDocHolder->GetComponent().is(), "embeddedobj.common", "If an object is activated or in running state it must have a document!" );
    if ( !m_xDocHolder->GetComponent().is() )
        throw uno::RuntimeException();

    if ( m_bIsLink )
    {
        // TODO: just store the document to its location
        uno::Reference< frame::XStorable > xStorable( m_xDocHolder->GetComponent(), uno::UNO_QUERY_THROW );

        // free the main mutex for the storing time
        aGuard.clear();

        xStorable->store();

        aGuard.reset();
    }
    else
    {
        OSL_ENSURE( m_xParentStorage.is() && m_xObjectStorage.is(), "The object has no valid persistence!" );

        if ( !m_xObjectStorage.is() )
            throw io::IOException(); //TODO: access denied

        sal_Int32 nStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
        try {
            nStorageFormat = ::comphelper::OStorageHelper::GetXStorageFormat( m_xParentStorage );
        }
        catch ( const beans::IllegalTypeException& )
        {
            // the container just has an unknown type, use current file format
        }
        catch ( const uno::Exception& )
        {
            SAL_WARN( "embeddedobj.common", "Can not retrieve storage media type!" );
        }
        if (nStorageFormat == SOFFICE_FILEFORMAT_60)
        {
            SAL_INFO("embeddedobj.common", "fdo#78159: Storing OOoXML as ODF");
            nStorageFormat = SOFFICE_FILEFORMAT_CURRENT;
            // setting MediaType is done later anyway, no need to do it here
        }

        aGuard.clear();
        uno::Sequence<beans::PropertyValue> aEmpty;
        uno::Sequence<beans::PropertyValue> aMediaArgs(1);
        aMediaArgs[0].Name = "DocumentBaseURL";
        aMediaArgs[0].Value <<= GetBaseURL_Impl();
        StoreDocToStorage_Impl( m_xObjectStorage, aMediaArgs, aEmpty, nStorageFormat, m_aEntryName, true );
        aGuard.reset();
    }

    uno::Reference< util::XModifiable > xModif( m_xDocHolder->GetComponent(), uno::UNO_QUERY );
    if ( xModif.is() )
        xModif->setModified( false );

    PostEvent_Impl( "OnSaveDone" );
}


sal_Bool SAL_CALL OCommonEmbeddedObject::isReadonly()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_nObjectState == -1 )
    {
        // the object is still not loaded
        throw embed::WrongStateException( "The object persistence is not initialized!",
                                        static_cast< ::cppu::OWeakObject* >(this) );
    }

    if ( m_bWaitSaveCompleted )
        throw embed::WrongStateException(
                    "The object waits for saveCompleted() call!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    return m_bReadOnly;
}


void SAL_CALL OCommonEmbeddedObject::reload(
                const uno::Sequence< beans::PropertyValue >& lArguments,
                const uno::Sequence< beans::PropertyValue >& lObjArgs )
{
    // TODO: use lObjArgs
    // for now this method is used only to switch readonly state

    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( m_nObjectState == -1 )
    {
        // the object is still not loaded
        throw embed::WrongStateException( "The object persistence is not initialized!",
                                        static_cast< ::cppu::OWeakObject* >(this) );
    }

    if ( m_nObjectState != embed::EmbedStates::LOADED )
    {
        // the object is still not loaded
        throw embed::WrongStateException(
                                "The object must be in loaded state to be reloaded!",
                                static_cast< ::cppu::OWeakObject* >(this) );
    }

    if ( m_bWaitSaveCompleted )
        throw embed::WrongStateException(
                    "The object waits for saveCompleted() call!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    if ( m_bIsLink )
    {
        // reload of the link
        OUString aOldLinkFilter = m_aLinkFilterName;

        OUString aNewLinkFilter;
        for ( beans::PropertyValue const & prop : lArguments )
        {
            if ( prop.Name == "URL" )
            {
                // the new URL
                prop.Value >>= m_aLinkURL;
                m_aLinkFilterName.clear();
            }
            else if ( prop.Name == "FilterName" )
            {
                prop.Value >>= aNewLinkFilter;
                m_aLinkFilterName.clear();
            }
        }

        ::comphelper::MimeConfigurationHelper aHelper( m_xContext );
        if ( m_aLinkFilterName.isEmpty() )
        {
            if ( !aNewLinkFilter.isEmpty() )
                m_aLinkFilterName = aNewLinkFilter;
            else
            {
                uno::Sequence< beans::PropertyValue > aArgs( 1 );
                aArgs[0].Name = "URL";
                aArgs[0].Value <<= m_aLinkURL;
                m_aLinkFilterName = aHelper.UpdateMediaDescriptorWithFilterName( aArgs, false );
            }
        }

        if ( aOldLinkFilter != m_aLinkFilterName )
        {
            uno::Sequence< beans::NamedValue > aObject = aHelper.GetObjectPropsByFilter( m_aLinkFilterName );

            // TODO/LATER: probably the document holder could be cleaned explicitly as in the destructor
            m_xDocHolder.clear();

            LinkInit_Impl( aObject, lArguments, lObjArgs );
        }
    }

    m_aDocMediaDescriptor = GetValuableArgs_Impl( lArguments, true );

    // TODO: use lObjArgs for StoreVisualReplacement
    for ( beans::PropertyValue const & prop : lObjArgs )
        if ( prop.Name == "OutplaceDispatchInterceptor" )
        {<--- Consider using std::find_if algorithm instead of a raw loop.
            uno::Reference< frame::XDispatchProviderInterceptor > xDispatchInterceptor;
            if ( prop.Value >>= xDispatchInterceptor )
                m_xDocHolder->SetOutplaceDispatchInterceptor( xDispatchInterceptor );

            break;
        }

    // TODO:
    // when document allows reloading through API the object can be reloaded not only in loaded state

    bool bOldReadOnlyValue = m_bReadOnly;

    m_bReadOnly = false;
    for ( beans::PropertyValue const & prop : lArguments )
        if ( prop.Name == "ReadOnly" )
            prop.Value >>= m_bReadOnly;

    if ( bOldReadOnlyValue == m_bReadOnly || m_bIsLink )
        return;

    // close own storage
    try {
        if ( m_xObjectStorage.is() )
            m_xObjectStorage->dispose();
    }
    catch ( const uno::Exception& )
    {
    }

    sal_Int32 nStorageMode = m_bReadOnly ? embed::ElementModes::READ : embed::ElementModes::READWRITE;
    m_xObjectStorage = m_xParentStorage->openStorageElement( m_aEntryName, nStorageMode );
}

sal_Bool SAL_CALL OCommonEmbeddedObject::isStored()
{
    if (!m_xObjectStorage.is())
        return false;

    return m_xObjectStorage->getElementNames().hasElements();
}


void SAL_CALL OCommonEmbeddedObject::breakLink( const uno::Reference< embed::XStorage >& xStorage,
                                                const OUString& sEntName )
{
    ::osl::ResettableMutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if (!m_bIsLink || m_nObjectState == -1)
    {
        // it must be a linked initialized object
        throw embed::WrongStateException(
                    "The object is not a valid linked object!",
                    static_cast< ::cppu::OWeakObject* >(this) );
    }
    // the current implementation of OOo links does not implement this method since it does not implement
    // all the set of interfaces required for OOo embedded object ( XEmbedPersist is not supported ).

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( "No parent storage is provided!",
                                            static_cast< ::cppu::OWeakObject* >(this),
                                            1 );

    if ( sEntName.isEmpty() )
        throw lang::IllegalArgumentException( "Empty element name is provided!",
                                            static_cast< ::cppu::OWeakObject* >(this),
                                            2 );

    if ( m_bWaitSaveCompleted )
        throw embed::WrongStateException(
                    "The object waits for saveCompleted() call!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    uno::Reference< container::XNameAccess > xNameAccess( xStorage, uno::UNO_QUERY_THROW );

    m_bReadOnly = false;

    if ( m_xParentStorage != xStorage || m_aEntryName != sEntName )
        SwitchOwnPersistence( xStorage, sEntName );

    // for linked object it means that it becomes embedded object
    // the document must switch it's persistence also

    // TODO/LATER: handle the case when temp doc can not be created
    // the document is a new embedded object so it must be marked as modified
    uno::Reference< util::XCloseable > xDocument = CreateTempDocFromLink_Impl();
    uno::Reference< util::XModifiable > xModif( m_xDocHolder->GetComponent(), uno::UNO_QUERY_THROW );
    try
    {
        xModif->setModified( true );
    }
    catch( const uno::Exception& )
    {}

    m_xDocHolder->SetComponent( xDocument, m_bReadOnly );
    SAL_WARN_IF( !m_xDocHolder->GetComponent().is(), "embeddedobj.common", "If document can't be created, an exception must be thrown!" );

    if ( m_nObjectState == embed::EmbedStates::LOADED )
    {
        // the state is changed and can not be switched to loaded state back without saving
        m_nObjectState = embed::EmbedStates::RUNNING;
        StateChangeNotification_Impl( false, embed::EmbedStates::LOADED, m_nObjectState, aGuard );
    }
    else if ( m_nObjectState == embed::EmbedStates::ACTIVE )
        m_xDocHolder->Show();

    m_bIsLink = false;
    m_aLinkFilterName.clear();
    m_aLinkURL.clear();
}


sal_Bool SAL_CALL  OCommonEmbeddedObject::isLink()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    return m_bIsLink;
}


OUString SAL_CALL OCommonEmbeddedObject::getLinkURL()
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if ( m_bDisposed )
        throw lang::DisposedException(); // TODO

    if ( !m_bIsLink )
        throw embed::WrongStateException(
                    "The object is not a link object!",
                    static_cast< ::cppu::OWeakObject* >(this) );

    return m_aLinkURL;
}

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