bump product version to 5.0.4.1
[LibreOffice.git] / connectivity / source / manager / mdrivermanager.cxx
blobb64e935374da675edcd3857bba7f65f40c92aba1
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>
28 #include <tools/diagnose_ex.h>
29 #include <comphelper/processfactory.hxx>
30 #include <cppuhelper/implbase1.hxx>
31 #include <cppuhelper/supportsservice.hxx>
32 #include <cppuhelper/weakref.hxx>
33 #include <osl/diagnose.h>
35 #include <algorithm>
36 #include <iterator>
37 #include <vector>
39 #include <o3tl/compat_functional.hxx>
41 namespace drivermanager
44 using namespace ::com::sun::star::uno;
45 using namespace ::com::sun::star::lang;
46 using namespace ::com::sun::star::sdbc;
47 using namespace ::com::sun::star::beans;
48 using namespace ::com::sun::star::container;
49 using namespace ::com::sun::star::logging;
50 using namespace ::osl;
52 #define SERVICE_SDBC_DRIVER OUString("com.sun.star.sdbc.Driver")
54 void throwNoSuchElementException() throw(NoSuchElementException)
56 throw NoSuchElementException();
59 class ODriverEnumeration : public ::cppu::WeakImplHelper1< XEnumeration >
61 friend class OSDBCDriverManager;
63 typedef std::vector< Reference< XDriver > > DriverArray;
64 DriverArray m_aDrivers;
65 DriverArray::const_iterator m_aPos;
66 // order matters!
68 protected:
69 virtual ~ODriverEnumeration();
70 public:
71 ODriverEnumeration(const DriverArray& _rDriverSequence);
73 // XEnumeration
74 virtual sal_Bool SAL_CALL hasMoreElements( ) throw(RuntimeException, std::exception) SAL_OVERRIDE;
75 virtual Any SAL_CALL nextElement( ) throw(NoSuchElementException, WrappedTargetException, RuntimeException, std::exception) SAL_OVERRIDE;
79 ODriverEnumeration::ODriverEnumeration(const DriverArray& _rDriverSequence)
80 :m_aDrivers( _rDriverSequence )
81 ,m_aPos( m_aDrivers.begin() )
86 ODriverEnumeration::~ODriverEnumeration()
91 sal_Bool SAL_CALL ODriverEnumeration::hasMoreElements( ) throw(RuntimeException, std::exception)
93 return m_aPos != m_aDrivers.end();
97 Any SAL_CALL ODriverEnumeration::nextElement( ) throw(NoSuchElementException, WrappedTargetException, RuntimeException, std::exception)
99 if ( !hasMoreElements() )
100 throwNoSuchElementException();
102 return makeAny( *m_aPos++ );
106 /// an STL functor which ensures that a SdbcDriver described by a DriverAccess is loaded
107 struct EnsureDriver : public ::std::unary_function< DriverAccess, DriverAccess >
109 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 : public ::std::unary_function< DriverAccess, Reference<XDriver> >
144 Reference<XDriver> operator()( const DriverAccess& _rAccess ) const
146 return _rAccess.xDriver;
150 typedef ::o3tl::unary_compose< ExtractDriverFromAccess, EnsureDriver > ExtractAfterLoad_BASE;
151 /// an STL functor which loads a driver described by a DriverAccess, and extracts the SdbcDriver
152 struct ExtractAfterLoad : public ExtractAfterLoad_BASE
154 ExtractAfterLoad( const Reference< XComponentContext > &rxContext )
155 : ExtractAfterLoad_BASE( ExtractDriverFromAccess(), EnsureDriver( rxContext ) ) {}
158 struct ExtractDriverFromCollectionElement : public ::std::unary_function< DriverCollection::value_type, Reference<XDriver> >
160 Reference<XDriver> operator()( const DriverCollection::value_type& _rElement ) const
162 return _rElement.second;
166 // predicate for checking whether or not a driver accepts a given URL
167 class AcceptsURL : public ::std::unary_function< Reference<XDriver>, bool >
169 protected:
170 const OUString& m_rURL;
172 public:
173 // ctor
174 AcceptsURL( const OUString& _rURL ) : m_rURL( _rURL ) { }
177 bool operator()( const Reference<XDriver>& _rDriver ) const
179 // ask the driver
180 if ( _rDriver.is() && _rDriver->acceptsURL( m_rURL ) )
181 return true;
183 // does not accept ...
184 return false;
188 static sal_Int32 lcl_getDriverPrecedence( const Reference<XComponentContext>& _rContext, Sequence< OUString >& _rPrecedence )
190 _rPrecedence.realloc( 0 );
193 // some strings we need
194 const OUString sDriverManagerConfigLocation( "org.openoffice.Office.DataAccess/DriverManager" );
195 const OUString sDriverPreferenceLocation( "DriverPrecedence" );
196 const OUString sNodePathArgumentName( "nodepath" );
197 const OUString sNodeAccessServiceName( "com.sun.star.configuration.ConfigurationAccess" );
199 // create a configuration provider
200 Reference< XMultiServiceFactory > xConfigurationProvider(
201 com::sun::star::configuration::theDefaultProvider::get( _rContext ) );
203 // one argument for creating the node access: the path to the configuration node
204 Sequence< Any > aCreationArgs(1);
205 aCreationArgs[0] <<= NamedValue( sNodePathArgumentName, makeAny( sDriverManagerConfigLocation ) );
207 // create the node access
208 Reference< XNameAccess > xDriverManagerNode(xConfigurationProvider->createInstanceWithArguments(sNodeAccessServiceName, aCreationArgs), UNO_QUERY);
210 OSL_ENSURE(xDriverManagerNode.is(), "lcl_getDriverPrecedence: could not open my configuration node!");
211 if (xDriverManagerNode.is())
213 // obtain the preference list
214 Any aPreferences = xDriverManagerNode->getByName(sDriverPreferenceLocation);
215 #if OSL_DEBUG_LEVEL > 0
216 bool bSuccess =
217 #endif
218 aPreferences >>= _rPrecedence;
219 OSL_ENSURE(bSuccess || !aPreferences.hasValue(), "lcl_getDriverPrecedence: invalid value for the preferences node (no string sequence but not NULL)!");
222 catch( const Exception& )
224 DBG_UNHANDLED_EXCEPTION();
227 return _rPrecedence.getLength();
230 /// an STL argorithm compatible predicate comparing two DriverAccess instances by their implementation names
231 struct CompareDriverAccessByName : public ::std::binary_function< DriverAccess, DriverAccess, bool >
234 bool operator()( const DriverAccess& lhs, const DriverAccess& rhs )
236 return lhs.sImplementationName < rhs.sImplementationName;
240 /// and STL argorithm compatible predicate comparing a DriverAccess' impl name to a string
241 struct EqualDriverAccessToName : public ::std::binary_function< DriverAccess, OUString, bool >
243 OUString m_sImplName;
244 EqualDriverAccessToName(const OUString& _sImplName) : m_sImplName(_sImplName){}
246 bool operator()( const DriverAccess& lhs)
248 return lhs.sImplementationName.equals(m_sImplName);
253 OSDBCDriverManager::OSDBCDriverManager( const Reference< XComponentContext >& _rxContext )
254 :m_xContext( _rxContext )
255 ,m_aEventLogger( _rxContext, "org.openoffice.logging.sdbc.DriverManager" )
256 ,m_aDriverConfig(m_xContext)
257 ,m_nLoginTimeout(0)
259 // bootstrap all objects supporting the .sdb.Driver service
260 bootstrapDrivers();
262 // initialize the drivers order
263 initializeDriverPrecedence();
267 OSDBCDriverManager::~OSDBCDriverManager()
271 void OSDBCDriverManager::bootstrapDrivers()
273 Reference< XContentEnumerationAccess > xEnumAccess( m_xContext->getServiceManager(), UNO_QUERY );
274 Reference< XEnumeration > xEnumDrivers;
275 if (xEnumAccess.is())
276 xEnumDrivers = xEnumAccess->createContentEnumeration(SERVICE_SDBC_DRIVER);
278 OSL_ENSURE( xEnumDrivers.is(), "OSDBCDriverManager::bootstrapDrivers: no enumeration for the drivers available!" );
279 if (xEnumDrivers.is())
281 Reference< XSingleComponentFactory > xFactory;
282 Reference< XServiceInfo > xSI;
283 while (xEnumDrivers->hasMoreElements())
285 xFactory.set(xEnumDrivers->nextElement(), css::uno::UNO_QUERY);
286 OSL_ENSURE( xFactory.is(), "OSDBCDriverManager::bootstrapDrivers: no factory extracted" );
288 if ( xFactory.is() )
290 // we got a factory for the driver
291 DriverAccess aDriverDescriptor;
292 bool bValidDescriptor = false;
294 // can it tell us something about the implementation name?
295 xSI.set(xFactory, css::uno::UNO_QUERY);
296 if ( xSI.is() )
297 { // yes -> no need to load the driver immediately (load it later when needed)
298 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
299 aDriverDescriptor.xComponentFactory = xFactory;
300 bValidDescriptor = true;
302 m_aEventLogger.log( LogLevel::CONFIG,
303 "found SDBC driver $1$, no need to load it",
304 aDriverDescriptor.sImplementationName
307 else
309 // no -> create the driver
310 Reference< XDriver > xDriver( xFactory->createInstanceWithContext( m_xContext ), UNO_QUERY );
311 OSL_ENSURE( xDriver.is(), "OSDBCDriverManager::bootstrapDrivers: a driver which is no driver?!" );
313 if ( xDriver.is() )
315 aDriverDescriptor.xDriver = xDriver;
316 // and obtain it's implementation name
317 xSI.set(xDriver, css::uno::UNO_QUERY);
318 OSL_ENSURE( xSI.is(), "OSDBCDriverManager::bootstrapDrivers: a driver without service info?" );
319 if ( xSI.is() )
321 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
322 bValidDescriptor = true;
324 m_aEventLogger.log( LogLevel::CONFIG,
325 "found SDBC driver $1$, needed to load it",
326 aDriverDescriptor.sImplementationName
332 if ( bValidDescriptor )
334 m_aDriversBS.push_back( aDriverDescriptor );
342 void OSDBCDriverManager::initializeDriverPrecedence()
344 if ( m_aDriversBS.empty() )
345 // nothing to do
346 return;
350 // get the precedence of the drivers from the configuration
351 Sequence< OUString > aDriverOrder;
352 if ( 0 == lcl_getDriverPrecedence( m_xContext, aDriverOrder ) )
353 // nothing to do
354 return;
356 // aDriverOrder now is the list of driver implementation names in the order they should be used
358 if ( m_aEventLogger.isLoggable( LogLevel::CONFIG ) )
360 sal_Int32 nOrderedCount = aDriverOrder.getLength();
361 for ( sal_Int32 i=0; i<nOrderedCount; ++i )
362 m_aEventLogger.log( LogLevel::CONFIG,
363 "configuration's driver order: driver $1$ of $2$: $3$",
364 (sal_Int32)(i + 1), nOrderedCount, aDriverOrder[i]
368 // sort our bootstrapped drivers
369 ::std::sort( m_aDriversBS.begin(), m_aDriversBS.end(), CompareDriverAccessByName() );
371 // loop through the names in the precedence order
372 const OUString* pDriverOrder = aDriverOrder.getConstArray();
373 const OUString* pDriverOrderEnd = pDriverOrder + aDriverOrder.getLength();
375 // the first driver for which there is no preference
376 DriverAccessArray::iterator aNoPrefDriversStart = m_aDriversBS.begin();
377 // at the moment this is the first of all drivers we know
379 for ( ; ( pDriverOrder < pDriverOrderEnd ) && ( aNoPrefDriversStart != m_aDriversBS.end() ); ++pDriverOrder )
381 DriverAccess driver_order;
382 driver_order.sImplementationName = *pDriverOrder;
384 // look for the impl name in the DriverAccess array
385 ::std::pair< DriverAccessArray::iterator, DriverAccessArray::iterator > aPos =
386 ::std::equal_range( aNoPrefDriversStart, m_aDriversBS.end(), driver_order, CompareDriverAccessByName() );
388 if ( aPos.first != aPos.second )
389 { // we have a DriverAccess with this impl name
391 OSL_ENSURE( ::std::distance( aPos.first, aPos.second ) == 1,
392 "OSDBCDriverManager::initializeDriverPrecedence: more than one driver with this impl name? How this?" );
393 // move the DriverAccess pointed to by aPos.first to the position pointed to by aNoPrefDriversStart
395 if ( aPos.first != aNoPrefDriversStart )
396 { // if this does not hold, the DriverAccess alread has the correct position
398 // rotate the range [aNoPrefDriversStart, aPos.second) right 1 element
399 ::std::rotate( aNoPrefDriversStart, aPos.second - 1, aPos.second );
402 // next round we start searching and pos right
403 ++aNoPrefDriversStart;
407 catch (Exception&)
409 OSL_FAIL("OSDBCDriverManager::initializeDriverPrecedence: caught an exception while sorting the drivers!");
414 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnection( const OUString& _rURL ) throw(SQLException, RuntimeException, std::exception)
416 MutexGuard aGuard(m_aMutex);
418 m_aEventLogger.log( LogLevel::INFO,
419 "connection requested for URL $1$",
420 _rURL
423 Reference< XConnection > xConnection;
424 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
425 if (xDriver.is())
427 // TODO : handle the login timeout
428 xConnection = xDriver->connect(_rURL, Sequence< PropertyValue >());
429 // may throw an exception
430 m_aEventLogger.log( LogLevel::INFO,
431 "connection retrieved for URL $1$",
432 _rURL
436 return xConnection;
440 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnectionWithInfo( const OUString& _rURL, const Sequence< PropertyValue >& _rInfo ) throw(SQLException, RuntimeException, std::exception)
442 MutexGuard aGuard(m_aMutex);
444 m_aEventLogger.log( LogLevel::INFO,
445 "connection with info requested for URL $1$",
446 _rURL
449 Reference< XConnection > xConnection;
450 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
451 if (xDriver.is())
453 // TODO : handle the login timeout
454 xConnection = xDriver->connect(_rURL, _rInfo);
455 // may throw an exception
456 m_aEventLogger.log( LogLevel::INFO,
457 "connection with info retrieved for URL $1$",
458 _rURL
462 return xConnection;
466 void SAL_CALL OSDBCDriverManager::setLoginTimeout( sal_Int32 seconds ) throw(RuntimeException, std::exception)
468 MutexGuard aGuard(m_aMutex);
469 m_nLoginTimeout = seconds;
473 sal_Int32 SAL_CALL OSDBCDriverManager::getLoginTimeout( ) throw(RuntimeException, std::exception)
475 MutexGuard aGuard(m_aMutex);
476 return m_nLoginTimeout;
480 Reference< XEnumeration > SAL_CALL OSDBCDriverManager::createEnumeration( ) throw(RuntimeException, std::exception)
482 MutexGuard aGuard(m_aMutex);
484 ODriverEnumeration::DriverArray aDrivers;
486 // ensure that all our bootstrapped drivers are instantiated
487 ::std::for_each( m_aDriversBS.begin(), m_aDriversBS.end(), EnsureDriver( m_xContext ) );
489 // copy the bootstrapped drivers
490 ::std::transform(
491 m_aDriversBS.begin(), // "copy from" start
492 m_aDriversBS.end(), // "copy from" end
493 ::std::back_inserter( aDrivers ), // insert into
494 ExtractDriverFromAccess() // transformation to apply (extract a driver from a driver access)
497 // append the runtime drivers
498 ::std::transform(
499 m_aDriversRT.begin(), // "copy from" start
500 m_aDriversRT.end(), // "copy from" end
501 ::std::back_inserter( aDrivers ), // insert into
502 ExtractDriverFromCollectionElement() // transformation to apply (extract a driver from a driver access)
505 return new ODriverEnumeration( aDrivers );
509 ::com::sun::star::uno::Type SAL_CALL OSDBCDriverManager::getElementType( ) throw(::com::sun::star::uno::RuntimeException, std::exception)
511 return cppu::UnoType<XDriver>::get();
515 sal_Bool SAL_CALL OSDBCDriverManager::hasElements( ) throw(::com::sun::star::uno::RuntimeException, std::exception)
517 MutexGuard aGuard(m_aMutex);
518 return !(m_aDriversBS.empty() && m_aDriversRT.empty());
522 OUString SAL_CALL OSDBCDriverManager::getImplementationName( ) throw(RuntimeException, std::exception)
524 return getImplementationName_static();
527 sal_Bool SAL_CALL OSDBCDriverManager::supportsService( const OUString& _rServiceName ) throw(RuntimeException, std::exception)
529 return cppu::supportsService(this, _rServiceName);
533 Sequence< OUString > SAL_CALL OSDBCDriverManager::getSupportedServiceNames( ) throw(RuntimeException, std::exception)
535 return getSupportedServiceNames_static();
539 Reference< XInterface > SAL_CALL OSDBCDriverManager::Create( const Reference< XMultiServiceFactory >& _rxFactory )
541 return *( new OSDBCDriverManager( comphelper::getComponentContext(_rxFactory) ) );
545 OUString SAL_CALL OSDBCDriverManager::getImplementationName_static( ) throw(RuntimeException)
547 return OUString("com.sun.star.comp.sdbc.OSDBCDriverManager");
551 Sequence< OUString > SAL_CALL OSDBCDriverManager::getSupportedServiceNames_static( ) throw(RuntimeException)
553 Sequence< OUString > aSupported(1);
554 aSupported[0] = getSingletonName_static();
555 return aSupported;
559 OUString SAL_CALL OSDBCDriverManager::getSingletonName_static( ) throw(RuntimeException)
561 return OUString( "com.sun.star.sdbc.DriverManager" );
565 Reference< XInterface > SAL_CALL OSDBCDriverManager::getRegisteredObject( const OUString& _rName ) throw(Exception, RuntimeException, std::exception)
567 MutexGuard aGuard(m_aMutex);
568 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
569 if (aSearch == m_aDriversRT.end())
570 throwNoSuchElementException();
572 return aSearch->second.get();
576 void SAL_CALL OSDBCDriverManager::registerObject( const OUString& _rName, const Reference< XInterface >& _rxObject ) throw(Exception, RuntimeException, std::exception)
578 MutexGuard aGuard(m_aMutex);
580 m_aEventLogger.log( LogLevel::INFO,
581 "attempt to register new driver for name $1$",
582 _rName
585 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
586 if (aSearch == m_aDriversRT.end())
588 Reference< XDriver > xNewDriver(_rxObject, UNO_QUERY);
589 if (xNewDriver.is())
590 m_aDriversRT.insert(DriverCollection::value_type(_rName, xNewDriver));
591 else
592 throw IllegalArgumentException();
594 else
595 throw ElementExistException();
597 m_aEventLogger.log( LogLevel::INFO,
598 "new driver registered for name $1$",
599 _rName
604 void SAL_CALL OSDBCDriverManager::revokeObject( const OUString& _rName ) throw(Exception, RuntimeException, std::exception)
606 MutexGuard aGuard(m_aMutex);
608 m_aEventLogger.log( LogLevel::INFO,
609 "attempt to revoke driver for name $1$",
610 _rName
613 DriverCollection::iterator aSearch = m_aDriversRT.find(_rName);
614 if (aSearch == m_aDriversRT.end())
615 throwNoSuchElementException();
617 m_aDriversRT.erase(aSearch); // we already have the iterator so we could use it
619 m_aEventLogger.log( LogLevel::INFO,
620 "driver revoked for name $1$",
621 _rName
626 Reference< XDriver > SAL_CALL OSDBCDriverManager::getDriverByURL( const OUString& _rURL ) throw(RuntimeException, std::exception)
628 m_aEventLogger.log( LogLevel::INFO,
629 "driver requested for URL $1$",
630 _rURL
633 Reference< XDriver > xDriver( implGetDriverForURL( _rURL ) );
635 if ( xDriver.is() )
636 m_aEventLogger.log( LogLevel::INFO,
637 "driver obtained for URL $1$",
638 _rURL
641 return xDriver;
645 Reference< XDriver > OSDBCDriverManager::implGetDriverForURL(const OUString& _rURL)
647 Reference< XDriver > xReturn;
650 const OUString sDriverFactoryName = m_aDriverConfig.getDriverFactoryName(_rURL);
652 EqualDriverAccessToName aEqual(sDriverFactoryName);
653 DriverAccessArray::iterator aFind = ::std::find_if(m_aDriversBS.begin(),m_aDriversBS.end(),aEqual);
654 if ( aFind == m_aDriversBS.end() )
656 // search all bootstrapped drivers
657 aFind = ::std::find_if(
658 m_aDriversBS.begin(), // begin of search range
659 m_aDriversBS.end(), // end of search range
660 o3tl::unary_compose< AcceptsURL, ExtractAfterLoad >( AcceptsURL( _rURL ), ExtractAfterLoad( m_xContext ) )
661 // compose two functors: extract the driver from the access, then ask the resulting driver for acceptance
663 } // if ( m_aDriversBS.find(sDriverFactoryName ) == m_aDriversBS.end() )
664 else
666 EnsureDriver aEnsure( m_xContext );
667 aEnsure(*aFind);
670 // found something?
671 if ( m_aDriversBS.end() != aFind && aFind->xDriver.is() && aFind->xDriver->acceptsURL(_rURL) )
672 xReturn = aFind->xDriver;
675 if ( !xReturn.is() )
677 // no -> search the runtime drivers
678 DriverCollection::iterator aPos = ::std::find_if(
679 m_aDriversRT.begin(), // begin of search range
680 m_aDriversRT.end(), // end of search range
681 o3tl::unary_compose< AcceptsURL, ExtractDriverFromCollectionElement >( AcceptsURL( _rURL ), ExtractDriverFromCollectionElement() )
682 // compose two functors: extract the driver from the access, then ask the resulting driver for acceptance
685 if ( m_aDriversRT.end() != aPos )
686 xReturn = aPos->second;
689 return xReturn;
692 } // namespace drivermanager
694 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */