ctkServices.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. /*=============================================================================
  2. Library: CTK
  3. Copyright (c) 2010 German Cancer Research Center,
  4. Division of Medical and Biological Informatics
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. =============================================================================*/
  15. #include "ctkServices_p.h"
  16. #include <QStringListIterator>
  17. #include <QMutexLocker>
  18. #include <QBuffer>
  19. #include <algorithm>
  20. #include "ctkServiceFactory.h"
  21. #include "ctkPluginConstants.h"
  22. #include "ctkServiceException.h"
  23. #include "ctkServiceRegistrationPrivate.h"
  24. #include "ctkQtServiceRegistration_p.h"
  25. #include "ctkLDAPExpr.h"
  26. using namespace QtMobility;
  27. struct ServiceRegistrationComparator
  28. {
  29. bool operator()(const ctkServiceRegistration* a, const ctkServiceRegistration* b) const
  30. {
  31. return *a < *b;
  32. }
  33. };
  34. ServiceProperties ctkServices::createServiceProperties(const ServiceProperties& in,
  35. const QStringList& classes,
  36. long sid)
  37. {
  38. static qlonglong nextServiceID = 1;
  39. ServiceProperties props;
  40. if (!in.isEmpty())
  41. {
  42. for (ServiceProperties::const_iterator it = in.begin(); it != in.end(); ++it)
  43. {
  44. const QString key = it.key();
  45. const QString lcKey = it.key().toLower();
  46. for (QListIterator<QString> i(props.keys()); i.hasNext(); )
  47. {
  48. if (lcKey == i.next())
  49. {
  50. throw std::invalid_argument(std::string("Several entries for property: ") + key.toStdString());
  51. }
  52. }
  53. props.insert(lcKey, in.value(key));
  54. }
  55. }
  56. if (!classes.isEmpty())
  57. {
  58. props.insert(PluginConstants::OBJECTCLASS, classes);
  59. }
  60. props.insert(PluginConstants::SERVICE_ID, sid != -1 ? sid : nextServiceID++);
  61. return props;
  62. }
  63. ctkServices::ctkServices(ctkPluginFrameworkContext* fwCtx)
  64. : mutex(QMutex::Recursive), framework(fwCtx)
  65. {
  66. }
  67. ctkServices::~ctkServices()
  68. {
  69. clear();
  70. }
  71. void ctkServices::clear()
  72. {
  73. QList<ctkServiceRegistration*> serviceRegs = services.keys();
  74. qDeleteAll(serviceRegs);
  75. services.clear();
  76. classServices.clear();
  77. framework = 0;
  78. }
  79. ctkServiceRegistration* ctkServices::registerService(ctkPluginPrivate* plugin,
  80. const QStringList& classes,
  81. QObject* service,
  82. const ServiceProperties& properties)
  83. {
  84. if (service == 0)
  85. {
  86. throw std::invalid_argument("Can't register 0 as a service");
  87. }
  88. // Check if service implements claimed classes and that they exist.
  89. for (QStringListIterator i(classes); i.hasNext();)
  90. {
  91. QString cls = i.next();
  92. if (cls.isEmpty())
  93. {
  94. throw std::invalid_argument("Can't register as null class");
  95. }
  96. if (!(qobject_cast<ctkServiceFactory*>(service)))
  97. {
  98. if (!checkServiceClass(service, cls))
  99. {
  100. throw std::invalid_argument
  101. (std::string("Service object is not an instance of ") + cls.toStdString());
  102. }
  103. }
  104. }
  105. ctkServiceRegistration* res = new ctkServiceRegistration(plugin, service,
  106. createServiceProperties(properties, classes));
  107. {
  108. QMutexLocker lock(&mutex);
  109. services.insert(res, classes);
  110. for (QStringListIterator i(classes); i.hasNext(); )
  111. {
  112. QString currClass = i.next();
  113. QList<ctkServiceRegistration*>& s = classServices[currClass];
  114. QList<ctkServiceRegistration*>::iterator ip =
  115. std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator());
  116. s.insert(ip, res);
  117. }
  118. }
  119. //ctkServiceReference r = res->getReference();
  120. // TODO
  121. //Listeners l = bundle.fwCtx.listeners;
  122. //l.serviceChanged(l.getMatchingServiceListeners(r),
  123. // new ServiceEvent(ServiceEvent.REGISTERED, r),
  124. // null);
  125. return res;
  126. }
  127. void ctkServices::registerService(ctkPluginPrivate* plugin, QByteArray serviceDescription)
  128. {
  129. QMutexLocker lock(&mutex);
  130. QBuffer serviceBuffer(&serviceDescription);
  131. qServiceManager.addService(&serviceBuffer);
  132. QServiceManager::Error error = qServiceManager.error();
  133. if (!(error == QServiceManager::NoError || error == QServiceManager::ServiceAlreadyExists))
  134. {
  135. throw std::invalid_argument(std::string("Registering the service descriptor for plugin ")
  136. + plugin->symbolicName.toStdString() + " failed: " +
  137. getQServiceManagerErrorString(error).toStdString());
  138. }
  139. QString serviceName = plugin->symbolicName + "_" + plugin->version.toString();
  140. QList<QServiceInterfaceDescriptor> descriptors = qServiceManager.findInterfaces(serviceName);
  141. if (descriptors.isEmpty())
  142. {
  143. qDebug().nospace() << "Warning: No interfaces found for service name " << serviceName
  144. << " in plugin " << plugin->symbolicName << " (ctkVersion " << plugin->version.toString() << ")";
  145. }
  146. QListIterator<QServiceInterfaceDescriptor> it(descriptors);
  147. while (it.hasNext())
  148. {
  149. QServiceInterfaceDescriptor descr = it.next();
  150. qDebug() << "Registering:" << descr.interfaceName();
  151. QStringList classes;
  152. ServiceProperties props;
  153. QStringList customKeys = descr.customAttributes();
  154. QStringListIterator keyIt(customKeys);
  155. bool classAttrFound = false;
  156. while (keyIt.hasNext())
  157. {
  158. QString key = keyIt.next();
  159. if (key == PluginConstants::OBJECTCLASS)
  160. {
  161. classAttrFound = true;
  162. classes << descr.customAttribute(key);
  163. }
  164. else
  165. {
  166. props.insert(key, descr.customAttribute(key));
  167. }
  168. }
  169. if (!classAttrFound)
  170. {
  171. throw std::invalid_argument(std::string("The custom attribute \"") +
  172. PluginConstants::OBJECTCLASS.toStdString() +
  173. "\" is missing in the interface description of \"" +
  174. descr.interfaceName().toStdString());
  175. }
  176. ctkServiceRegistration* res = new ctkQtServiceRegistration(plugin,
  177. descr,
  178. createServiceProperties(props, classes));
  179. services.insert(res, classes);
  180. for (QStringListIterator i(classes); i.hasNext(); )
  181. {
  182. QString currClass = i.next();
  183. QList<ctkServiceRegistration*>& s = classServices[currClass];
  184. QList<ctkServiceRegistration*>::iterator ip =
  185. std::lower_bound(s.begin(), s.end(), res, ServiceRegistrationComparator());
  186. s.insert(ip, res);
  187. }
  188. //ctkServiceReference* r = res->getReference();
  189. // TODO
  190. //Listeners l = bundle.fwCtx.listeners;
  191. //l.serviceChanged(l.getMatchingServiceListeners(r),
  192. // new ServiceEvent(ServiceEvent.REGISTERED, r),
  193. // null);
  194. }
  195. }
  196. QString ctkServices::getQServiceManagerErrorString(QServiceManager::Error error)
  197. {
  198. switch (error)
  199. {
  200. case QServiceManager::NoError:
  201. return QString("No error occurred.");
  202. case QServiceManager::StorageAccessError:
  203. return QString("The service data storage is not accessible. This could be because the caller does not have the required permissions.");
  204. case QServiceManager::InvalidServiceLocation:
  205. return QString("The service was not found at its specified location.");
  206. case QServiceManager::InvalidServiceXml:
  207. return QString("The XML defining the service metadata is invalid.");
  208. case QServiceManager::InvalidServiceInterfaceDescriptor:
  209. return QString("The service interface descriptor is invalid, or refers to an interface implementation that cannot be accessed in the current scope.");
  210. case QServiceManager::ServiceAlreadyExists:
  211. return QString("Another service has previously been registered with the same location.");
  212. case QServiceManager::ImplementationAlreadyExists:
  213. return QString("Another service that implements the same interface version has previously been registered.");
  214. case QServiceManager::PluginLoadingFailed:
  215. return QString("The service plugin cannot be loaded.");
  216. case QServiceManager::ComponentNotFound:
  217. return QString("The service or interface implementation has not been registered.");
  218. case QServiceManager::ServiceCapabilityDenied:
  219. return QString("The security session does not allow the service based on its capabilities.");
  220. case QServiceManager::UnknownError:
  221. return QString("An unknown error occurred.");
  222. default:
  223. return QString("Unknown error enum.");
  224. }
  225. }
  226. void ctkServices::updateServiceRegistrationOrder(ctkServiceRegistration* sr,
  227. const QStringList& classes)
  228. {
  229. QMutexLocker lock(&mutex);
  230. for (QStringListIterator i(classes); i.hasNext(); )
  231. {
  232. QList<ctkServiceRegistration*>& s = classServices[i.next()];
  233. s.removeAll(sr);
  234. s.insert(std::lower_bound(s.begin(), s.end(), sr, ServiceRegistrationComparator()), sr);
  235. }
  236. }
  237. bool ctkServices::checkServiceClass(QObject* service, const QString& cls) const
  238. {
  239. return service->inherits(cls.toAscii());
  240. }
  241. QList<ctkServiceRegistration*> ctkServices::get(const QString& clazz) const
  242. {
  243. QMutexLocker lock(&mutex);
  244. return classServices.value(clazz);
  245. }
  246. ctkServiceReference ctkServices::get(ctkPluginPrivate* plugin, const QString& clazz) const
  247. {
  248. QMutexLocker lock(&mutex);
  249. try {
  250. QList<ctkServiceReference> srs = get(clazz, QString());
  251. qDebug() << "get service ref" << clazz << "for plugin"
  252. << plugin->location << " = " << srs.size() << "refs";
  253. if (!srs.isEmpty()) {
  254. return srs.front();
  255. }
  256. }
  257. catch (const std::invalid_argument& )
  258. { }
  259. throw ctkServiceException(QString("No service registered for: ") + clazz);
  260. }
  261. QList<ctkServiceReference> ctkServices::get(const QString& clazz, const QString& filter) const
  262. {
  263. QMutexLocker lock(&mutex);
  264. QListIterator<ctkServiceRegistration*>* s = 0;
  265. ctkLDAPExpr* ldap = 0;
  266. if (clazz.isEmpty())
  267. {
  268. if (!filter.isEmpty())
  269. {
  270. ldap = new ctkLDAPExpr(filter);
  271. QSet<QString> matched = ldap->getMatchedObjectClasses();
  272. if (!matched.isEmpty())
  273. {
  274. //TODO
  275. // ArrayList v = null;
  276. // boolean vReadOnly = true;;
  277. // for (Iterator i = matched.iterator(); i.hasNext(); ) {
  278. // ArrayList cl = (ArrayList) classServices.get(i.next());
  279. // if (cl != null) {
  280. // if (v == null) {
  281. // v = cl;
  282. // } else {
  283. // if (vReadOnly) {
  284. // v = new ArrayList(v);
  285. // vReadOnly = false;
  286. // }
  287. // v.addAll(cl);
  288. // }
  289. // }
  290. // }
  291. // if (v != null) {
  292. // s = v.iterator();
  293. // } else {
  294. // return null;
  295. // }
  296. }
  297. else
  298. {
  299. s = new QListIterator<ctkServiceRegistration*>(services.keys());
  300. }
  301. }
  302. else
  303. {
  304. s = new QListIterator<ctkServiceRegistration*>(services.keys());
  305. }
  306. }
  307. else
  308. {
  309. QList<ctkServiceRegistration*> v = classServices.value(clazz);
  310. if (!v.isEmpty())
  311. {
  312. s = new QListIterator<ctkServiceRegistration*>(v);
  313. }
  314. else
  315. {
  316. return QList<ctkServiceReference>();
  317. }
  318. if (!filter.isEmpty())
  319. {
  320. ldap = new ctkLDAPExpr(filter);
  321. }
  322. }
  323. QList<ctkServiceReference> res;
  324. while (s->hasNext())
  325. {
  326. ctkServiceRegistration* sr = s->next();
  327. ctkServiceReference sri = sr->getReference();
  328. if (filter.isEmpty() || ldap->evaluate(sr->d_func()->properties, false))
  329. {
  330. res.push_back(sri);
  331. }
  332. }
  333. delete s;
  334. delete ldap;
  335. return res;
  336. }
  337. void ctkServices::removeServiceRegistration(ctkServiceRegistration* sr)
  338. {
  339. QMutexLocker lock(&mutex);
  340. QStringList classes = sr->d_func()->properties.value(PluginConstants::OBJECTCLASS).toStringList();
  341. services.remove(sr);
  342. for (QStringListIterator i(classes); i.hasNext(); )
  343. {
  344. QString currClass = i.next();
  345. QList<ctkServiceRegistration*>& s = classServices[currClass];
  346. if (s.size() > 1)
  347. {
  348. s.removeAll(sr);
  349. }
  350. else
  351. {
  352. classServices.remove(currClass);
  353. }
  354. }
  355. }
  356. QList<ctkServiceRegistration*> ctkServices::getRegisteredByPlugin(ctkPluginPrivate* p) const
  357. {
  358. QMutexLocker lock(&mutex);
  359. QList<ctkServiceRegistration*> res;
  360. for (QHashIterator<ctkServiceRegistration*, QStringList> i(services); i.hasNext(); )
  361. {
  362. ctkServiceRegistration* sr = i.next().key();
  363. if ((sr->d_func()->plugin = p))
  364. {
  365. res.push_back(sr);
  366. }
  367. }
  368. return res;
  369. }
  370. QList<ctkServiceRegistration*> ctkServices::getUsedByPlugin(ctkPlugin* p) const
  371. {
  372. QMutexLocker lock(&mutex);
  373. QList<ctkServiceRegistration*> res;
  374. for (QHashIterator<ctkServiceRegistration*, QStringList> i(services); i.hasNext(); )
  375. {
  376. ctkServiceRegistration* sr = i.next().key();
  377. if (sr->d_func()->isUsedByPlugin(p))
  378. {
  379. res.push_back(sr);
  380. }
  381. }
  382. return res;
  383. }