QGIS API Documentation 3.41.0-Master (1deb1daf037)
Loading...
Searching...
No Matches
qgssensorthingsshareddata.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgssensorthingsshareddata.h
3 ----------------
4 begin : November 2023
5 copyright : (C) 2013 Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
19#include "qgslogger.h"
20#include "qgsreadwritelocker.h"
24#include "qgsjsonutils.h"
25
26#include <QCryptographicHash>
27#include <QFile>
28#include <nlohmann/json.hpp>
29
31
32QgsSensorThingsSharedData::QgsSensorThingsSharedData( const QString &uri )
33{
34 const QVariantMap uriParts = QgsSensorThingsProviderMetadata().decodeUri( uri );
35
36 mEntityType = qgsEnumKeyToValue( uriParts.value( QStringLiteral( "entity" ) ).toString(), Qgis::SensorThingsEntity::Invalid );
37 const QVariantList expandTo = uriParts.value( QStringLiteral( "expandTo" ) ).toList();
38 QList< Qgis::SensorThingsEntity > expandedEntities;
39 for ( const QVariant &expansionVariant : expandTo )
40 {
41 const QgsSensorThingsExpansionDefinition expansion = expansionVariant.value< QgsSensorThingsExpansionDefinition >();
42 if ( expansion.isValid() )
43 {
44 mExpansions.append( expansion );
45 expandedEntities.append( expansion.childEntity() );
46 }
47
48 mExpandQueryString = QgsSensorThingsUtils::asQueryString( mEntityType, mExpansions );
49 }
50
51 mFields = QgsSensorThingsUtils::fieldsForExpandedEntityType( mEntityType, expandedEntities );
52
53 mGeometryField = QgsSensorThingsUtils::geometryFieldForEntityType( mEntityType );
54 // use initial value of maximum page size as default
55 mMaximumPageSize = uriParts.value( QStringLiteral( "pageSize" ), mMaximumPageSize ).toInt();
56 // will default to 0 if not specified, i.e. no limit
57 mFeatureLimit = uriParts.value( QStringLiteral( "featureLimit" ) ).toInt();
58 mFilterExtent = uriParts.value( QStringLiteral( "bounds" ) ).value< QgsRectangle >();
59 mSubsetString = uriParts.value( QStringLiteral( "sql" ) ).toString();
60
62 {
63 if ( uriParts.contains( QStringLiteral( "geometryType" ) ) )
64 {
65 const QString geometryType = uriParts.value( QStringLiteral( "geometryType" ) ).toString();
66 if ( geometryType.compare( QLatin1String( "point" ), Qt::CaseInsensitive ) == 0 )
67 {
68 mGeometryType = Qgis::WkbType::PointZ;
69 }
70 else if ( geometryType.compare( QLatin1String( "multipoint" ), Qt::CaseInsensitive ) == 0 )
71 {
72 mGeometryType = Qgis::WkbType::MultiPointZ;
73 }
74 else if ( geometryType.compare( QLatin1String( "line" ), Qt::CaseInsensitive ) == 0 )
75 {
76 mGeometryType = Qgis::WkbType::MultiLineStringZ;
77 }
78 else if ( geometryType.compare( QLatin1String( "polygon" ), Qt::CaseInsensitive ) == 0 )
79 {
80 mGeometryType = Qgis::WkbType::MultiPolygonZ;
81 }
82
83 if ( mGeometryType != Qgis::WkbType::NoGeometry )
84 {
85 // geometry is always GeoJSON spec (for now, at least), so CRS will always be WGS84
86 mSourceCRS = QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) );
87 }
88 }
89 else
90 {
91 mGeometryType = Qgis::WkbType::NoGeometry;
92 }
93 }
94 else
95 {
96 mGeometryType = Qgis::WkbType::NoGeometry;
97 }
98
99 const QgsDataSourceUri dsUri( uri );
100 mAuthCfg = dsUri.authConfigId();
101 mHeaders = dsUri.httpHeaders();
102
103 mRootUri = uriParts.value( QStringLiteral( "url" ) ).toString();
104}
105
106QUrl QgsSensorThingsSharedData::parseUrl( const QUrl &url, bool *isTestEndpoint )
107{
108 if ( isTestEndpoint )
109 *isTestEndpoint = false;
110
111 QUrl modifiedUrl( url );
112 if ( modifiedUrl.toString().contains( QLatin1String( "fake_qgis_http_endpoint" ) ) )
113 {
114 if ( isTestEndpoint )
115 *isTestEndpoint = true;
116
117 // Just for testing with local files instead of http:// resources
118 QString modifiedUrlString = modifiedUrl.toString();
119 // Qt5 does URL encoding from some reason (of the FILTER parameter for example)
120 modifiedUrlString = QUrl::fromPercentEncoding( modifiedUrlString.toUtf8() );
121 modifiedUrlString.replace( QLatin1String( "fake_qgis_http_endpoint/" ), QLatin1String( "fake_qgis_http_endpoint_" ) );
122 QgsDebugMsgLevel( QStringLiteral( "Get %1" ).arg( modifiedUrlString ), 2 );
123 modifiedUrlString = modifiedUrlString.mid( QStringLiteral( "http://" ).size() );
124 QString args = modifiedUrlString.indexOf( '?' ) >= 0 ? modifiedUrlString.mid( modifiedUrlString.indexOf( '?' ) ) : QString();
125 if ( modifiedUrlString.size() > 150 )
126 {
127 args = QCryptographicHash::hash( args.toUtf8(), QCryptographicHash::Md5 ).toHex();
128 }
129 else
130 {
131 args.replace( QLatin1String( "?" ), QLatin1String( "_" ) );
132 args.replace( QLatin1String( "&" ), QLatin1String( "_" ) );
133 args.replace( QLatin1String( "$" ), QLatin1String( "_" ) );
134 args.replace( QLatin1String( "<" ), QLatin1String( "_" ) );
135 args.replace( QLatin1String( ">" ), QLatin1String( "_" ) );
136 args.replace( QLatin1String( "'" ), QLatin1String( "_" ) );
137 args.replace( QLatin1String( "\"" ), QLatin1String( "_" ) );
138 args.replace( QLatin1String( " " ), QLatin1String( "_" ) );
139 args.replace( QLatin1String( ":" ), QLatin1String( "_" ) );
140 args.replace( QLatin1String( "/" ), QLatin1String( "_" ) );
141 args.replace( QLatin1String( "\n" ), QLatin1String( "_" ) );
142 }
143#ifdef Q_OS_WIN
144 // Passing "urls" like "http://c:/path" to QUrl 'eats' the : after c,
145 // so we must restore it
146 if ( modifiedUrlString[1] == '/' )
147 {
148 modifiedUrlString = modifiedUrlString[0] + ":/" + modifiedUrlString.mid( 2 );
149 }
150#endif
151 modifiedUrlString = modifiedUrlString.mid( 0, modifiedUrlString.indexOf( '?' ) ) + args;
152 QgsDebugMsgLevel( QStringLiteral( "Get %1 (after laundering)" ).arg( modifiedUrlString ), 2 );
153 modifiedUrl = QUrl::fromLocalFile( modifiedUrlString );
154 if ( !QFile::exists( modifiedUrlString ) )
155 {
156 QgsDebugError( QStringLiteral( "Local test file %1 for URL %2 does not exist!!!" ).arg( modifiedUrlString, url.toString() ) );
157 }
158 }
159
160 return modifiedUrl;
161}
162
163QgsRectangle QgsSensorThingsSharedData::extent() const
164{
165 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
166
167 // Since we can't retrieve the actual layer extent via SensorThings API, we use a pessimistic
168 // global extent until we've retrieved all the features from the layer
169 return hasCachedAllFeatures() ? mFetchedFeatureExtent
170 : ( !mFilterExtent.isNull() ? mFilterExtent : QgsRectangle( -180, -90, 180, 90 ) );
171}
172
173long long QgsSensorThingsSharedData::featureCount( QgsFeedback *feedback ) const
174{
175 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
176 if ( mFeatureCount >= 0 )
177 return mFeatureCount;
178
179 locker.changeMode( QgsReadWriteLocker::Write );
180 mError.clear();
181
182 // MISSING PART -- how to handle feature count when we are expanding features?
183 // This situation is not handled by the SensorThings standard at all, so we'll just have
184 // to return an unknown count whenever expansion is used
185 if ( !mExpansions.isEmpty() )
186 {
187 return static_cast< long long >( Qgis::FeatureCountState::UnknownCount );
188 }
189
190 // return no features, just the total count
191 QString countUri = QStringLiteral( "%1?$top=0&$count=true" ).arg( mEntityBaseUri );
192 const QString typeFilter = QgsSensorThingsUtils::filterForWkbType( mEntityType, mGeometryType );
193 const QString extentFilter = QgsSensorThingsUtils::filterForExtent( mGeometryField, mFilterExtent );
194 QString filterString = QgsSensorThingsUtils::combineFilters( { typeFilter, extentFilter, mSubsetString } );
195 if ( !filterString.isEmpty() )
196 filterString = QStringLiteral( "&$filter=" ) + filterString;
197 if ( !filterString.isEmpty() )
198 countUri += filterString;
199
200 const QUrl url = parseUrl( QUrl( countUri ) );
201
202 QNetworkRequest request( url );
203 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsSensorThingsSharedData" ) );
204 mHeaders.updateNetworkRequest( request );
205
206 QgsBlockingNetworkRequest networkRequest;
207 networkRequest.setAuthCfg( mAuthCfg );
208 const QgsBlockingNetworkRequest::ErrorCode error = networkRequest.get( request, false, feedback );
209
210 if ( feedback && feedback->isCanceled() )
211 return mFeatureCount;
212
213 // Handle network errors
215 {
216 QgsDebugError( QStringLiteral( "Network error: %1" ).arg( networkRequest.errorMessage() ) );
217 mError = networkRequest.errorMessage();
218 }
219 else
220 {
221 const QgsNetworkReplyContent content = networkRequest.reply();
222 try
223 {
224 auto rootContent = json::parse( content.content().toStdString() );
225 if ( !rootContent.contains( "@iot.count" ) )
226 {
227 mError = QObject::tr( "No '@iot.count' value in response" );
228 return mFeatureCount;
229 }
230
231 mFeatureCount = rootContent["@iot.count"].get<long long>();
232 if ( mFeatureLimit > 0 && mFeatureCount > mFeatureLimit )
233 mFeatureCount = mFeatureLimit;
234 }
235 catch ( const json::parse_error &ex )
236 {
237 mError = QObject::tr( "Error parsing response: %1" ).arg( ex.what() );
238 }
239 }
240
241 return mFeatureCount;
242}
243
244QString QgsSensorThingsSharedData::subsetString() const
245{
246 return mSubsetString;
247}
248
249bool QgsSensorThingsSharedData::hasCachedAllFeatures() const
250{
251 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
252 return mHasCachedAllFeatures
253 || ( mFeatureCount > 0 && mCachedFeatures.size() == mFeatureCount )
254 || ( mFeatureLimit > 0 && mRetrievedBaseFeatureCount >= mFeatureLimit );
255}
256
257bool QgsSensorThingsSharedData::getFeature( QgsFeatureId id, QgsFeature &f, QgsFeedback *feedback )
258{
259 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
260
261 // If cached, return cached feature
262 QMap<QgsFeatureId, QgsFeature>::const_iterator it = mCachedFeatures.constFind( id );
263 if ( it != mCachedFeatures.constEnd() )
264 {
265 f = it.value();
266 return true;
267 }
268
269 if ( hasCachedAllFeatures() )
270 return false; // all features are cached, and we didn't find a match
271
272 bool featureFetched = false;
273
274 if ( mNextPage.isEmpty() )
275 {
276 locker.changeMode( QgsReadWriteLocker::Write );
277
278 int thisPageSize = mMaximumPageSize;
279 if ( mFeatureLimit > 0 && ( mCachedFeatures.size() + thisPageSize ) > mFeatureLimit )
280 thisPageSize = mFeatureLimit - mCachedFeatures.size();
281
282 mNextPage = QStringLiteral( "%1?$top=%2&$count=false%3" ).arg( mEntityBaseUri ).arg( thisPageSize ).arg( !mExpandQueryString.isEmpty() ? ( QStringLiteral( "&" ) + mExpandQueryString ) : QString() );
283 const QString typeFilter = QgsSensorThingsUtils::filterForWkbType( mEntityType, mGeometryType );
284 const QString extentFilter = QgsSensorThingsUtils::filterForExtent( mGeometryField, mFilterExtent );
285 const QString filterString = QgsSensorThingsUtils::combineFilters( { typeFilter, extentFilter, mSubsetString } );
286 if ( !filterString.isEmpty() )
287 mNextPage += QStringLiteral( "&$filter=" ) + filterString;
288 }
289
290 locker.unlock();
291
292 processFeatureRequest( mNextPage, feedback, [id, &f, &featureFetched]( const QgsFeature & feature )
293 {
294 if ( feature.id() == id )
295 {
296 f = feature;
297 featureFetched = true;
298 // don't break here -- store all the features we retrieved in this page first!
299 }
300 }, [&featureFetched, this]
301 {
302 return !featureFetched && !hasCachedAllFeatures();
303 }, [this]
304 {
305 mNextPage.clear();
306 mHasCachedAllFeatures = true;
307 } );
308
309 return featureFetched;
310}
311
312QgsFeatureIds QgsSensorThingsSharedData::getFeatureIdsInExtent( const QgsRectangle &extent, QgsFeedback *feedback, const QString &thisPage, QString &nextPage, const QgsFeatureIds &alreadyFetchedIds )
313{
314 const QgsRectangle requestExtent = mFilterExtent.isNull() ? extent : extent.intersect( mFilterExtent );
315 const QgsGeometry extentGeom = QgsGeometry::fromRect( requestExtent );
316 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
317
318 if ( hasCachedAllFeatures() || mCachedExtent.contains( extentGeom ) )
319 {
320 // all features cached locally, rely on local spatial index
321 nextPage.clear();
322 return qgis::listToSet( mSpatialIndex.intersects( requestExtent ) );
323 }
324
325 const QString typeFilter = QgsSensorThingsUtils::filterForWkbType( mEntityType, mGeometryType );
326 const QString extentFilter = QgsSensorThingsUtils::filterForExtent( mGeometryField, requestExtent );
327 QString filterString = QgsSensorThingsUtils::combineFilters( { typeFilter, extentFilter, mSubsetString } );
328 if ( !filterString.isEmpty() )
329 filterString = QStringLiteral( "&$filter=" ) + filterString;
330 int thisPageSize = mMaximumPageSize;
331 QString queryUrl;
332 if ( !thisPage.isEmpty() )
333 {
334 queryUrl = thisPage;
335 const thread_local QRegularExpression topRe( QStringLiteral( "\\$top=\\d+" ) );
336 const QRegularExpressionMatch match = topRe.match( queryUrl );
337 if ( match.hasMatch() )
338 {
339 if ( mFeatureLimit > 0 && ( mCachedFeatures.size() + thisPageSize ) > mFeatureLimit )
340 thisPageSize = mFeatureLimit - mCachedFeatures.size();
341 queryUrl = queryUrl.left( match.capturedStart( 0 ) ) + QStringLiteral( "$top=%1" ).arg( thisPageSize ) + queryUrl.mid( match.capturedEnd( 0 ) );
342 }
343 }
344 else
345 {
346 queryUrl = QStringLiteral( "%1?$top=%2&$count=false%3%4" ).arg( mEntityBaseUri ).arg( thisPageSize ).arg( filterString, !mExpandQueryString.isEmpty() ? ( QStringLiteral( "&" ) + mExpandQueryString ) : QString() );
347 }
348
349 if ( thisPage.isEmpty() && mCachedExtent.intersects( extentGeom ) )
350 {
351 // we have SOME of the results from this extent cached. Let's return those first.
352 // This is slightly nicer from a rendering point of view, because panning the map won't see features
353 // previously visible disappear temporarily while we wait for them to be included in the service's result set...
354 nextPage = queryUrl;
355 return qgis::listToSet( mSpatialIndex.intersects( requestExtent ) );
356 }
357
358 locker.unlock();
359
360 QgsFeatureIds ids;
361
362 bool noMoreFeatures = false;
363 bool hasFirstPage = false;
364 const bool res = processFeatureRequest( queryUrl, feedback, [&ids, &alreadyFetchedIds]( const QgsFeature & feature )
365 {
366 if ( !alreadyFetchedIds.contains( feature.id() ) )
367 ids.insert( feature.id() );
368 }, [&hasFirstPage]
369 {
370 if ( !hasFirstPage )
371 {
372 hasFirstPage = true;
373 return true;
374 }
375
376 return false;
377 }, [&noMoreFeatures]
378 {
379 noMoreFeatures = true;
380 } );
381 if ( noMoreFeatures && res && ( !feedback || !feedback->isCanceled() ) )
382 {
383 locker.changeMode( QgsReadWriteLocker::Write );
384 mCachedExtent = QgsGeometry::unaryUnion( { mCachedExtent, extentGeom } );
385 }
386 nextPage = noMoreFeatures || !res ? QString() : queryUrl;
387
388 return ids;
389}
390
391void QgsSensorThingsSharedData::clearCache()
392{
393 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Write );
394
395 mFeatureCount = static_cast< long long >( Qgis::FeatureCountState::Uncounted );
396 mCachedFeatures.clear();
397 mIotIdToFeatureId.clear();
398 mSpatialIndex = QgsSpatialIndex();
399 mFetchedFeatureExtent = QgsRectangle();
400}
401
402bool QgsSensorThingsSharedData::processFeatureRequest( QString &nextPage, QgsFeedback *feedback, const std::function< void( const QgsFeature & ) > &fetchedFeatureCallback, const std::function<bool ()> &continueFetchingCallback, const std::function<void ()> &onNoMoreFeaturesCallback )
403{
404 // copy some members before we unlock the read/write locker
405
406 QgsReadWriteLocker locker( mReadWriteLock, QgsReadWriteLocker::Read );
407 const QString authcfg = mAuthCfg;
408 const QgsHttpHeaders headers = mHeaders;
409 const QgsFields fields = mFields;
410 const QList< QgsSensorThingsExpansionDefinition > expansions = mExpansions;
411
412 while ( continueFetchingCallback() )
413 {
414 // don't lock while doing the fetch
415 locker.unlock();
416
417 // from: https://docs.ogc.org/is/18-088/18-088.html#nextLink
418 // "SensorThings clients SHALL treat the URL of the nextLink as opaque, and SHALL NOT append system query options to the URL of a next link"
419 //
420 // ie don't mess with this URL!!
421 const QUrl url = parseUrl( nextPage );
422
423 QNetworkRequest request( url );
424 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsSensorThingsSharedData" ) );
425 headers.updateNetworkRequest( request );
426
427 QgsBlockingNetworkRequest networkRequest;
428 networkRequest.setAuthCfg( authcfg );
429 const QgsBlockingNetworkRequest::ErrorCode error = networkRequest.get( request, false, feedback );
430 if ( feedback && feedback->isCanceled() )
431 {
432 return false;
433 }
434
436 {
437 QgsDebugError( QStringLiteral( "Network error: %1" ).arg( networkRequest.errorMessage() ) );
438 locker.changeMode( QgsReadWriteLocker::Write );
439 mError = networkRequest.errorMessage();
440 QgsDebugMsgLevel( QStringLiteral( "Query returned empty result" ), 2 );
441 return false;
442 }
443 else
444 {
445 const QgsNetworkReplyContent content = networkRequest.reply();
446 try
447 {
448 const auto rootContent = json::parse( content.content().toStdString() );
449 if ( !rootContent.contains( "value" ) )
450 {
451 locker.changeMode( QgsReadWriteLocker::Write );
452 mError = QObject::tr( "No 'value' in response" );
453 QgsDebugMsgLevel( QStringLiteral( "No 'value' in response" ), 2 );
454 return false;
455 }
456 else
457 {
458 // all good, got a batch of features
459 const auto &values = rootContent["value"];
460 if ( values.empty() )
461 {
462 locker.changeMode( QgsReadWriteLocker::Write );
463
464 onNoMoreFeaturesCallback();
465
466 return true;
467 }
468 else
469 {
470 locker.changeMode( QgsReadWriteLocker::Write );
471 for ( const auto &featureData : values )
472 {
473 auto getString = []( const basic_json<> &json, const char *tag ) -> QVariant
474 {
475 if ( !json.contains( tag ) )
476 return QVariant();
477
478 std::function< QString( const basic_json<> &obj, bool &ok ) > objToString;
479 objToString = [&objToString]( const basic_json<> &obj, bool & ok ) -> QString
480 {
481 ok = true;
482 if ( obj.is_number_integer() )
483 {
484 return QString::number( obj.get<int>() );
485 }
486 else if ( obj.is_number_unsigned() )
487 {
488 return QString::number( obj.get<unsigned>() );
489 }
490 else if ( obj.is_boolean() )
491 {
492 return QString::number( obj.get<bool>() );
493 }
494 else if ( obj.is_number_float() )
495 {
496 return QString::number( obj.get<double>() );
497 }
498 else if ( obj.is_array() )
499 {
500 QStringList results;
501 results.reserve( obj.size() );
502 for ( const auto &item : obj )
503 {
504 bool itemOk = false;
505 const QString itemString = objToString( item, itemOk );
506 if ( itemOk )
507 results.push_back( itemString );
508 }
509 return results.join( ',' );
510 }
511 else if ( obj.is_string() )
512 {
513 return QString::fromStdString( obj.get<std::string >() );
514 }
515
516 ok = false;
517 return QString();
518 };
519
520 const auto &jObj = json[tag];
521 bool ok = false;
522 const QString r = objToString( jObj, ok );
523 if ( ok )
524 return r;
525 return QVariant();
526 };
527
528 auto getDateTime = []( const basic_json<> &json, const char *tag ) -> QVariant
529 {
530 if ( !json.contains( tag ) )
531 return QVariant();
532
533 const auto &jObj = json[tag];
534 if ( jObj.is_string() )
535 {
536 const QString dateTimeString = QString::fromStdString( json[tag].get<std::string >() );
537 return QDateTime::fromString( dateTimeString, Qt::ISODateWithMs );
538 }
539
540 return QVariant();
541 };
542
543 auto getVariantMap = []( const basic_json<> &json, const char *tag ) -> QVariant
544 {
545 if ( !json.contains( tag ) )
546 return QVariant();
547
548 return QgsJsonUtils::jsonToVariant( json[tag] );
549 };
550
551 auto getVariantList = []( const basic_json<> &json, const char *tag ) -> QVariant
552 {
553 if ( !json.contains( tag ) )
554 return QVariant();
555
556 return QgsJsonUtils::jsonToVariant( json[tag] );
557 };
558
559 auto getStringList = []( const basic_json<> &json, const char *tag ) -> QVariant
560 {
561 if ( !json.contains( tag ) )
562 return QVariant();
563
564 const auto &jObj = json[tag];
565 if ( jObj.is_string() )
566 {
567 return QStringList{ QString::fromStdString( json[tag].get<std::string >() ) };
568 }
569 else if ( jObj.is_array() )
570 {
571 QStringList res;
572 for ( const auto &element : jObj )
573 {
574 if ( element.is_string() )
575 res.append( QString::fromStdString( element.get<std::string >() ) );
576 }
577 return res;
578 }
579
580 return QVariant();
581 };
582
583 auto getDateTimeRange = []( const basic_json<> &json, const char *tag ) -> std::pair< QVariant, QVariant >
584 {
585 if ( !json.contains( tag ) )
586 return { QVariant(), QVariant() };
587
588 const auto &jObj = json[tag];
589 if ( jObj.is_string() )
590 {
591 const QString rangeString = QString::fromStdString( json[tag].get<std::string >() );
592 const QStringList rangeParts = rangeString.split( '/' );
593 if ( rangeParts.size() == 2 )
594 {
595 return
596 {
597 QDateTime::fromString( rangeParts.at( 0 ), Qt::ISODateWithMs ),
598 QDateTime::fromString( rangeParts.at( 1 ), Qt::ISODateWithMs )
599 };
600 }
601 else
602 {
603 const QDateTime instant = QDateTime::fromString( rangeString, Qt::ISODateWithMs );
604 if ( instant.isValid() )
605 return { instant, instant };
606 }
607 }
608
609 return { QVariant(), QVariant() };
610 };
611
612 const QString iotId = getString( featureData, "@iot.id" ).toString();
613 if ( expansions.isEmpty() )
614 {
615 auto existingFeatureIdIt = mIotIdToFeatureId.constFind( iotId );
616 if ( existingFeatureIdIt != mIotIdToFeatureId.constEnd() )
617 {
618 // we've previously fetched and cached this feature, skip it
619 fetchedFeatureCallback( *mCachedFeatures.find( *existingFeatureIdIt ) );
620 continue;
621 }
622 }
623
624 QgsFeature feature( fields );
625
626 // Set geometry
627 if ( mGeometryType != Qgis::WkbType::NoGeometry )
628 {
629 if ( featureData.contains( mGeometryField.toLocal8Bit().constData() ) )
630 {
631 const auto &geometryPart = featureData[mGeometryField.toLocal8Bit().constData()];
632 if ( geometryPart.contains( "geometry" ) )
633 feature.setGeometry( QgsJsonUtils::geometryFromGeoJson( geometryPart["geometry"] ) );
634 else
635 feature.setGeometry( QgsJsonUtils::geometryFromGeoJson( geometryPart ) );
636 }
637 }
638
639 auto extendAttributes = [&getString, &getVariantMap, &getDateTimeRange, &getDateTime, &getStringList, &getVariantList]( Qgis::SensorThingsEntity entityType, const auto & entityData, QgsAttributes & attributes )
640 {
641 const QString iotId = getString( entityData, "@iot.id" ).toString();
642 const QString selfLink = getString( entityData, "@iot.selfLink" ).toString();
643
644 const QVariant properties = getVariantMap( entityData, "properties" );
645
646 // NOLINTBEGIN(bugprone-branch-clone)
647 switch ( entityType )
648 {
650 break;
651
653 attributes
654 << iotId
655 << selfLink
656 << getString( entityData, "name" )
657 << getString( entityData, "description" )
658 << properties;
659 break;
660
662 attributes
663 << iotId
664 << selfLink
665 << getString( entityData, "name" )
666 << getString( entityData, "description" )
667 << properties;
668 break;
669
671 attributes
672 << iotId
673 << selfLink
674 << getDateTime( entityData, "time" );
675 break;
676
678 {
679 std::pair< QVariant, QVariant > phenomenonTime = getDateTimeRange( entityData, "phenomenonTime" );
680 std::pair< QVariant, QVariant > resultTime = getDateTimeRange( entityData, "resultTime" );
681 attributes
682 << iotId
683 << selfLink
684 << getString( entityData, "name" )
685 << getString( entityData, "description" )
686 << getVariantMap( entityData, "unitOfMeasurement" )
687 << getString( entityData, "observationType" )
688 << properties
689 << phenomenonTime.first
690 << phenomenonTime.second
691 << resultTime.first
692 << resultTime.second;
693 break;
694 }
695
697 attributes
698 << iotId
699 << selfLink
700 << getString( entityData, "name" )
701 << getString( entityData, "description" )
702 << getString( entityData, "metadata" )
703 << properties;
704 break;
705
707 attributes
708 << iotId
709 << selfLink
710 << getString( entityData, "name" )
711 << getString( entityData, "definition" )
712 << getString( entityData, "description" )
713 << properties;
714 break;
715
717 {
718 std::pair< QVariant, QVariant > phenomenonTime = getDateTimeRange( entityData, "phenomenonTime" );
719 std::pair< QVariant, QVariant > validTime = getDateTimeRange( entityData, "validTime" );
720 attributes
721 << iotId
722 << selfLink
723 << phenomenonTime.first
724 << phenomenonTime.second
725 << getString( entityData, "result" ) // TODO -- result type handling!
726 << getDateTime( entityData, "resultTime" )
727 << getStringList( entityData, "resultQuality" )
728 << validTime.first
729 << validTime.second
730 << getVariantMap( entityData, "parameters" );
731 break;
732 }
733
735 attributes
736 << iotId
737 << selfLink
738 << getString( entityData, "name" )
739 << getString( entityData, "description" )
740 << properties;
741 break;
742
744 {
745 std::pair< QVariant, QVariant > phenomenonTime = getDateTimeRange( entityData, "phenomenonTime" );
746 std::pair< QVariant, QVariant > resultTime = getDateTimeRange( entityData, "resultTime" );
747 attributes
748 << iotId
749 << selfLink
750 << getString( entityData, "name" )
751 << getString( entityData, "description" )
752 << getVariantList( entityData, "unitOfMeasurements" )
753 << getString( entityData, "observationType" )
754 << getStringList( entityData, "multiObservationDataTypes" )
755 << properties
756 << phenomenonTime.first
757 << phenomenonTime.second
758 << resultTime.first
759 << resultTime.second;
760 break;
761 }
762 }
763 // NOLINTEND(bugprone-branch-clone)
764 };
765
766 QgsAttributes attributes;
767 attributes.reserve( fields.size() );
768 extendAttributes( mEntityType, featureData, attributes );
769
770 auto processFeature = [this, &fetchedFeatureCallback]( QgsFeature & feature, const QString & rawFeatureId )
771 {
772 feature.setId( mNextFeatureId++ );
773
774 mCachedFeatures.insert( feature.id(), feature );
775 mIotIdToFeatureId.insert( rawFeatureId, feature.id() );
776 mSpatialIndex.addFeature( feature );
777 mFetchedFeatureExtent.combineExtentWith( feature.geometry().boundingBox() );
778
779 fetchedFeatureCallback( feature );
780 };
781
782 const QString baseFeatureId = getString( featureData, "@iot.id" ).toString();
783 if ( !expansions.empty() )
784 {
785 mRetrievedBaseFeatureCount++;
786
787 std::function< void( const nlohmann::json &, Qgis::SensorThingsEntity, const QList<QgsSensorThingsExpansionDefinition > &, const QString &, const QgsAttributes & ) > traverseExpansion;
788 traverseExpansion = [this, &feature, &getString, &traverseExpansion, &fetchedFeatureCallback, &extendAttributes, &processFeature]( const nlohmann::json & currentLevelData, Qgis::SensorThingsEntity parentEntityType, const QList<QgsSensorThingsExpansionDefinition > &expansionTargets, const QString & lowerLevelId, const QgsAttributes & lowerLevelAttributes )
789 {
790 const QgsSensorThingsExpansionDefinition currentExpansionTarget = expansionTargets.at( 0 );
791 const QList< QgsSensorThingsExpansionDefinition > remainingExpansionTargets = expansionTargets.mid( 1 );
792
793 bool ok = false;
794 const Qgis::RelationshipCardinality cardinality = QgsSensorThingsUtils::relationshipCardinality( parentEntityType, currentExpansionTarget.childEntity(), ok );
795 QString currentExpansionPropertyString;
796 switch ( cardinality )
797 {
800 currentExpansionPropertyString = qgsEnumValueToKey( currentExpansionTarget.childEntity() );
801 break;
802
805 currentExpansionPropertyString = QgsSensorThingsUtils::entityToSetString( currentExpansionTarget.childEntity() );
806 break;
807 }
808
809 if ( currentLevelData.contains( currentExpansionPropertyString.toLocal8Bit().constData() ) )
810 {
811 auto parseExpandedEntity = [lowerLevelAttributes, &feature, &processFeature, &lowerLevelId, &getString, &remainingExpansionTargets, &fetchedFeatureCallback, &extendAttributes, &traverseExpansion, &currentExpansionTarget, this]( const json & expandedEntityElement )
812 {
813 QgsAttributes expandedAttributes = lowerLevelAttributes;
814 const QString expandedEntityIotId = getString( expandedEntityElement, "@iot.id" ).toString();
815 const QString expandedFeatureId = lowerLevelId + '_' + expandedEntityIotId;
816
817 if ( remainingExpansionTargets.empty() )
818 {
819 auto existingFeatureIdIt = mIotIdToFeatureId.constFind( expandedFeatureId );
820 if ( existingFeatureIdIt != mIotIdToFeatureId.constEnd() )
821 {
822 // we've previously fetched and cached this feature, skip it
823 fetchedFeatureCallback( *mCachedFeatures.find( *existingFeatureIdIt ) );
824 return;
825 }
826 }
827
828 extendAttributes( currentExpansionTarget.childEntity(), expandedEntityElement, expandedAttributes );
829 if ( !remainingExpansionTargets.empty() )
830 {
831 // traverse deeper
832 traverseExpansion( expandedEntityElement, currentExpansionTarget.childEntity(), remainingExpansionTargets, expandedFeatureId, expandedAttributes );
833 }
834 else
835 {
836 feature.setAttributes( expandedAttributes );
837 processFeature( feature, expandedFeatureId );
838 }
839 };
840 const auto &expandedEntity = currentLevelData[currentExpansionPropertyString.toLocal8Bit().constData()];
841 if ( expandedEntity.is_array() )
842 {
843 for ( const auto &expandedEntityElement : expandedEntity )
844 {
845 parseExpandedEntity( expandedEntityElement );
846 }
847 // NOTE: What do we do when the expanded entity has a next link? Does this situation ever arise?
848 // The specification doesn't explicitly state whether pagination is supported for expansion, so we assume
849 // it's not possible.
850 }
851 else if ( expandedEntity.is_object() )
852 {
853 parseExpandedEntity( expandedEntity );
854 }
855 }
856 else
857 {
858 // No expansion for this parent feature.
859 // Maybe we should NULL out the attributes and return the parent feature? Right now we just
860 // skip it if there's no child features...
861 }
862 };
863
864 traverseExpansion( featureData, mEntityType, expansions, baseFeatureId, attributes );
865
866 if ( mFeatureLimit > 0 && mFeatureLimit <= mRetrievedBaseFeatureCount )
867 break;
868 }
869 else
870 {
871 feature.setAttributes( attributes );
872 processFeature( feature, baseFeatureId );
873 mRetrievedBaseFeatureCount++;
874 if ( mFeatureLimit > 0 && mFeatureLimit <= mRetrievedBaseFeatureCount )
875 break;
876 }
877 }
878 }
879 locker.unlock();
880
881 if ( rootContent.contains( "@iot.nextLink" ) && ( mFeatureLimit == 0 || mFeatureLimit > mCachedFeatures.size() ) )
882 {
883 nextPage = QString::fromStdString( rootContent["@iot.nextLink"].get<std::string>() );
884 }
885 else
886 {
887 onNoMoreFeaturesCallback();
888 }
889
890 // if target feature was added to cache, return it
891 if ( !continueFetchingCallback() )
892 {
893 return true;
894 }
895 }
896 }
897 catch ( const json::parse_error &ex )
898 {
899 locker.changeMode( QgsReadWriteLocker::Write );
900 mError = QObject::tr( "Error parsing response: %1" ).arg( ex.what() );
901 QgsDebugMsgLevel( QStringLiteral( "Error parsing response: %1" ).arg( ex.what() ), 2 );
902 return false;
903 }
904 }
905 }
906 return false;
907}
908
SensorThingsEntity
OGC SensorThings API entity types.
Definition qgis.h:5666
@ Sensor
A Sensor is an instrument that observes a property or phenomenon with the goal of producing an estima...
@ MultiDatastream
A MultiDatastream groups a collection of Observations and the Observations in a MultiDatastream have ...
@ ObservedProperty
An ObservedProperty specifies the phenomenon of an Observation.
@ Invalid
An invalid/unknown entity.
@ FeatureOfInterest
In the context of the Internet of Things, many Observations’ FeatureOfInterest can be the Location of...
@ Datastream
A Datastream groups a collection of Observations measuring the same ObservedProperty and produced by ...
@ Observation
An Observation is the act of measuring or otherwise determining the value of a property.
@ Location
A Location entity locates the Thing or the Things it associated with. A Thing’s Location entity is de...
@ Thing
A Thing is an object of the physical world (physical things) or the information world (virtual things...
@ HistoricalLocation
A Thing’s HistoricalLocation entity set provides the times of the current (i.e., last known) and prev...
RelationshipCardinality
Relationship cardinality.
Definition qgis.h:4203
@ ManyToMany
Many to many relationship.
@ ManyToOne
Many to one relationship.
@ OneToOne
One to one relationship.
@ OneToMany
One to many relationship.
@ MultiPointZ
MultiPointZ.
@ NoGeometry
No geometry.
@ PointZ
PointZ.
@ MultiLineStringZ
MultiLineStringZ.
@ MultiPolygonZ
MultiPolygonZ.
A vector of attributes.
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
void setAuthCfg(const QString &authCfg)
Sets the authentication config id which should be used during the request.
QString errorMessage() const
Returns the error message string, after a get(), post(), head() or put() request has been made.
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
@ NoError
No error was encountered.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
This class represents a coordinate reference system (CRS).
Class for storing the component parts of a RDBMS data source URI (e.g.
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:58
QgsFeatureId id
Definition qgsfeature.h:66
void setId(QgsFeatureId id)
Sets the feature id for this feature.
QgsGeometry geometry
Definition qgsfeature.h:69
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
Container of fields for a vector layer.
Definition qgsfields.h:46
int size() const
Returns number of items.
A geometry is the spatial representation of a feature.
static QgsGeometry fromRect(const QgsRectangle &rect)
Creates a new geometry from a QgsRectangle.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
This class implements simple http header management.
bool updateNetworkRequest(QNetworkRequest &request) const
Updates a request by adding all the HTTP headers.
static QgsGeometry geometryFromGeoJson(const json &geometry)
Parses a GeoJSON "geometry" value to a QgsGeometry object.
static QVariant jsonToVariant(const json &value)
Converts a JSON value to a QVariant, in case of parsing error an invalid QVariant is returned.
Encapsulates a network reply within a container which is inexpensive to copy and safe to pass between...
QByteArray content() const
Returns the reply content.
The QgsReadWriteLocker class is a convenience class that simplifies locking and unlocking QReadWriteL...
@ Write
Lock for write.
A rectangle specified with double values.
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.
Encapsulates information about how relationships in a SensorThings API service should be expanded.
Qgis::SensorThingsEntity childEntity() const
Returns the target child entity which should be expanded.
bool isValid() const
Returns true if the definition is valid.
static QString entityToSetString(Qgis::SensorThingsEntity type)
Converts a SensorThings entity set to a SensorThings entity set string.
static QString asQueryString(Qgis::SensorThingsEntity baseType, const QList< QgsSensorThingsExpansionDefinition > &expansions)
Returns a list of expansions as a valid SensorThings API query string, eg "$expand=Locations($orderby...
static QString combineFilters(const QStringList &filters)
Combines a set of SensorThings API filter operators.
static QString filterForWkbType(Qgis::SensorThingsEntity entityType, Qgis::WkbType wkbType)
Returns a filter string which restricts results to those matching the specified entityType and wkbTyp...
static Qgis::RelationshipCardinality relationshipCardinality(Qgis::SensorThingsEntity baseType, Qgis::SensorThingsEntity relatedType, bool &valid)
Returns the cardinality of the relationship between a base entity type and a related entity type.
static bool entityTypeHasGeometry(Qgis::SensorThingsEntity type)
Returns true if the specified entity type can have geometry attached.
static QgsFields fieldsForExpandedEntityType(Qgis::SensorThingsEntity baseType, const QList< Qgis::SensorThingsEntity > &expandedTypes)
Returns the fields which correspond to a specified entity baseType, expanded using the specified list...
static QString geometryFieldForEntityType(Qgis::SensorThingsEntity type)
Returns the geometry field for a specified entity type.
static QString filterForExtent(const QString &geometryField, const QgsRectangle &extent)
Returns a filter string which restricts results to those within the specified extent.
A spatial index for QgsFeature objects.
@ Uncounted
Feature count not yet computed.
@ UnknownCount
Provider returned an unknown feature count.
T qgsEnumKeyToValue(const QString &key, const T &defaultValue, bool tryValueAsKey=true, bool *returnOk=nullptr)
Returns the value corresponding to the given key of an enum.
Definition qgis.h:6354
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:6335
QSet< QgsFeatureId > QgsFeatureIds
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:41
#define QgsDebugError(str)
Definition qgslogger.h:40
#define QgsSetRequestInitiatorClass(request, _class)