Version 4.3.0.0.beta1, tag libreoffice-4.3.0.0.beta1
[LibreOffice.git] / connectivity / source / manager / mdrivermanager.cxx
blob4e5514725176158f4b5fc8c62cc9b5937343d531
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 <stdio.h>
23 #include "mdrivermanager.hxx"
24 #include <com/sun/star/configuration/theDefaultProvider.hpp>
25 #include <com/sun/star/sdbc/XDriver.hpp>
26 #include <com/sun/star/container/XContentEnumerationAccess.hpp>
27 #include <com/sun/star/container/ElementExistException.hpp>
28 #include <com/sun/star/beans/NamedValue.hpp>
30 #include <tools/diagnose_ex.h>
31 #include <comphelper/processfactory.hxx>
32 #include <cppuhelper/implbase1.hxx>
33 #include <cppuhelper/supportsservice.hxx>
34 #include <cppuhelper/weakref.hxx>
35 #include <osl/diagnose.h>
37 #include <algorithm>
38 #include <iterator>
39 #include <vector>
41 #include <o3tl/compat_functional.hxx>
43 namespace drivermanager
46 using namespace ::com::sun::star::uno;
47 using namespace ::com::sun::star::lang;
48 using namespace ::com::sun::star::sdbc;
49 using namespace ::com::sun::star::beans;
50 using namespace ::com::sun::star::container;
51 using namespace ::com::sun::star::logging;
52 using namespace ::osl;
54 #define SERVICE_SDBC_DRIVER OUString("com.sun.star.sdbc.Driver")
56 void throwNoSuchElementException() throw(NoSuchElementException)
58 throw NoSuchElementException();
62 //= ODriverEnumeration
64 class ODriverEnumeration : public ::cppu::WeakImplHelper1< XEnumeration >
66 friend class OSDBCDriverManager;
68 typedef std::vector< Reference< XDriver > > DriverArray;
69 DriverArray m_aDrivers;
70 DriverArray::const_iterator m_aPos;
71 // order matters!
73 protected:
74 virtual ~ODriverEnumeration();
75 public:
76 ODriverEnumeration(const DriverArray& _rDriverSequence);
78 // XEnumeration
79 virtual sal_Bool SAL_CALL hasMoreElements( ) throw(RuntimeException, std::exception) SAL_OVERRIDE;
80 virtual Any SAL_CALL nextElement( ) throw(NoSuchElementException, WrappedTargetException, RuntimeException, std::exception) SAL_OVERRIDE;
84 ODriverEnumeration::ODriverEnumeration(const DriverArray& _rDriverSequence)
85 :m_aDrivers( _rDriverSequence )
86 ,m_aPos( m_aDrivers.begin() )
91 ODriverEnumeration::~ODriverEnumeration()
96 sal_Bool SAL_CALL ODriverEnumeration::hasMoreElements( ) throw(RuntimeException, std::exception)
98 return m_aPos != m_aDrivers.end();
102 Any SAL_CALL ODriverEnumeration::nextElement( ) throw(NoSuchElementException, WrappedTargetException, RuntimeException, std::exception)
104 if ( !hasMoreElements() )
105 throwNoSuchElementException();
107 return makeAny( *m_aPos++ );
111 //= helper
114 /// an STL functor which ensures that a SdbcDriver described by a DriverAccess is loaded
115 struct EnsureDriver : public ::std::unary_function< DriverAccess, DriverAccess >
117 EnsureDriver( const Reference< XComponentContext > &rxContext )
118 : mxContext( rxContext ) {}
120 const DriverAccess& operator()( const DriverAccess& _rDescriptor ) const
122 if ( !_rDescriptor.xDriver.is() )
123 // we did not load this driver, yet
124 if ( _rDescriptor.xComponentFactory.is() )
125 // we have a factory for it
126 const_cast< DriverAccess& >( _rDescriptor ).xDriver = _rDescriptor.xDriver.query(
127 _rDescriptor.xComponentFactory->createInstanceWithContext( mxContext ) );
128 return _rDescriptor;
131 private:
132 Reference< XComponentContext > mxContext;
135 /// an STL functor which extracts a SdbcDriver from a DriverAccess
136 struct ExtractDriverFromAccess : public ::std::unary_function< DriverAccess, Reference<XDriver> >
138 Reference<XDriver> operator()( const DriverAccess& _rAccess ) const
140 return _rAccess.xDriver;
144 typedef ::o3tl::unary_compose< ExtractDriverFromAccess, EnsureDriver > ExtractAfterLoad_BASE;
145 /// an STL functor which loads a driver described by a DriverAccess, and extracts the SdbcDriver
146 struct ExtractAfterLoad : public ExtractAfterLoad_BASE
148 ExtractAfterLoad( const Reference< XComponentContext > &rxContext )
149 : ExtractAfterLoad_BASE( ExtractDriverFromAccess(), EnsureDriver( rxContext ) ) {}
152 struct ExtractDriverFromCollectionElement : public ::std::unary_function< DriverCollection::value_type, Reference<XDriver> >
154 Reference<XDriver> operator()( const DriverCollection::value_type& _rElement ) const
156 return _rElement.second;
160 // predicate for checking whether or not a driver accepts a given URL
161 class AcceptsURL : public ::std::unary_function< Reference<XDriver>, bool >
163 protected:
164 const OUString& m_rURL;
166 public:
167 // ctor
168 AcceptsURL( const OUString& _rURL ) : m_rURL( _rURL ) { }
171 bool operator()( const Reference<XDriver>& _rDriver ) const
173 // ask the driver
174 if ( _rDriver.is() && _rDriver->acceptsURL( m_rURL ) )
175 return true;
177 // does not accept ...
178 return false;
182 static sal_Int32 lcl_getDriverPrecedence( const Reference<XComponentContext>& _rContext, Sequence< OUString >& _rPrecedence )
184 _rPrecedence.realloc( 0 );
187 // some strings we need
188 const OUString sDriverManagerConfigLocation( "org.openoffice.Office.DataAccess/DriverManager" );
189 const OUString sDriverPreferenceLocation( "DriverPrecedence" );
190 const OUString sNodePathArgumentName( "nodepath" );
191 const OUString sNodeAccessServiceName( "com.sun.star.configuration.ConfigurationAccess" );
193 // create a configuration provider
194 Reference< XMultiServiceFactory > xConfigurationProvider(
195 com::sun::star::configuration::theDefaultProvider::get( _rContext ) );
197 // one argument for creating the node access: the path to the configuration node
198 Sequence< Any > aCreationArgs(1);
199 aCreationArgs[0] <<= NamedValue( sNodePathArgumentName, makeAny( sDriverManagerConfigLocation ) );
201 // create the node access
202 Reference< XNameAccess > xDriverManagerNode(xConfigurationProvider->createInstanceWithArguments(sNodeAccessServiceName, aCreationArgs), UNO_QUERY);
204 OSL_ENSURE(xDriverManagerNode.is(), "lcl_getDriverPrecedence: could not open my configuration node!");
205 if (xDriverManagerNode.is())
207 // obtain the preference list
208 Any aPreferences = xDriverManagerNode->getByName(sDriverPreferenceLocation);
209 #if OSL_DEBUG_LEVEL > 0
210 bool bSuccess =
211 #endif
212 aPreferences >>= _rPrecedence;
213 OSL_ENSURE(bSuccess || !aPreferences.hasValue(), "lcl_getDriverPrecedence: invalid value for the preferences node (no string sequence but not NULL)!");
216 catch( const Exception& )
218 DBG_UNHANDLED_EXCEPTION();
221 return _rPrecedence.getLength();
224 /// an STL argorithm compatible predicate comparing two DriverAccess instances by their implementation names
225 struct CompareDriverAccessByName : public ::std::binary_function< DriverAccess, DriverAccess, bool >
228 bool operator()( const DriverAccess& lhs, const DriverAccess& rhs )
230 return lhs.sImplementationName < rhs.sImplementationName;
234 /// and STL argorithm compatible predicate comparing a DriverAccess' impl name to a string
235 struct EqualDriverAccessToName : public ::std::binary_function< DriverAccess, OUString, bool >
237 OUString m_sImplName;
238 EqualDriverAccessToName(const OUString& _sImplName) : m_sImplName(_sImplName){}
240 bool operator()( const DriverAccess& lhs)
242 return lhs.sImplementationName.equals(m_sImplName);
247 //= OSDBCDriverManager
250 OSDBCDriverManager::OSDBCDriverManager( const Reference< XComponentContext >& _rxContext )
251 :m_xContext( _rxContext )
252 ,m_aEventLogger( _rxContext, "org.openoffice.logging.sdbc.DriverManager" )
253 ,m_aDriverConfig(m_xContext)
254 ,m_nLoginTimeout(0)
256 // bootstrap all objects supporting the .sdb.Driver service
257 bootstrapDrivers();
259 // initialize the drivers order
260 initializeDriverPrecedence();
264 OSDBCDriverManager::~OSDBCDriverManager()
268 void OSDBCDriverManager::bootstrapDrivers()
270 Reference< XContentEnumerationAccess > xEnumAccess( m_xContext->getServiceManager(), UNO_QUERY );
271 Reference< XEnumeration > xEnumDrivers;
272 if (xEnumAccess.is())
273 xEnumDrivers = xEnumAccess->createContentEnumeration(SERVICE_SDBC_DRIVER);
275 OSL_ENSURE( xEnumDrivers.is(), "OSDBCDriverManager::bootstrapDrivers: no enumeration for the drivers available!" );
276 if (xEnumDrivers.is())
278 Reference< XSingleComponentFactory > xFactory;
279 Reference< XServiceInfo > xSI;
280 while (xEnumDrivers->hasMoreElements())
282 xFactory.set(xEnumDrivers->nextElement(), css::uno::UNO_QUERY);
283 OSL_ENSURE( xFactory.is(), "OSDBCDriverManager::bootstrapDrivers: no factory extracted" );
285 if ( xFactory.is() )
287 // we got a factory for the driver
288 DriverAccess aDriverDescriptor;
289 bool bValidDescriptor = false;
291 // can it tell us something about the implementation name?
292 xSI = xSI.query( xFactory );
293 if ( xSI.is() )
294 { // yes -> no need to load the driver immediately (load it later when needed)
295 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
296 aDriverDescriptor.xComponentFactory = xFactory;
297 bValidDescriptor = true;
299 m_aEventLogger.log( LogLevel::CONFIG,
300 "found SDBC driver $1$, no need to load it",
301 aDriverDescriptor.sImplementationName
304 else
306 // no -> create the driver
307 Reference< XDriver > xDriver( xFactory->createInstanceWithContext( m_xContext ), UNO_QUERY );
308 OSL_ENSURE( xDriver.is(), "OSDBCDriverManager::bootstrapDrivers: a driver which is no driver?!" );
310 if ( xDriver.is() )
312 aDriverDescriptor.xDriver = xDriver;
313 // and obtain it's implementation name
314 xSI = xSI.query( xDriver );
315 OSL_ENSURE( xSI.is(), "OSDBCDriverManager::bootstrapDrivers: a driver without service info?" );
316 if ( xSI.is() )
318 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
319 bValidDescriptor = true;
321 m_aEventLogger.log( LogLevel::CONFIG,
322 "found SDBC driver $1$, needed to load it",
323 aDriverDescriptor.sImplementationName
329 if ( bValidDescriptor )
331 m_aDriversBS.push_back( aDriverDescriptor );
339 void OSDBCDriverManager::initializeDriverPrecedence()
341 if ( m_aDriversBS.empty() )
342 // nothing to do
343 return;
347 // get the precedence of the drivers from the configuration
348 Sequence< OUString > aDriverOrder;
349 if ( 0 == lcl_getDriverPrecedence( m_xContext, aDriverOrder ) )
350 // nothing to do
351 return;
353 // aDriverOrder now is the list of driver implementation names in the order they should be used
355 if ( m_aEventLogger.isLoggable( LogLevel::CONFIG ) )
357 sal_Int32 nOrderedCount = aDriverOrder.getLength();
358 for ( sal_Int32 i=0; i<nOrderedCount; ++i )
359 m_aEventLogger.log( LogLevel::CONFIG,
360 "configuration's driver order: driver $1$ of $2$: $3$",
361 (sal_Int32)(i + 1), nOrderedCount, aDriverOrder[i]
365 // sort our bootstrapped drivers
366 ::std::sort( m_aDriversBS.begin(), m_aDriversBS.end(), CompareDriverAccessByName() );
368 // loop through the names in the precedence order
369 const OUString* pDriverOrder = aDriverOrder.getConstArray();
370 const OUString* pDriverOrderEnd = pDriverOrder + aDriverOrder.getLength();
372 // the first driver for which there is no preference
373 DriverAccessArray::iterator aNoPrefDriversStart = m_aDriversBS.begin();
374 // at the moment this is the first of all drivers we know
376 for ( ; ( pDriverOrder < pDriverOrderEnd ) && ( aNoPrefDriversStart != m_aDriversBS.end() ); ++pDriverOrder )
378 DriverAccess driver_order;
379 driver_order.sImplementationName = *pDriverOrder;
381 // look for the impl name in the DriverAccess array
382 ::std::pair< DriverAccessArray::iterator, DriverAccessArray::iterator > aPos =
383 ::std::equal_range( aNoPrefDriversStart, m_aDriversBS.end(), driver_order, CompareDriverAccessByName() );
385 if ( aPos.first != aPos.second )
386 { // we have a DriverAccess with this impl name
388 OSL_ENSURE( ::std::distance( aPos.first, aPos.second ) == 1,
389 "OSDBCDriverManager::initializeDriverPrecedence: more than one driver with this impl name? How this?" );
390 // move the DriverAccess pointed to by aPos.first to the position pointed to by aNoPrefDriversStart
392 if ( aPos.first != aNoPrefDriversStart )
393 { // if this does not hold, the DriverAccess alread has the correct position
395 // rotate the range [aNoPrefDriversStart, aPos.second) right 1 element
396 ::std::rotate( aNoPrefDriversStart, aPos.second - 1, aPos.second );
399 // next round we start searching and pos right
400 ++aNoPrefDriversStart;
404 catch (Exception&)
406 OSL_FAIL("OSDBCDriverManager::initializeDriverPrecedence: caught an exception while sorting the drivers!");
411 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnection( const OUString& _rURL ) throw(SQLException, RuntimeException, std::exception)
413 MutexGuard aGuard(m_aMutex);
415 m_aEventLogger.log( LogLevel::INFO,
416 "connection requested for URL $1$",
417 _rURL
420 Reference< XConnection > xConnection;
421 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
422 if (xDriver.is())
424 // TODO : handle the login timeout
425 xConnection = xDriver->connect(_rURL, Sequence< PropertyValue >());
426 // may throw an exception
427 m_aEventLogger.log( LogLevel::INFO,
428 "connection retrieved for URL $1$",
429 _rURL
433 return xConnection;
437 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnectionWithInfo( const OUString& _rURL, const Sequence< PropertyValue >& _rInfo ) throw(SQLException, RuntimeException, std::exception)
439 MutexGuard aGuard(m_aMutex);
441 m_aEventLogger.log( LogLevel::INFO,
442 "connection with info requested for URL $1$",
443 _rURL
446 Reference< XConnection > xConnection;
447 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
448 if (xDriver.is())
450 // TODO : handle the login timeout
451 xConnection = xDriver->connect(_rURL, _rInfo);
452 // may throw an exception
453 m_aEventLogger.log( LogLevel::INFO,
454 "connection with info retrieved for URL $1$",
455 _rURL
459 return xConnection;
463 void SAL_CALL OSDBCDriverManager::setLoginTimeout( sal_Int32 seconds ) throw(RuntimeException, std::exception)
465 MutexGuard aGuard(m_aMutex);
466 m_nLoginTimeout = seconds;
470 sal_Int32 SAL_CALL OSDBCDriverManager::getLoginTimeout( ) throw(RuntimeException, std::exception)
472 MutexGuard aGuard(m_aMutex);
473 return m_nLoginTimeout;
477 Reference< XEnumeration > SAL_CALL OSDBCDriverManager::createEnumeration( ) throw(RuntimeException, std::exception)
479 MutexGuard aGuard(m_aMutex);
481 ODriverEnumeration::DriverArray aDrivers;
483 // ensure that all our bootstrapped drivers are instantiated
484 ::std::for_each( m_aDriversBS.begin(), m_aDriversBS.end(), EnsureDriver( m_xContext ) );
486 // copy the bootstrapped drivers
487 ::std::transform(
488 m_aDriversBS.begin(), // "copy from" start
489 m_aDriversBS.end(), // "copy from" end
490 ::std::back_inserter( aDrivers ), // insert into
491 ExtractDriverFromAccess() // transformation to apply (extract a driver from a driver access)
494 // append the runtime drivers
495 ::std::transform(
496 m_aDriversRT.begin(), // "copy from" start
497 m_aDriversRT.end(), // "copy from" end
498 ::std::back_inserter( aDrivers ), // insert into
499 ExtractDriverFromCollectionElement() // transformation to apply (extract a driver from a driver access)
502 return new ODriverEnumeration( aDrivers );
506 ::com::sun::star::uno::Type SAL_CALL OSDBCDriverManager::getElementType( ) throw(::com::sun::star::uno::RuntimeException, std::exception)
508 return ::getCppuType(static_cast< Reference< XDriver >* >(NULL));
512 sal_Bool SAL_CALL OSDBCDriverManager::hasElements( ) throw(::com::sun::star::uno::RuntimeException, std::exception)
514 MutexGuard aGuard(m_aMutex);
515 return !(m_aDriversBS.empty() && m_aDriversRT.empty());
519 OUString SAL_CALL OSDBCDriverManager::getImplementationName( ) throw(RuntimeException, std::exception)
521 return getImplementationName_static();
524 sal_Bool SAL_CALL OSDBCDriverManager::supportsService( const OUString& _rServiceName ) throw(RuntimeException, std::exception)
526 return cppu::supportsService(this, _rServiceName);
530 Sequence< OUString > SAL_CALL OSDBCDriverManager::getSupportedServiceNames( ) throw(RuntimeException, std::exception)
532 return getSupportedServiceNames_static();
536 Reference< XInterface > SAL_CALL OSDBCDriverManager::Create( const Reference< XMultiServiceFactory >& _rxFactory )
538 return *( new OSDBCDriverManager( comphelper::getComponentContext(_rxFactory) ) );
542 OUString SAL_CALL OSDBCDriverManager::getImplementationName_static( ) throw(RuntimeException)
544 return OUString("com.sun.star.comp.sdbc.OSDBCDriverManager");
548 Sequence< OUString > SAL_CALL OSDBCDriverManager::getSupportedServiceNames_static( ) throw(RuntimeException)
550 Sequence< OUString > aSupported(1);
551 aSupported[0] = getSingletonName_static();
552 return aSupported;
556 OUString SAL_CALL OSDBCDriverManager::getSingletonName_static( ) throw(RuntimeException)
558 return OUString( "com.sun.star.sdbc.DriverManager" );
562 Reference< XInterface > SAL_CALL OSDBCDriverManager::getRegisteredObject( const OUString& _rName ) throw(Exception, RuntimeException, std::exception)
564 MutexGuard aGuard(m_aMutex);
565 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
566 if (aSearch == m_aDriversRT.end())
567 throwNoSuchElementException();
569 return aSearch->second.get();
573 void SAL_CALL OSDBCDriverManager::registerObject( const OUString& _rName, const Reference< XInterface >& _rxObject ) throw(Exception, RuntimeException, std::exception)
575 MutexGuard aGuard(m_aMutex);
577 m_aEventLogger.log( LogLevel::INFO,
578 "attempt to register new driver for name $1$",
579 _rName
582 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
583 if (aSearch == m_aDriversRT.end())
585 Reference< XDriver > xNewDriver(_rxObject, UNO_QUERY);
586 if (xNewDriver.is())
587 m_aDriversRT.insert(DriverCollection::value_type(_rName, xNewDriver));
588 else
589 throw IllegalArgumentException();
591 else
592 throw ElementExistException();
594 m_aEventLogger.log( LogLevel::INFO,
595 "new driver registered for name $1$",
596 _rName
601 void SAL_CALL OSDBCDriverManager::revokeObject( const OUString& _rName ) throw(Exception, RuntimeException, std::exception)
603 MutexGuard aGuard(m_aMutex);
605 m_aEventLogger.log( LogLevel::INFO,
606 "attempt to revoke driver for name $1$",
607 _rName
610 DriverCollection::iterator aSearch = m_aDriversRT.find(_rName);
611 if (aSearch == m_aDriversRT.end())
612 throwNoSuchElementException();
614 m_aDriversRT.erase(aSearch); // we already have the iterator so we could use it
616 m_aEventLogger.log( LogLevel::INFO,
617 "driver revoked for name $1$",
618 _rName
623 Reference< XDriver > SAL_CALL OSDBCDriverManager::getDriverByURL( const OUString& _rURL ) throw(RuntimeException, std::exception)
625 m_aEventLogger.log( LogLevel::INFO,
626 "driver requested for URL $1$",
627 _rURL
630 Reference< XDriver > xDriver( implGetDriverForURL( _rURL ) );
632 if ( xDriver.is() )
633 m_aEventLogger.log( LogLevel::INFO,
634 "driver obtained for URL $1$",
635 _rURL
638 return xDriver;
642 Reference< XDriver > OSDBCDriverManager::implGetDriverForURL(const OUString& _rURL)
644 Reference< XDriver > xReturn;
647 const OUString sDriverFactoryName = m_aDriverConfig.getDriverFactoryName(_rURL);
649 EqualDriverAccessToName aEqual(sDriverFactoryName);
650 DriverAccessArray::iterator aFind = ::std::find_if(m_aDriversBS.begin(),m_aDriversBS.end(),aEqual);
651 if ( aFind == m_aDriversBS.end() )
653 // search all bootstrapped drivers
654 aFind = ::std::find_if(
655 m_aDriversBS.begin(), // begin of search range
656 m_aDriversBS.end(), // end of search range
657 o3tl::unary_compose< AcceptsURL, ExtractAfterLoad >( AcceptsURL( _rURL ), ExtractAfterLoad( m_xContext ) )
658 // compose two functors: extract the driver from the access, then ask the resulting driver for acceptance
660 } // if ( m_aDriversBS.find(sDriverFactoryName ) == m_aDriversBS.end() )
661 else
663 EnsureDriver aEnsure( m_xContext );
664 aEnsure(*aFind);
667 // found something?
668 if ( m_aDriversBS.end() != aFind && aFind->xDriver.is() && aFind->xDriver->acceptsURL(_rURL) )
669 xReturn = aFind->xDriver;
672 if ( !xReturn.is() )
674 // no -> search the runtime drivers
675 DriverCollection::iterator aPos = ::std::find_if(
676 m_aDriversRT.begin(), // begin of search range
677 m_aDriversRT.end(), // end of search range
678 o3tl::unary_compose< AcceptsURL, ExtractDriverFromCollectionElement >( AcceptsURL( _rURL ), ExtractDriverFromCollectionElement() )
679 // compose two functors: extract the driver from the access, then ask the resulting driver for acceptance
682 if ( m_aDriversRT.end() != aPos )
683 xReturn = aPos->second;
686 return xReturn;
689 } // namespace drivermanager
691 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */