summaryrefslogtreecommitdiffstats
path: root/extensions/source/abpilot/datasourcehandling.cxx
blob: a411c2536b5009bc1fd0a66f4b97b8fdd0b43827 (plain)
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
/* -*- 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 <strings.hrc>
#include "abptypes.hxx"
#include <componentmodule.hxx>
#include "datasourcehandling.hxx"
#include "addresssettings.hxx"

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/sdb/DatabaseContext.hpp>
#include <com/sun/star/sdb/SQLContext.hpp>
#include <com/sun/star/sdb/XCompletedConnection.hpp>
#include <com/sun/star/sdb/XDatabaseRegistrations.hpp>
#include <com/sun/star/sdb/XDocumentDataSource.hpp>
#include <com/sun/star/sdbc/XConnection.hpp>
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#include <com/sun/star/task/InteractionHandler.hpp>
#include <com/sun/star/uri/UriReferenceFactory.hpp>
#include <com/sun/star/uri/VndSunStarPkgUrlReferenceFactory.hpp>

#include <comphelper/interaction.hxx>
#include <comphelper/processfactory.hxx>
#include <tools/debug.hxx>
#include <tools/diagnose_ex.h>
#include <unotools/sharedunocomponent.hxx>
#include <vcl/stdtext.hxx>
#include <vcl/weld.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/viewfrm.hxx>
#include <comphelper/propertysequence.hxx>

namespace
{

/// Returns the URL of this object shell.
OUString lcl_getOwnURL(SfxObjectShell const * pObjectShell)
{
    OUString aRet;

    if (!pObjectShell)
        return aRet;

    const INetURLObject& rURLObject = pObjectShell->GetMedium()->GetURLObject();
    aRet = rURLObject.GetMainURL(INetURLObject::DecodeMechanism::NONE);
    return aRet;
}

}

namespace abp
{


    using namespace ::utl;
    using namespace ::comphelper;
    using namespace ::com::sun::star;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::task;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::frame;

    static Reference< XDatabaseContext > lcl_getDataSourceContext( const Reference< XComponentContext >& _rxContext )
    {
        Reference<XDatabaseContext> xContext = DatabaseContext::create(_rxContext);
        return xContext;
    }


    /// creates a new data source and inserts it into the context
    static void lcl_implCreateAndInsert(
        const Reference< XComponentContext >& _rxContext, const OUString& _rName,
        Reference< XPropertySet >& /* [out] */ _rxNewDataSource )
    {

        // get the data source context
        Reference< XDatabaseContext > xContext = lcl_getDataSourceContext( _rxContext );

        DBG_ASSERT( !xContext->hasByName( _rName ), "lcl_implCreateAndInsert: name already used!" );


        // create a new data source
        Reference< XPropertySet > xNewDataSource;
        if (xContext.is())
            xNewDataSource.set( xContext->createInstance(), UNO_QUERY );
        DBG_ASSERT( xNewDataSource.is(), "lcl_implCreateAndInsert: could not create a new data source!" );


        // insert the data source into the context
        DBG_ASSERT( xContext.is(), "lcl_implCreateAndInsert: missing an interface on the context (XNamingService)!" );
        if (xContext.is())
        {
            //  xDynamicContext->registerObject( _rName, xNewDataSource );
            _rxNewDataSource = xNewDataSource;
        }
    }


    /// creates and inserts a data source, and sets its URL property to the string given
    static ODataSource lcl_implCreateAndSetURL(
        const Reference< XComponentContext >& _rxORB, const OUString& _rName,
        const char* _pInitialAsciiURL )
    {
        ODataSource aReturn( _rxORB );
        try
        {
            // create the new data source
            Reference< XPropertySet > xNewDataSource;
            lcl_implCreateAndInsert( _rxORB, _rName, xNewDataSource );


            // set the URL property
            if (xNewDataSource.is())
            {
                xNewDataSource->setPropertyValue(
                    "URL",
                    Any( OUString::createFromAscii( _pInitialAsciiURL ) )
                );
            }

            aReturn.setDataSource( xNewDataSource, _rName );
        }
        catch(const Exception&)
        {
            TOOLS_WARN_EXCEPTION("extensions.abpilot",
                                 "caught an exception while creating the data source!");
        }

        return aReturn;
    }

    static void lcl_registerDataSource(
        const Reference< XComponentContext >& _rxORB, const OUString& _sName,
        const OUString& _sURL )
    {
        OSL_ENSURE( !_sName.isEmpty(), "lcl_registerDataSource: invalid name!" );
        OSL_ENSURE( !_sURL.isEmpty(), "lcl_registerDataSource: invalid URL!" );
        try
        {
            Reference< XDatabaseContext > xRegistrations( DatabaseContext::create(_rxORB) );
            if ( xRegistrations->hasRegisteredDatabase( _sName ) )
                xRegistrations->changeDatabaseLocation( _sName, _sURL );
            else
                xRegistrations->registerDatabaseLocation( _sName, _sURL );
        }
        catch( const Exception& )
        {
            DBG_UNHANDLED_EXCEPTION("extensions.abpilot");
        }
    }

    struct ODataSourceContextImpl
    {
        Reference< XComponentContext >      xORB;
        Reference< XNameAccess >            xContext;           /// the UNO data source context
        StringBag                           aDataSourceNames;   /// for quicker name checks (without the UNO overhead)

        explicit ODataSourceContextImpl(const Reference< XComponentContext >& _rxORB)
            : xORB(_rxORB)
        {
        }
        ODataSourceContextImpl(const ODataSourceContextImpl&) = delete;
        ODataSourceContextImpl& operator=(const ODataSourceContextImpl&) = delete;
    };

    ODataSourceContext::ODataSourceContext(const Reference< XComponentContext >& _rxORB)
        :m_pImpl( new ODataSourceContextImpl( _rxORB ) )
    {
        try
        {
            // create the UNO context
            m_pImpl->xContext.set( lcl_getDataSourceContext( _rxORB ), UNO_QUERY_THROW );

            // collect the data source names
            Sequence< OUString > aDSNames = m_pImpl->xContext->getElementNames();
            const OUString* pDSNames = aDSNames.getConstArray();
            const OUString* pDSNamesEnd = pDSNames + aDSNames.getLength();

            for ( ;pDSNames != pDSNamesEnd; ++pDSNames )
                m_pImpl->aDataSourceNames.insert( *pDSNames );
        }
        catch( const Exception& )
        {
            TOOLS_WARN_EXCEPTION( "extensions.abpilot", "ODataSourceContext::ODataSourceContext" );
        }
    }
    ODataSourceContext::~ODataSourceContext()
    {
    }


    void ODataSourceContext::disambiguate(OUString& _rDataSourceName)
    {
        OUString sCheck( _rDataSourceName );
        StringBag::const_iterator aPos = m_pImpl->aDataSourceNames.find( sCheck );

        sal_Int32 nPostfix = 1;
        while ( ( m_pImpl->aDataSourceNames.end() != aPos ) && ( nPostfix < 65535 ) )
        {   // there already is a data source with this name
            sCheck = _rDataSourceName + OUString::number( nPostfix++ );

            aPos = m_pImpl->aDataSourceNames.find( sCheck );
        }

        _rDataSourceName = sCheck;
    }


    void ODataSourceContext::getDataSourceNames( StringBag& _rNames ) const
    {
        _rNames = m_pImpl->aDataSourceNames;
    }

    ODataSource ODataSourceContext::createNewThunderbird( const OUString& _rName )
    {
        return lcl_implCreateAndSetURL( m_pImpl->xORB, _rName, "sdbc:address:thunderbird" );
    }


    ODataSource ODataSourceContext::createNewEvolutionLdap( const OUString& _rName)
    {
        return lcl_implCreateAndSetURL( m_pImpl->xORB, _rName, "sdbc:address:evolution:ldap" );
    }

    ODataSource ODataSourceContext::createNewEvolutionGroupwise( const OUString& _rName)
    {
        return lcl_implCreateAndSetURL( m_pImpl->xORB, _rName, "sdbc:address:evolution:groupwise" );
    }

    ODataSource ODataSourceContext::createNewEvolution( const OUString& _rName)
    {
        return lcl_implCreateAndSetURL( m_pImpl->xORB, _rName, "sdbc:address:evolution:local" );
    }


    ODataSource ODataSourceContext::createNewKab( const OUString& _rName)
    {
        return lcl_implCreateAndSetURL( m_pImpl->xORB, _rName, "sdbc:address:kab" );
    }


    ODataSource ODataSourceContext::createNewMacab( const OUString& _rName)
    {
        return lcl_implCreateAndSetURL( m_pImpl->xORB, _rName, "sdbc:address:macab" );
    }


    // tdf117101: Spreadsheet by default
    ODataSource ODataSourceContext::createNewOther( const OUString& _rName)
    {
        return lcl_implCreateAndSetURL( m_pImpl->xORB, _rName, "sdbc:calc:" );
    }

    struct ODataSourceImpl
    {
    public:
        Reference< XComponentContext >          xORB;               /// the service factory
        Reference< XPropertySet >               xDataSource;        /// the UNO data source
        ::utl::SharedUNOComponent< XConnection >
                                                xConnection;
        StringBag                               aTables;            // the cached table names
        OUString                                sName;

        explicit ODataSourceImpl(const Reference< XComponentContext >& _rxORB)
            : xORB(_rxORB)
        {
        }
    };


    ODataSource::ODataSource( const ODataSource& _rSource )
    {
        *this = _rSource;
    }

    ODataSource& ODataSource::operator=( const ODataSource& _rSource )
    {
        if( this != &_rSource )
        {
            m_pImpl.reset( new ODataSourceImpl( *_rSource.m_pImpl ) );
        }
        return *this;
    }

    ODataSource& ODataSource::operator=(ODataSource&& _rSource) noexcept
    {
        m_pImpl = std::move(_rSource.m_pImpl);
        return *this;
    }

    ODataSource::ODataSource( const Reference< XComponentContext >& _rxORB )
        :m_pImpl(new ODataSourceImpl(_rxORB))
    {
    }

    ODataSource::~ODataSource( )
    {
    }

    void ODataSource::store(const AddressSettings& rSettings)
    {
        if (!isValid())
            // nothing to do
            return;
        try
        {
            Reference< XDocumentDataSource > xDocAccess( m_pImpl->xDataSource, UNO_QUERY );
            Reference< XStorable > xStorable;
            if ( xDocAccess.is() )
                xStorable.set(xDocAccess->getDatabaseDocument(), css::uno::UNO_QUERY);
            OSL_ENSURE( xStorable.is(),"DataSource is no XStorable!" );
            if ( xStorable.is() )
            {
                SfxViewFrame* pFrame = SfxViewFrame::Current();
                SfxObjectShell* pObjectShell = pFrame ? pFrame->GetObjectShell() : nullptr;
                OUString aOwnURL = lcl_getOwnURL(pObjectShell); // empty if pObjectShell is nullptr
                if (aOwnURL.isEmpty() || !rSettings.bEmbedDataSource)
                {
                    // Cannot or should not embed.
                    xStorable->storeAsURL(m_pImpl->sName,Sequence<PropertyValue>());
                }
                else
                {
                    // Embed.
                    OUString aStreamRelPath = "EmbeddedDatabase";
                    auto xContext(comphelper::getProcessComponentContext());
                    auto xUri = css::uri::UriReferenceFactory::create(xContext)->parse(aOwnURL);
                    assert(xUri.is());
                    xUri = css::uri::VndSunStarPkgUrlReferenceFactory::create(xContext)->createVndSunStarPkgUrlReference(xUri);
                    assert(xUri.is());
                    OUString const sTmpName = xUri->getUriReference() + "/" + aStreamRelPath;
                    assert(pObjectShell);
                    uno::Reference<embed::XStorage> xStorage = pObjectShell->GetStorage();
                    uno::Sequence<beans::PropertyValue> aSequence = comphelper::InitPropertySequence(
                    {
                        {"TargetStorage", uno::Any(xStorage)},
                        {"StreamRelPath", uno::Any(aStreamRelPath)},
                        {"BaseURI", uno::Any(aOwnURL)}
                    });
                    xStorable->storeAsURL(sTmpName, aSequence);
                    m_pImpl->sName = sTmpName;

                    // Refer to the sub-storage name in the document settings, so
                    // we can load it again next time the file is imported.
                    uno::Reference<lang::XMultiServiceFactory> xFactory(pObjectShell->GetModel(), uno::UNO_QUERY);
                    uno::Reference<beans::XPropertySet> xPropertySet(xFactory->createInstance("com.sun.star.document.Settings"), uno::UNO_QUERY);
                    xPropertySet->setPropertyValue("EmbeddedDatabaseName", uno::Any(aStreamRelPath));
                }
            }
        }
        catch(const Exception&)
        {
            TOOLS_WARN_EXCEPTION("extensions.abpilot",
                                 "caught an exception while creating the data source!");
        }
    }

    void ODataSource::registerDataSource( const OUString& _sRegisteredDataSourceName)
    {
        if (!isValid())
            // nothing to do
            return;

        try
        {
            // invalidate ourself
            lcl_registerDataSource(m_pImpl->xORB,_sRegisteredDataSourceName,m_pImpl->sName);
        }
        catch(const Exception&)
        {
            TOOLS_WARN_EXCEPTION("extensions.abpilot",
                                 "caught an exception while creating the data source!");
        }
    }


    void ODataSource::setDataSource( const Reference< XPropertySet >& _rxDS,const OUString& _sName )
    {
        if (m_pImpl->xDataSource.get() == _rxDS.get())
            // nothing to do
            return;

        if ( isConnected() )
            disconnect();

        m_pImpl->sName = _sName;
        m_pImpl->xDataSource = _rxDS;
    }


    void ODataSource::remove()
    {
        if (!isValid())
            // nothing to do
            return;

        try
        {
            // invalidate ourself
            m_pImpl->xDataSource.clear();
        }
        catch(const Exception&)
        {
            TOOLS_WARN_EXCEPTION("extensions.abpilot",
                                 "caught an exception while creating the data source!");
        }
    }


    bool ODataSource::rename( const OUString& _rName )
    {
        if (!isValid())
            // nothing to do
            return false;

        m_pImpl->sName = _rName;
        return true;
    }


    OUString ODataSource::getName() const
    {
        if ( !isValid() )
            return OUString();
        return m_pImpl->sName;
    }


    bool ODataSource::hasTable( const OUString& _rTableName ) const
    {
        if ( !isConnected() )
            return false;

        const StringBag& aTables( getTableNames() );
        return aTables.find( _rTableName ) != aTables.end();
    }


    const StringBag& ODataSource::getTableNames() const
    {
        m_pImpl->aTables.clear();
        if ( !isConnected() )
        {
            OSL_FAIL( "ODataSource::getTableNames: not connected!" );
        }
        else
        {
            try
            {
                // get the tables container from the connection
                Reference< XTablesSupplier > xSuppTables( m_pImpl->xConnection.getTyped(), UNO_QUERY );
                Reference< XNameAccess > xTables;
                if ( xSuppTables.is( ) )
                    xTables = xSuppTables->getTables();
                DBG_ASSERT( xTables.is(), "ODataSource::getTableNames: could not retrieve the tables container!" );

                // get the names
                Sequence< OUString > aTableNames;
                if ( xTables.is( ) )
                    aTableNames = xTables->getElementNames( );

                // copy the names
                const OUString* pTableNames = aTableNames.getConstArray();
                const OUString* pTableNamesEnd = pTableNames + aTableNames.getLength();
                for (;pTableNames < pTableNamesEnd; ++pTableNames)
                    m_pImpl->aTables.insert( *pTableNames );
            }
            catch(const Exception&)
            {
            }
        }

        // now the table cache is up-to-date
        return m_pImpl->aTables;
    }


    bool ODataSource::connect(weld::Window* _pMessageParent)
    {
        if ( isConnected( ) )
            // nothing to do
            return true;


        // create the interaction handler (needed for authentication and error handling)
        Reference< XInteractionHandler > xInteractions;
        try
        {
            xInteractions = InteractionHandler::createWithParent(m_pImpl->xORB, nullptr);
        }
        catch(const Exception&)
        {
        }


        // failure to create the interaction handler is a serious issue ...
        if (!xInteractions.is())
        {
            if ( _pMessageParent )
                ShowServiceNotAvailableError( _pMessageParent, u"com.sun.star.task.InteractionHandler", true );
            return false;
        }


        // open the connection
        Any aError;
        Reference< XConnection > xConnection;
        try
        {
            Reference< XCompletedConnection > xComplConn( m_pImpl->xDataSource, UNO_QUERY );
            DBG_ASSERT( xComplConn.is(), "ODataSource::connect: missing the XCompletedConnection interface on the data source!" );
            if ( xComplConn.is() )
                xConnection = xComplConn->connectWithCompletion( xInteractions );
        }
        catch( const SQLContext& e ) { aError <<= e; }
        catch( const SQLWarning& e ) { aError <<= e; }
        catch( const SQLException& e ) { aError <<= e; }
        catch( const Exception& )
        {
            TOOLS_WARN_EXCEPTION("extensions.abpilot", "");
        }


        // handle errors
        if ( aError.hasValue() && _pMessageParent )
        {
            try
            {
                SQLException aException;
                aError >>= aException;
                if ( aException.Message.isEmpty() )
                {
                    // prepend some context info
                    SQLContext aDetailedError;
                    aDetailedError.Message = compmodule::ModuleRes(RID_STR_NOCONNECTION);
                    aDetailedError.Details = compmodule::ModuleRes(RID_STR_PLEASECHECKSETTINGS);
                    aDetailedError.NextException = aError;
                    // handle (aka display) the new context info
                    xInteractions->handle( new OInteractionRequest( Any( aDetailedError ) ) );
                }
                else
                {
                      // handle (aka display) the original error
                    xInteractions->handle( new OInteractionRequest( Any( aException ) ) );
                }
            }
            catch( const Exception& )
            {
                TOOLS_WARN_EXCEPTION("extensions.abpilot",
                                     "caught an exception while trying to display the error!");
            }
        }

        if ( !xConnection.is() )
            return false;


        // success
        m_pImpl->xConnection.reset( xConnection );
        m_pImpl->aTables.clear();

        return true;
    }


    void ODataSource::disconnect( )
    {
        m_pImpl->xConnection.clear();
        m_pImpl->aTables.clear();
    }


    bool ODataSource::isConnected( ) const
    {
        return m_pImpl->xConnection.is();
    }


    bool ODataSource::isValid() const
    {
        return m_pImpl && m_pImpl->xDataSource.is();
    }

    Reference< XPropertySet > ODataSource::getDataSource() const
    {
        return m_pImpl ? m_pImpl->xDataSource : Reference< XPropertySet >();
    }


}   // namespace abp


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