bump product version to 7.2.5.1
[LibreOffice.git] / connectivity / source / manager / mdrivermanager.cxx
blobe3a0c82efca3b21f511518a32c22478352534e94
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
21 #include "mdrivermanager.hxx"
22 #include <com/sun/star/configuration/theDefaultProvider.hpp>
23 #include <com/sun/star/sdbc/XDriver.hpp>
24 #include <com/sun/star/container/XContentEnumerationAccess.hpp>
25 #include <com/sun/star/container/ElementExistException.hpp>
26 #include <com/sun/star/beans/NamedValue.hpp>
27 #include <com/sun/star/logging/LogLevel.hpp>
29 #include <tools/diagnose_ex.h>
30 #include <cppuhelper/implbase.hxx>
31 #include <cppuhelper/supportsservice.hxx>
32 #include <cppuhelper/weak.hxx>
33 #include <osl/diagnose.h>
35 #include <algorithm>
36 #include <iterator>
37 #include <vector>
39 namespace drivermanager
42 using namespace ::com::sun::star::uno;
43 using namespace ::com::sun::star::lang;
44 using namespace ::com::sun::star::sdbc;
45 using namespace ::com::sun::star::beans;
46 using namespace ::com::sun::star::container;
47 using namespace ::com::sun::star::logging;
48 using namespace ::osl;
50 #define SERVICE_SDBC_DRIVER "com.sun.star.sdbc.Driver"
52 /// @throws NoSuchElementException
53 static void throwNoSuchElementException()
55 throw NoSuchElementException();
58 class ODriverEnumeration : public ::cppu::WeakImplHelper< XEnumeration >
60 friend class OSDBCDriverManager;
62 typedef std::vector< Reference< XDriver > > DriverArray;
63 DriverArray m_aDrivers;
64 DriverArray::const_iterator m_aPos;
65 // order matters!
67 protected:
68 virtual ~ODriverEnumeration() override;
69 public:
70 explicit ODriverEnumeration(const DriverArray& _rDriverSequence);
72 // XEnumeration
73 virtual sal_Bool SAL_CALL hasMoreElements( ) override;
74 virtual Any SAL_CALL nextElement( ) override;
78 ODriverEnumeration::ODriverEnumeration(const DriverArray& _rDriverSequence)
79 :m_aDrivers( _rDriverSequence )
80 ,m_aPos( m_aDrivers.begin() )
85 ODriverEnumeration::~ODriverEnumeration()
90 sal_Bool SAL_CALL ODriverEnumeration::hasMoreElements( )
92 return m_aPos != m_aDrivers.end();
96 Any SAL_CALL ODriverEnumeration::nextElement( )
98 if ( !hasMoreElements() )
99 throwNoSuchElementException();
101 return makeAny( *m_aPos++ );
104 namespace {
106 /// an STL functor which ensures that a SdbcDriver described by a DriverAccess is loaded
107 struct EnsureDriver
109 explicit EnsureDriver( const Reference< XComponentContext > &rxContext )
110 : mxContext( rxContext ) {}
112 const DriverAccess& operator()( const DriverAccess& _rDescriptor ) const
114 // we did not load this driver, yet
115 if (!_rDescriptor.xDriver.is())
117 // we have a factory for it
118 if (_rDescriptor.xComponentFactory.is())
120 DriverAccess& rDesc = const_cast<DriverAccess&>(_rDescriptor);
123 //load driver
124 rDesc.xDriver.set(
125 rDesc.xComponentFactory->createInstanceWithContext(mxContext), css::uno::UNO_QUERY);
127 catch (const Exception&)
129 //failure, abandon driver
130 rDesc.xComponentFactory.clear();
134 return _rDescriptor;
137 private:
138 Reference< XComponentContext > mxContext;
141 /// an STL functor which extracts a SdbcDriver from a DriverAccess
142 struct ExtractDriverFromAccess
144 const Reference<XDriver>& operator()( const DriverAccess& _rAccess ) const
146 return _rAccess.xDriver;
150 struct ExtractDriverFromCollectionElement
152 const Reference<XDriver>& operator()( const DriverCollection::value_type& _rElement ) const
154 return _rElement.second;
158 // predicate for checking whether or not a driver accepts a given URL
159 class AcceptsURL
161 protected:
162 const OUString& m_rURL;
164 public:
165 // ctor
166 explicit AcceptsURL( const OUString& _rURL ) : m_rURL( _rURL ) { }
169 bool operator()( const Reference<XDriver>& _rDriver ) const
171 // ask the driver
172 return _rDriver.is() && _rDriver->acceptsURL( m_rURL );
178 static sal_Int32 lcl_getDriverPrecedence( const Reference<XComponentContext>& _rContext, Sequence< OUString >& _rPrecedence )
180 _rPrecedence.realloc( 0 );
183 // create a configuration provider
184 Reference< XMultiServiceFactory > xConfigurationProvider(
185 css::configuration::theDefaultProvider::get( _rContext ) );
187 // one argument for creating the node access: the path to the configuration node
188 Sequence< Any > aCreationArgs(1);
189 aCreationArgs[0] <<= NamedValue( "nodepath", makeAny( OUString("org.openoffice.Office.DataAccess/DriverManager") ) );
191 // create the node access
192 Reference< XNameAccess > xDriverManagerNode(
193 xConfigurationProvider->createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", aCreationArgs),
194 UNO_QUERY);
196 OSL_ENSURE(xDriverManagerNode.is(), "lcl_getDriverPrecedence: could not open my configuration node!");
197 if (xDriverManagerNode.is())
199 // obtain the preference list
200 Any aPreferences = xDriverManagerNode->getByName("DriverPrecedence");
201 bool bSuccess = aPreferences >>= _rPrecedence;
202 OSL_ENSURE(bSuccess || !aPreferences.hasValue(), "lcl_getDriverPrecedence: invalid value for the preferences node (no string sequence but not NULL)!");
205 catch( const Exception& )
207 DBG_UNHANDLED_EXCEPTION("connectivity.manager");
210 return _rPrecedence.getLength();
213 namespace {
215 /// an STL argorithm compatible predicate comparing two DriverAccess instances by their implementation names
216 struct CompareDriverAccessByName
219 bool operator()( const DriverAccess& lhs, const DriverAccess& rhs )
221 return lhs.sImplementationName < rhs.sImplementationName;
225 /// and STL argorithm compatible predicate comparing a DriverAccess' impl name to a string
226 struct EqualDriverAccessToName
228 OUString m_sImplName;
229 explicit EqualDriverAccessToName(const OUString& _sImplName) : m_sImplName(_sImplName){}
231 bool operator()( const DriverAccess& lhs)
233 return lhs.sImplementationName == m_sImplName;
239 OSDBCDriverManager::OSDBCDriverManager( const Reference< XComponentContext >& _rxContext )
240 :OSDBCDriverManager_Base(m_aMutex)
241 ,m_xContext( _rxContext )
242 ,m_aEventLogger( _rxContext, "org.openoffice.logging.sdbc.DriverManager" )
243 ,m_aDriverConfig(m_xContext)
244 ,m_nLoginTimeout(0)
246 // bootstrap all objects supporting the .sdb.Driver service
247 bootstrapDrivers();
249 // initialize the drivers order
250 initializeDriverPrecedence();
254 OSDBCDriverManager::~OSDBCDriverManager()
258 void OSDBCDriverManager::bootstrapDrivers()
260 Reference< XContentEnumerationAccess > xEnumAccess( m_xContext->getServiceManager(), UNO_QUERY );
261 Reference< XEnumeration > xEnumDrivers;
262 if (xEnumAccess.is())
263 xEnumDrivers = xEnumAccess->createContentEnumeration(SERVICE_SDBC_DRIVER);
265 OSL_ENSURE( xEnumDrivers.is(), "OSDBCDriverManager::bootstrapDrivers: no enumeration for the drivers available!" );
266 if (!xEnumDrivers.is())
267 return;
269 Reference< XSingleComponentFactory > xFactory;
270 Reference< XServiceInfo > xSI;
271 while (xEnumDrivers->hasMoreElements())
273 xFactory.set(xEnumDrivers->nextElement(), css::uno::UNO_QUERY);
274 OSL_ENSURE( xFactory.is(), "OSDBCDriverManager::bootstrapDrivers: no factory extracted" );
276 if ( xFactory.is() )
278 // we got a factory for the driver
279 DriverAccess aDriverDescriptor;
280 bool bValidDescriptor = false;
282 // can it tell us something about the implementation name?
283 xSI.set(xFactory, css::uno::UNO_QUERY);
284 if ( xSI.is() )
285 { // yes -> no need to load the driver immediately (load it later when needed)
286 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
287 aDriverDescriptor.xComponentFactory = xFactory;
288 bValidDescriptor = true;
290 m_aEventLogger.log( LogLevel::CONFIG,
291 "found SDBC driver $1$, no need to load it",
292 aDriverDescriptor.sImplementationName
295 else
297 // no -> create the driver
298 Reference< XDriver > xDriver( xFactory->createInstanceWithContext( m_xContext ), UNO_QUERY );
299 OSL_ENSURE( xDriver.is(), "OSDBCDriverManager::bootstrapDrivers: a driver which is no driver?!" );
301 if ( xDriver.is() )
303 aDriverDescriptor.xDriver = xDriver;
304 // and obtain its implementation name
305 xSI.set(xDriver, css::uno::UNO_QUERY);
306 OSL_ENSURE( xSI.is(), "OSDBCDriverManager::bootstrapDrivers: a driver without service info?" );
307 if ( xSI.is() )
309 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
310 bValidDescriptor = true;
312 m_aEventLogger.log( LogLevel::CONFIG,
313 "found SDBC driver $1$, needed to load it",
314 aDriverDescriptor.sImplementationName
320 if ( bValidDescriptor )
322 m_aDriversBS.push_back( aDriverDescriptor );
329 void OSDBCDriverManager::initializeDriverPrecedence()
331 if ( m_aDriversBS.empty() )
332 // nothing to do
333 return;
337 // get the precedence of the drivers from the configuration
338 Sequence< OUString > aDriverOrder;
339 if ( 0 == lcl_getDriverPrecedence( m_xContext, aDriverOrder ) )
340 // nothing to do
341 return;
343 // aDriverOrder now is the list of driver implementation names in the order they should be used
345 if ( m_aEventLogger.isLoggable( LogLevel::CONFIG ) )
347 sal_Int32 nOrderedCount = aDriverOrder.getLength();
348 for ( sal_Int32 i=0; i<nOrderedCount; ++i )
349 m_aEventLogger.log( LogLevel::CONFIG,
350 "configuration's driver order: driver $1$ of $2$: $3$",
351 static_cast<sal_Int32>(i + 1), nOrderedCount, aDriverOrder[i]
355 // sort our bootstrapped drivers
356 std::sort( m_aDriversBS.begin(), m_aDriversBS.end(), CompareDriverAccessByName() );
358 // the first driver for which there is no preference
359 DriverAccessArray::iterator aNoPrefDriversStart = m_aDriversBS.begin();
360 // at the moment this is the first of all drivers we know
362 // loop through the names in the precedence order
363 for ( const OUString& rDriverOrder : std::as_const(aDriverOrder) )
365 if (aNoPrefDriversStart == m_aDriversBS.end())
366 break;
368 DriverAccess driver_order;
369 driver_order.sImplementationName = rDriverOrder;
371 // look for the impl name in the DriverAccess array
372 std::pair< DriverAccessArray::iterator, DriverAccessArray::iterator > aPos =
373 std::equal_range( aNoPrefDriversStart, m_aDriversBS.end(), driver_order, CompareDriverAccessByName() );
375 if ( aPos.first != aPos.second )
376 { // we have a DriverAccess with this impl name
378 OSL_ENSURE( std::distance( aPos.first, aPos.second ) == 1,
379 "OSDBCDriverManager::initializeDriverPrecedence: more than one driver with this impl name? How this?" );
380 // move the DriverAccess pointed to by aPos.first to the position pointed to by aNoPrefDriversStart
382 if ( aPos.first != aNoPrefDriversStart )
383 { // if this does not hold, the DriverAccess already has the correct position
385 // rotate the range [aNoPrefDriversStart, aPos.second) right 1 element
386 std::rotate( aNoPrefDriversStart, aPos.second - 1, aPos.second );
389 // next round we start searching and pos right
390 ++aNoPrefDriversStart;
394 catch (Exception&)
396 TOOLS_WARN_EXCEPTION( "connectivity.hsqldb", "OSDBCDriverManager::initializeDriverPrecedence: caught an exception while sorting the drivers!");
401 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnection( const OUString& _rURL )
403 MutexGuard aGuard(m_aMutex);
405 m_aEventLogger.log( LogLevel::INFO,
406 "connection requested for URL $1$",
407 _rURL
410 Reference< XConnection > xConnection;
411 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
412 if (xDriver.is())
414 // TODO : handle the login timeout
415 xConnection = xDriver->connect(_rURL, Sequence< PropertyValue >());
416 // may throw an exception
417 m_aEventLogger.log( LogLevel::INFO,
418 "connection retrieved for URL $1$",
419 _rURL
423 return xConnection;
427 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnectionWithInfo( const OUString& _rURL, const Sequence< PropertyValue >& _rInfo )
429 MutexGuard aGuard(m_aMutex);
431 m_aEventLogger.log( LogLevel::INFO,
432 "connection with info requested for URL $1$",
433 _rURL
436 Reference< XConnection > xConnection;
437 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
438 if (xDriver.is())
440 // TODO : handle the login timeout
441 xConnection = xDriver->connect(_rURL, _rInfo);
442 // may throw an exception
443 m_aEventLogger.log( LogLevel::INFO,
444 "connection with info retrieved for URL $1$",
445 _rURL
449 return xConnection;
453 void SAL_CALL OSDBCDriverManager::setLoginTimeout( sal_Int32 seconds )
455 MutexGuard aGuard(m_aMutex);
456 m_nLoginTimeout = seconds;
460 sal_Int32 SAL_CALL OSDBCDriverManager::getLoginTimeout( )
462 MutexGuard aGuard(m_aMutex);
463 return m_nLoginTimeout;
467 Reference< XEnumeration > SAL_CALL OSDBCDriverManager::createEnumeration( )
469 MutexGuard aGuard(m_aMutex);
471 ODriverEnumeration::DriverArray aDrivers;
473 // ensure that all our bootstrapped drivers are instantiated
474 std::for_each( m_aDriversBS.begin(), m_aDriversBS.end(), EnsureDriver( m_xContext ) );
476 // copy the bootstrapped drivers
477 std::transform(
478 m_aDriversBS.begin(), // "copy from" start
479 m_aDriversBS.end(), // "copy from" end
480 std::back_inserter( aDrivers ), // insert into
481 ExtractDriverFromAccess() // transformation to apply (extract a driver from a driver access)
484 // append the runtime drivers
485 std::transform(
486 m_aDriversRT.begin(), // "copy from" start
487 m_aDriversRT.end(), // "copy from" end
488 std::back_inserter( aDrivers ), // insert into
489 ExtractDriverFromCollectionElement() // transformation to apply (extract a driver from a driver access)
492 return new ODriverEnumeration( aDrivers );
496 css::uno::Type SAL_CALL OSDBCDriverManager::getElementType( )
498 return cppu::UnoType<XDriver>::get();
502 sal_Bool SAL_CALL OSDBCDriverManager::hasElements( )
504 MutexGuard aGuard(m_aMutex);
505 return !(m_aDriversBS.empty() && m_aDriversRT.empty());
509 OUString SAL_CALL OSDBCDriverManager::getImplementationName( )
511 return "com.sun.star.comp.sdbc.OSDBCDriverManager";
514 sal_Bool SAL_CALL OSDBCDriverManager::supportsService( const OUString& _rServiceName )
516 return cppu::supportsService(this, _rServiceName);
520 Sequence< OUString > SAL_CALL OSDBCDriverManager::getSupportedServiceNames( )
522 return { "com.sun.star.sdbc.DriverManager" };
526 Reference< XInterface > SAL_CALL OSDBCDriverManager::getRegisteredObject( const OUString& _rName )
528 MutexGuard aGuard(m_aMutex);
529 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
530 if (aSearch == m_aDriversRT.end())
531 throwNoSuchElementException();
533 return aSearch->second;
537 void SAL_CALL OSDBCDriverManager::registerObject( const OUString& _rName, const Reference< XInterface >& _rxObject )
539 MutexGuard aGuard(m_aMutex);
541 m_aEventLogger.log( LogLevel::INFO,
542 "attempt to register new driver for name $1$",
543 _rName
546 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
547 if (aSearch != m_aDriversRT.end())
548 throw ElementExistException();
549 Reference< XDriver > xNewDriver(_rxObject, UNO_QUERY);
550 if (!xNewDriver.is())
551 throw IllegalArgumentException();
553 m_aDriversRT.emplace(_rName, xNewDriver);
555 m_aEventLogger.log( LogLevel::INFO,
556 "new driver registered for name $1$",
557 _rName
562 void SAL_CALL OSDBCDriverManager::revokeObject( const OUString& _rName )
564 MutexGuard aGuard(m_aMutex);
566 m_aEventLogger.log( LogLevel::INFO,
567 "attempt to revoke driver for name $1$",
568 _rName
571 DriverCollection::iterator aSearch = m_aDriversRT.find(_rName);
572 if (aSearch == m_aDriversRT.end())
573 throwNoSuchElementException();
575 m_aDriversRT.erase(aSearch); // we already have the iterator so we could use it
577 m_aEventLogger.log( LogLevel::INFO,
578 "driver revoked for name $1$",
579 _rName
584 Reference< XDriver > SAL_CALL OSDBCDriverManager::getDriverByURL( const OUString& _rURL )
586 m_aEventLogger.log( LogLevel::INFO,
587 "driver requested for URL $1$",
588 _rURL
591 Reference< XDriver > xDriver( implGetDriverForURL( _rURL ) );
593 if ( xDriver.is() )
594 m_aEventLogger.log( LogLevel::INFO,
595 "driver obtained for URL $1$",
596 _rURL
599 return xDriver;
603 Reference< XDriver > OSDBCDriverManager::implGetDriverForURL(const OUString& _rURL)
605 Reference< XDriver > xReturn;
608 const OUString sDriverFactoryName = m_aDriverConfig.getDriverFactoryName(_rURL);
610 EqualDriverAccessToName aEqual(sDriverFactoryName);
611 DriverAccessArray::const_iterator aFind = std::find_if(m_aDriversBS.begin(),m_aDriversBS.end(),aEqual);
612 if ( aFind == m_aDriversBS.end() )
614 // search all bootstrapped drivers
615 aFind = std::find_if(
616 m_aDriversBS.begin(), // begin of search range
617 m_aDriversBS.end(), // end of search range
618 [&_rURL, this] (const DriverAccessArray::value_type& driverAccess) {
619 // extract the driver from the access, then ask the resulting driver for acceptance
620 const DriverAccess& ensuredAccess = EnsureDriver(m_xContext)(driverAccess);
621 const Reference<XDriver> driver = ExtractDriverFromAccess()(ensuredAccess);
622 return AcceptsURL(_rURL)(driver);
624 } // if ( m_aDriversBS.find(sDriverFactoryName ) == m_aDriversBS.end() )
625 else
627 EnsureDriver aEnsure( m_xContext );
628 aEnsure(*aFind);
631 // found something?
632 if ( m_aDriversBS.end() != aFind && aFind->xDriver.is() && aFind->xDriver->acceptsURL(_rURL) )
633 xReturn = aFind->xDriver;
636 if ( !xReturn.is() )
638 // no -> search the runtime drivers
639 DriverCollection::const_iterator aPos = std::find_if(
640 m_aDriversRT.begin(), // begin of search range
641 m_aDriversRT.end(), // end of search range
642 [&_rURL] (const DriverCollection::value_type& element) {
643 // extract the driver from the collection element, then ask the resulting driver for acceptance
644 const Reference<XDriver> driver = ExtractDriverFromCollectionElement()(element);
645 return AcceptsURL(_rURL)(driver);
648 if ( m_aDriversRT.end() != aPos )
649 xReturn = aPos->second;
652 return xReturn;
655 } // namespace drivermanager
657 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
658 connectivity_OSDBCDriverManager_get_implementation(
659 css::uno::XComponentContext* context , css::uno::Sequence<css::uno::Any> const&)
661 return cppu::acquire(new drivermanager::OSDBCDriverManager(context));
665 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */