calc: on editing invalidation of view with different zoom is wrong
[LibreOffice.git] / connectivity / source / manager / mdrivermanager.cxx
blob0f35c038f520853f26fd8032889958a94a81da4a
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 .
20 #include <config_fuzzers.h>
22 #include "mdrivermanager.hxx"
23 #include <com/sun/star/configuration/theDefaultProvider.hpp>
24 #include <com/sun/star/sdbc/XDriver.hpp>
25 #include <com/sun/star/container/XContentEnumerationAccess.hpp>
26 #include <com/sun/star/container/ElementExistException.hpp>
27 #include <com/sun/star/beans/NamedValue.hpp>
28 #include <com/sun/star/logging/LogLevel.hpp>
30 #include <comphelper/diagnose_ex.hxx>
31 #include <cppuhelper/implbase.hxx>
32 #include <cppuhelper/supportsservice.hxx>
33 #include <cppuhelper/weak.hxx>
34 #include <osl/diagnose.h>
36 #include <algorithm>
37 #include <iterator>
38 #include <utility>
39 #include <vector>
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 constexpr OUStringLiteral SERVICE_SDBC_DRIVER = u"com.sun.star.sdbc.Driver";
54 /// @throws NoSuchElementException
55 static void throwNoSuchElementException()
57 throw NoSuchElementException();
60 class ODriverEnumeration : public ::cppu::WeakImplHelper< XEnumeration >
62 friend class OSDBCDriverManager;
64 typedef std::vector< Reference< XDriver > > DriverArray;
65 DriverArray m_aDrivers;
66 DriverArray::const_iterator m_aPos;
67 // order matters!
69 protected:
70 virtual ~ODriverEnumeration() override;
71 public:
72 explicit ODriverEnumeration(DriverArray&& _rDriverSequence);
74 // XEnumeration
75 virtual sal_Bool SAL_CALL hasMoreElements( ) override;
76 virtual Any SAL_CALL nextElement( ) override;
80 ODriverEnumeration::ODriverEnumeration(DriverArray&& _rDriverSequence)
81 :m_aDrivers( std::move(_rDriverSequence) )
82 ,m_aPos( m_aDrivers.begin() )
87 ODriverEnumeration::~ODriverEnumeration()
92 sal_Bool SAL_CALL ODriverEnumeration::hasMoreElements( )
94 return m_aPos != m_aDrivers.end();
98 Any SAL_CALL ODriverEnumeration::nextElement( )
100 if ( !hasMoreElements() )
101 throwNoSuchElementException();
103 return Any( *m_aPos++ );
106 namespace
108 /// an STL functor which ensures that a SdbcDriver described by a DriverAccess is loaded
109 struct EnsureDriver
111 explicit EnsureDriver( const Reference< XComponentContext > &rxContext )
112 : mxContext( rxContext ) {}
114 const DriverAccess& operator()( const DriverAccess& _rDescriptor ) const
116 // we did not load this driver, yet
117 if (_rDescriptor.xDriver.is())
118 return _rDescriptor;
120 // we have a factory for it
121 if (_rDescriptor.xComponentFactory.is())
123 DriverAccess& rDesc = const_cast<DriverAccess&>(_rDescriptor);
126 //load driver
127 rDesc.xDriver.set(
128 rDesc.xComponentFactory->createInstanceWithContext(mxContext), css::uno::UNO_QUERY);
130 catch (const Exception&)
132 //failure, abandon driver
133 rDesc.xComponentFactory.clear();
136 return _rDescriptor;
139 private:
140 Reference< XComponentContext > mxContext;
143 /// an STL functor which extracts a SdbcDriver from a DriverAccess
144 struct ExtractDriverFromAccess
146 const Reference<XDriver>& operator()( const DriverAccess& _rAccess ) const
148 return _rAccess.xDriver;
152 struct ExtractDriverFromCollectionElement
154 const 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
163 protected:
164 const OUString& m_rURL;
166 public:
167 // ctor
168 explicit AcceptsURL( const OUString& _rURL ) : m_rURL( _rURL ) { }
171 bool operator()( const Reference<XDriver>& _rDriver ) const
173 // ask the driver
174 return _rDriver.is() && _rDriver->acceptsURL( m_rURL );
178 #if !ENABLE_FUZZERS
179 sal_Int32 lcl_getDriverPrecedence( const Reference<XComponentContext>& _rContext, Sequence< OUString >& _rPrecedence )
181 _rPrecedence.realloc( 0 );
184 // create a configuration provider
185 Reference< XMultiServiceFactory > xConfigurationProvider(
186 css::configuration::theDefaultProvider::get( _rContext ) );
188 // one argument for creating the node access: the path to the configuration node
189 Sequence< Any > aCreationArgs{ Any(NamedValue(
190 "nodepath", Any( OUString("org.openoffice.Office.DataAccess/DriverManager") ) )) };
192 // create the node access
193 Reference< XNameAccess > xDriverManagerNode(
194 xConfigurationProvider->createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", aCreationArgs),
195 UNO_QUERY);
197 OSL_ENSURE(xDriverManagerNode.is(), "lcl_getDriverPrecedence: could not open my configuration node!");
198 if (xDriverManagerNode.is())
200 // obtain the preference list
201 Any aPreferences = xDriverManagerNode->getByName("DriverPrecedence");
202 bool bSuccess = aPreferences >>= _rPrecedence;
203 OSL_ENSURE(bSuccess || !aPreferences.hasValue(), "lcl_getDriverPrecedence: invalid value for the preferences node (no string sequence but not NULL)!");
206 catch( const Exception& )
208 DBG_UNHANDLED_EXCEPTION("connectivity.manager");
211 return _rPrecedence.getLength();
213 #endif
215 /// an STL algorithm 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 an STL algorithm compatible predicate comparing the impl name of a DriverAccess to a string
226 struct EqualDriverAccessToName
228 OUString m_sImplName;
229 explicit EqualDriverAccessToName(OUString _sImplName) : m_sImplName(std::move(_sImplName)){}
231 bool operator()( const DriverAccess& lhs)
233 return lhs.sImplementationName == m_sImplName;
238 OSDBCDriverManager::OSDBCDriverManager( const Reference< XComponentContext >& _rxContext )
239 :OSDBCDriverManager_Base(m_aMutex)
240 ,m_xContext( _rxContext )
241 ,m_aEventLogger( _rxContext, "org.openoffice.logging.sdbc.DriverManager" )
242 ,m_aDriverConfig(m_xContext)
243 ,m_nLoginTimeout(0)
245 // bootstrap all objects supporting the .sdb.Driver service
246 bootstrapDrivers();
248 // initialize the drivers order
249 initializeDriverPrecedence();
253 OSDBCDriverManager::~OSDBCDriverManager()
257 void OSDBCDriverManager::bootstrapDrivers()
259 Reference< XContentEnumerationAccess > xEnumAccess( m_xContext->getServiceManager(), UNO_QUERY );
260 Reference< XEnumeration > xEnumDrivers;
261 if (xEnumAccess.is())
262 xEnumDrivers = xEnumAccess->createContentEnumeration(SERVICE_SDBC_DRIVER);
264 OSL_ENSURE( xEnumDrivers.is(), "OSDBCDriverManager::bootstrapDrivers: no enumeration for the drivers available!" );
265 if (!xEnumDrivers.is())
266 return;
268 Reference< XSingleComponentFactory > xFactory;
269 Reference< XServiceInfo > xSI;
270 while (xEnumDrivers->hasMoreElements())
272 xFactory.set(xEnumDrivers->nextElement(), css::uno::UNO_QUERY);
273 OSL_ENSURE( xFactory.is(), "OSDBCDriverManager::bootstrapDrivers: no factory extracted" );
275 if ( xFactory.is() )
277 // we got a factory for the driver
278 DriverAccess aDriverDescriptor;
279 bool bValidDescriptor = false;
281 // can it tell us something about the implementation name?
282 xSI.set(xFactory, css::uno::UNO_QUERY);
283 if ( xSI.is() )
284 { // yes -> no need to load the driver immediately (load it later when needed)
285 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
286 aDriverDescriptor.xComponentFactory = xFactory;
287 bValidDescriptor = true;
289 m_aEventLogger.log( LogLevel::CONFIG,
290 "found SDBC driver $1$, no need to load it",
291 aDriverDescriptor.sImplementationName
294 else
296 // no -> create the driver
297 Reference< XDriver > xDriver( xFactory->createInstanceWithContext( m_xContext ), UNO_QUERY );
298 OSL_ENSURE( xDriver.is(), "OSDBCDriverManager::bootstrapDrivers: a driver which is no driver?!" );
300 if ( xDriver.is() )
302 aDriverDescriptor.xDriver = xDriver;
303 // and obtain its implementation name
304 xSI.set(xDriver, css::uno::UNO_QUERY);
305 OSL_ENSURE( xSI.is(), "OSDBCDriverManager::bootstrapDrivers: a driver without service info?" );
306 if ( xSI.is() )
308 aDriverDescriptor.sImplementationName = xSI->getImplementationName();
309 bValidDescriptor = true;
311 m_aEventLogger.log( LogLevel::CONFIG,
312 "found SDBC driver $1$, needed to load it",
313 aDriverDescriptor.sImplementationName
319 if ( bValidDescriptor )
321 m_aDriversBS.push_back( aDriverDescriptor );
328 void OSDBCDriverManager::initializeDriverPrecedence()
330 #if !ENABLE_FUZZERS
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!");
398 #endif
402 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnection( const OUString& _rURL )
404 MutexGuard aGuard(m_aMutex);
406 m_aEventLogger.log( LogLevel::INFO,
407 "connection requested for URL $1$",
408 _rURL
411 Reference< XConnection > xConnection;
412 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
413 if (xDriver.is())
415 // TODO : handle the login timeout
416 xConnection = xDriver->connect(_rURL, Sequence< PropertyValue >());
417 // may throw an exception
418 m_aEventLogger.log( LogLevel::INFO,
419 "connection retrieved for URL $1$",
420 _rURL
424 return xConnection;
428 Reference< XConnection > SAL_CALL OSDBCDriverManager::getConnectionWithInfo( const OUString& _rURL, const Sequence< PropertyValue >& _rInfo )
430 MutexGuard aGuard(m_aMutex);
432 m_aEventLogger.log( LogLevel::INFO,
433 "connection with info requested for URL $1$",
434 _rURL
437 Reference< XConnection > xConnection;
438 Reference< XDriver > xDriver = implGetDriverForURL(_rURL);
439 if (xDriver.is())
441 // TODO : handle the login timeout
442 xConnection = xDriver->connect(_rURL, _rInfo);
443 // may throw an exception
444 m_aEventLogger.log( LogLevel::INFO,
445 "connection with info retrieved for URL $1$",
446 _rURL
450 return xConnection;
454 void SAL_CALL OSDBCDriverManager::setLoginTimeout( sal_Int32 seconds )
456 MutexGuard aGuard(m_aMutex);
457 m_nLoginTimeout = seconds;
461 sal_Int32 SAL_CALL OSDBCDriverManager::getLoginTimeout( )
463 MutexGuard aGuard(m_aMutex);
464 return m_nLoginTimeout;
468 Reference< XEnumeration > SAL_CALL OSDBCDriverManager::createEnumeration( )
470 MutexGuard aGuard(m_aMutex);
472 ODriverEnumeration::DriverArray aDrivers;
474 // ensure that all our bootstrapped drivers are instantiated
475 std::for_each( m_aDriversBS.begin(), m_aDriversBS.end(), EnsureDriver( m_xContext ) );
477 // copy the bootstrapped drivers
478 std::transform(
479 m_aDriversBS.begin(), // "copy from" start
480 m_aDriversBS.end(), // "copy from" end
481 std::back_inserter( aDrivers ), // insert into
482 ExtractDriverFromAccess() // transformation to apply (extract a driver from a driver access)
485 // append the runtime drivers
486 std::transform(
487 m_aDriversRT.begin(), // "copy from" start
488 m_aDriversRT.end(), // "copy from" end
489 std::back_inserter( aDrivers ), // insert into
490 ExtractDriverFromCollectionElement() // transformation to apply (extract a driver from a driver access)
493 return new ODriverEnumeration( std::move(aDrivers) );
497 css::uno::Type SAL_CALL OSDBCDriverManager::getElementType( )
499 return cppu::UnoType<XDriver>::get();
503 sal_Bool SAL_CALL OSDBCDriverManager::hasElements( )
505 MutexGuard aGuard(m_aMutex);
506 return !(m_aDriversBS.empty() && m_aDriversRT.empty());
510 OUString SAL_CALL OSDBCDriverManager::getImplementationName( )
512 return "com.sun.star.comp.sdbc.OSDBCDriverManager";
515 sal_Bool SAL_CALL OSDBCDriverManager::supportsService( const OUString& _rServiceName )
517 return cppu::supportsService(this, _rServiceName);
521 Sequence< OUString > SAL_CALL OSDBCDriverManager::getSupportedServiceNames( )
523 return { "com.sun.star.sdbc.DriverManager" };
527 Reference< XInterface > SAL_CALL OSDBCDriverManager::getRegisteredObject( const OUString& _rName )
529 MutexGuard aGuard(m_aMutex);
530 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
531 if (aSearch == m_aDriversRT.end())
532 throwNoSuchElementException();
534 return aSearch->second;
538 void SAL_CALL OSDBCDriverManager::registerObject( const OUString& _rName, const Reference< XInterface >& _rxObject )
540 MutexGuard aGuard(m_aMutex);
542 m_aEventLogger.log( LogLevel::INFO,
543 "attempt to register new driver for name $1$",
544 _rName
547 DriverCollection::const_iterator aSearch = m_aDriversRT.find(_rName);
548 if (aSearch != m_aDriversRT.end())
549 throw ElementExistException();
550 Reference< XDriver > xNewDriver(_rxObject, UNO_QUERY);
551 if (!xNewDriver.is())
552 throw IllegalArgumentException();
554 m_aDriversRT.emplace(_rName, xNewDriver);
556 m_aEventLogger.log( LogLevel::INFO,
557 "new driver registered for name $1$",
558 _rName
563 void SAL_CALL OSDBCDriverManager::revokeObject( const OUString& _rName )
565 MutexGuard aGuard(m_aMutex);
567 m_aEventLogger.log( LogLevel::INFO,
568 "attempt to revoke driver for name $1$",
569 _rName
572 DriverCollection::iterator aSearch = m_aDriversRT.find(_rName);
573 if (aSearch == m_aDriversRT.end())
574 throwNoSuchElementException();
576 m_aDriversRT.erase(aSearch); // we already have the iterator so we could use it
578 m_aEventLogger.log( LogLevel::INFO,
579 "driver revoked for name $1$",
580 _rName
585 Reference< XDriver > SAL_CALL OSDBCDriverManager::getDriverByURL( const OUString& _rURL )
587 m_aEventLogger.log( LogLevel::INFO,
588 "driver requested for URL $1$",
589 _rURL
592 Reference< XDriver > xDriver( implGetDriverForURL( _rURL ) );
594 if ( xDriver.is() )
595 m_aEventLogger.log( LogLevel::INFO,
596 "driver obtained for URL $1$",
597 _rURL
600 return xDriver;
604 Reference< XDriver > OSDBCDriverManager::implGetDriverForURL(const OUString& _rURL)
606 Reference< XDriver > xReturn;
609 const OUString sDriverFactoryName = m_aDriverConfig.getDriverFactoryName(_rURL);
611 EqualDriverAccessToName aEqual(sDriverFactoryName);
612 DriverAccessArray::const_iterator aFind = std::find_if(m_aDriversBS.begin(),m_aDriversBS.end(),aEqual);
613 if ( aFind == m_aDriversBS.end() )
615 // search all bootstrapped drivers
616 aFind = std::find_if(
617 m_aDriversBS.begin(), // begin of search range
618 m_aDriversBS.end(), // end of search range
619 [&_rURL, this] (const DriverAccessArray::value_type& driverAccess) {
620 // extract the driver from the access, then ask the resulting driver for acceptance
621 #if defined __GNUC__ && !defined __clang__ && __GNUC__ == 13
622 #pragma GCC diagnostic push
623 #pragma GCC diagnostic ignored "-Wdangling-reference"
624 #endif
625 const DriverAccess& ensuredAccess = EnsureDriver(m_xContext)(driverAccess);
626 #if defined __GNUC__ && !defined __clang__ && __GNUC__ == 13
627 #pragma GCC diagnostic pop
628 #endif
629 const Reference<XDriver> driver = ExtractDriverFromAccess()(ensuredAccess);
630 return AcceptsURL(_rURL)(driver);
632 } // if ( m_aDriversBS.find(sDriverFactoryName ) == m_aDriversBS.end() )
633 else
635 EnsureDriver aEnsure( m_xContext );
636 aEnsure(*aFind);
639 // found something?
640 if ( m_aDriversBS.end() != aFind && aFind->xDriver.is() && aFind->xDriver->acceptsURL(_rURL) )
641 xReturn = aFind->xDriver;
644 if ( !xReturn.is() )
646 // no -> search the runtime drivers
647 DriverCollection::const_iterator aPos = std::find_if(
648 m_aDriversRT.begin(), // begin of search range
649 m_aDriversRT.end(), // end of search range
650 [&_rURL] (const DriverCollection::value_type& element) {
651 // extract the driver from the collection element, then ask the resulting driver for acceptance
652 const Reference<XDriver> driver = ExtractDriverFromCollectionElement()(element);
653 return AcceptsURL(_rURL)(driver);
656 if ( m_aDriversRT.end() != aPos )
657 xReturn = aPos->second;
660 return xReturn;
663 } // namespace drivermanager
665 extern "C" SAL_DLLPUBLIC_EXPORT css::uno::XInterface*
666 connectivity_OSDBCDriverManager_get_implementation(
667 css::uno::XComponentContext* context , css::uno::Sequence<css::uno::Any> const&)
669 return cppu::acquire(new drivermanager::OSDBCDriverManager(context));
673 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */