QGIS API Documentation 3.36.0-Maidenhead (09951dc0acf)
Loading...
Searching...
No Matches
qgsarcgisrestquery.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsarcgisrestquery.cpp
3 ----------------------
4 begin : December 2020
5 copyright : (C) 2020 by 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
16#include "qgsarcgisrestquery.h"
17#include "qgsarcgisrestutils.h"
20#include "qgslogger.h"
21#include "qgsapplication.h"
22#include "qgsmessagelog.h"
23#include "qgsauthmanager.h"
24#include "qgsvariantutils.h"
25
26#include <QUrl>
27#include <QUrlQuery>
28#include <QImageReader>
29#include <QRegularExpression>
30#include <QJsonParseError>
31
32QVariantMap QgsArcGisRestQueryUtils::getServiceInfo( const QString &baseurl, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders, const QString &urlPrefix )
33{
34 // http://sampleserver5.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer?f=json
35 QUrl queryUrl( baseurl );
36 QUrlQuery query( queryUrl );
37 query.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) );
38 queryUrl.setQuery( query );
39 return queryServiceJSON( queryUrl, authcfg, errorTitle, errorText, requestHeaders, nullptr, urlPrefix );
40}
41
42QVariantMap QgsArcGisRestQueryUtils::getLayerInfo( const QString &layerurl, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders, const QString &urlPrefix )
43{
44 // http://sampleserver5.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/1?f=json
45 QUrl queryUrl( layerurl );
46 QUrlQuery query( queryUrl );
47 query.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) );
48 queryUrl.setQuery( query );
49 return queryServiceJSON( queryUrl, authcfg, errorTitle, errorText, requestHeaders, nullptr, urlPrefix );
50}
51
52QVariantMap QgsArcGisRestQueryUtils::getObjectIds( const QString &layerurl, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders, const QString &urlPrefix, const QgsRectangle &bbox, const QString &whereClause )
53{
54 // http://sampleserver5.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/1/query?where=1%3D1&returnIdsOnly=true&f=json
55 QUrl queryUrl( layerurl + "/query" );
56 QUrlQuery query( queryUrl );
57 query.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) );
58 query.addQueryItem( QStringLiteral( "where" ), whereClause.isEmpty() ? QStringLiteral( "1=1" ) : whereClause );
59 query.addQueryItem( QStringLiteral( "returnIdsOnly" ), QStringLiteral( "true" ) );
60 if ( !bbox.isNull() )
61 {
62 query.addQueryItem( QStringLiteral( "geometry" ), QStringLiteral( "%1,%2,%3,%4" )
63 .arg( bbox.xMinimum(), 0, 'f', -1 ).arg( bbox.yMinimum(), 0, 'f', -1 )
64 .arg( bbox.xMaximum(), 0, 'f', -1 ).arg( bbox.yMaximum(), 0, 'f', -1 ) );
65 query.addQueryItem( QStringLiteral( "geometryType" ), QStringLiteral( "esriGeometryEnvelope" ) );
66 query.addQueryItem( QStringLiteral( "spatialRel" ), QStringLiteral( "esriSpatialRelEnvelopeIntersects" ) );
67 }
68 queryUrl.setQuery( query );
69 return queryServiceJSON( queryUrl, authcfg, errorTitle, errorText, requestHeaders, nullptr, urlPrefix );
70}
71
72QgsRectangle QgsArcGisRestQueryUtils::getExtent( const QString &layerurl, const QString &whereClause, const QString &authcfg, const QgsHttpHeaders &requestHeaders, const QString &urlPrefix )
73{
74 // http://sampleserver5.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/1/query?where=1%3D1&returnExtentOnly=true&f=json
75 QUrl queryUrl( layerurl + "/query" );
76 QUrlQuery query( queryUrl );
77 query.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) );
78 query.addQueryItem( QStringLiteral( "where" ), whereClause );
79 query.addQueryItem( QStringLiteral( "returnExtentOnly" ), QStringLiteral( "true" ) );
80 queryUrl.setQuery( query );
81 QString errorTitle;
82 QString errorText;
83 const QVariantMap res = queryServiceJSON( queryUrl, authcfg, errorTitle, errorText, requestHeaders, nullptr, urlPrefix );
84 if ( res.isEmpty() )
85 {
86 QgsDebugError( QStringLiteral( "getExtent failed: %1 - %2" ).arg( errorTitle, errorText ) );
87 return QgsRectangle();
88 }
89
90 return QgsArcGisRestUtils::convertRectangle( res.value( QStringLiteral( "extent" ) ) );
91}
92
93QVariantMap QgsArcGisRestQueryUtils::getObjects( const QString &layerurl, const QString &authcfg, const QList<quint32> &objectIds, const QString &crs,
94 bool fetchGeometry, const QStringList &fetchAttributes,
95 bool fetchM, bool fetchZ,
96 const QgsRectangle &filterRect,
97 QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders, QgsFeedback *feedback, const QString &urlPrefix )
98{
99 QStringList ids;
100 for ( const int id : objectIds )
101 {
102 ids.append( QString::number( id ) );
103 }
104 QUrl queryUrl( layerurl + "/query" );
105 QUrlQuery query( queryUrl );
106 query.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) );
107 query.addQueryItem( QStringLiteral( "objectIds" ), ids.join( QLatin1Char( ',' ) ) );
108 const QString wkid = crs.indexOf( QLatin1Char( ':' ) ) >= 0 ? crs.split( ':' )[1] : QString();
109 query.addQueryItem( QStringLiteral( "inSR" ), wkid );
110 query.addQueryItem( QStringLiteral( "outSR" ), wkid );
111
112 query.addQueryItem( QStringLiteral( "returnGeometry" ), fetchGeometry ? QStringLiteral( "true" ) : QStringLiteral( "false" ) );
113
114 QString outFields;
115 if ( fetchAttributes.isEmpty() )
116 outFields = QStringLiteral( "*" );
117 else
118 outFields = fetchAttributes.join( ',' );
119 query.addQueryItem( QStringLiteral( "outFields" ), outFields );
120
121 query.addQueryItem( QStringLiteral( "returnM" ), fetchM ? QStringLiteral( "true" ) : QStringLiteral( "false" ) );
122 query.addQueryItem( QStringLiteral( "returnZ" ), fetchZ ? QStringLiteral( "true" ) : QStringLiteral( "false" ) );
123 if ( !filterRect.isNull() )
124 {
125 query.addQueryItem( QStringLiteral( "geometry" ), QStringLiteral( "%1,%2,%3,%4" )
126 .arg( filterRect.xMinimum(), 0, 'f', -1 ).arg( filterRect.yMinimum(), 0, 'f', -1 )
127 .arg( filterRect.xMaximum(), 0, 'f', -1 ).arg( filterRect.yMaximum(), 0, 'f', -1 ) );
128 query.addQueryItem( QStringLiteral( "geometryType" ), QStringLiteral( "esriGeometryEnvelope" ) );
129 query.addQueryItem( QStringLiteral( "spatialRel" ), QStringLiteral( "esriSpatialRelEnvelopeIntersects" ) );
130 }
131 queryUrl.setQuery( query );
132 return queryServiceJSON( queryUrl, authcfg, errorTitle, errorText, requestHeaders, feedback, urlPrefix );
133}
134
135QList<quint32> QgsArcGisRestQueryUtils::getObjectIdsByExtent( const QString &layerurl, const QgsRectangle &filterRect, QString &errorTitle, QString &errorText, const QString &authcfg, const QgsHttpHeaders &requestHeaders, QgsFeedback *feedback, const QString &whereClause, const QString &urlPrefix )
136{
137 QUrl queryUrl( layerurl + "/query" );
138 QUrlQuery query( queryUrl );
139 query.addQueryItem( QStringLiteral( "f" ), QStringLiteral( "json" ) );
140 query.addQueryItem( QStringLiteral( "where" ), whereClause.isEmpty() ? QStringLiteral( "1=1" ) : whereClause );
141 query.addQueryItem( QStringLiteral( "returnIdsOnly" ), QStringLiteral( "true" ) );
142 query.addQueryItem( QStringLiteral( "geometry" ), QStringLiteral( "%1,%2,%3,%4" )
143 .arg( filterRect.xMinimum(), 0, 'f', -1 ).arg( filterRect.yMinimum(), 0, 'f', -1 )
144 .arg( filterRect.xMaximum(), 0, 'f', -1 ).arg( filterRect.yMaximum(), 0, 'f', -1 ) );
145 query.addQueryItem( QStringLiteral( "geometryType" ), QStringLiteral( "esriGeometryEnvelope" ) );
146 query.addQueryItem( QStringLiteral( "spatialRel" ), QStringLiteral( "esriSpatialRelEnvelopeIntersects" ) );
147 queryUrl.setQuery( query );
148 const QVariantMap objectIdData = queryServiceJSON( queryUrl, authcfg, errorTitle, errorText, requestHeaders, feedback, urlPrefix );
149
150 if ( objectIdData.isEmpty() )
151 {
152 return QList<quint32>();
153 }
154
155 QList<quint32> ids;
156 const QVariantList objectIdsList = objectIdData[QStringLiteral( "objectIds" )].toList();
157 ids.reserve( objectIdsList.size() );
158 for ( const QVariant &objectId : objectIdsList )
159 {
160 ids << objectId.toInt();
161 }
162 return ids;
163}
164
165QByteArray QgsArcGisRestQueryUtils::queryService( const QUrl &u, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders, QgsFeedback *feedback, QString *contentType, const QString &urlPrefix )
166{
167 QUrl url = parseUrl( u );
168
169 if ( !urlPrefix.isEmpty() )
170 url = QUrl( urlPrefix + url.toString() );
171
172 QNetworkRequest request( url );
173 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsArcGisRestUtils" ) );
174 requestHeaders.updateNetworkRequest( request );
175
176 QgsBlockingNetworkRequest networkRequest;
177 networkRequest.setAuthCfg( authcfg );
178 const QgsBlockingNetworkRequest::ErrorCode error = networkRequest.get( request, false, feedback );
179
180 if ( feedback && feedback->isCanceled() )
181 return QByteArray();
182
183 // Handle network errors
185 {
186 QgsDebugError( QStringLiteral( "Network error: %1" ).arg( networkRequest.errorMessage() ) );
187 errorTitle = QStringLiteral( "Network error" );
188 errorText = networkRequest.errorMessage();
189
190 // try to get detailed error message from reply
191 const QString content = networkRequest.reply().content();
192 const thread_local QRegularExpression errorRx( QStringLiteral( "Error: <.*?>(.*?)<" ) );
193 const QRegularExpressionMatch match = errorRx.match( content );
194 if ( match.hasMatch() )
195 {
196 errorText = match.captured( 1 );
197 }
198
199 return QByteArray();
200 }
201
202 const QgsNetworkReplyContent content = networkRequest.reply();
203 if ( contentType )
204 *contentType = content.rawHeader( "Content-Type" );
205 return content.content();
206}
207
208QVariantMap QgsArcGisRestQueryUtils::queryServiceJSON( const QUrl &url, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders, QgsFeedback *feedback, const QString &urlPrefix )
209{
210 const QByteArray reply = queryService( url, authcfg, errorTitle, errorText, requestHeaders, feedback, nullptr, urlPrefix );
211 if ( !errorTitle.isEmpty() )
212 {
213 return QVariantMap();
214 }
215 if ( feedback && feedback->isCanceled() )
216 return QVariantMap();
217
218 // Parse data
219 QJsonParseError err;
220 const QJsonDocument doc = QJsonDocument::fromJson( reply, &err );
221 if ( doc.isNull() )
222 {
223 errorTitle = QStringLiteral( "Parsing error" );
224 errorText = err.errorString();
225 QgsDebugError( QStringLiteral( "Parsing error: %1" ).arg( err.errorString() ) );
226 return QVariantMap();
227 }
228 const QVariantMap res = doc.object().toVariantMap();
229 if ( res.contains( QStringLiteral( "error" ) ) )
230 {
231 const QVariantMap error = res.value( QStringLiteral( "error" ) ).toMap();
232 errorText = error.value( QStringLiteral( "message" ) ).toString();
233 errorTitle = QObject::tr( "Error %1" ).arg( error.value( QStringLiteral( "code" ) ).toString() );
234 return QVariantMap();
235 }
236 return res;
237}
238
239QUrl QgsArcGisRestQueryUtils::parseUrl( const QUrl &url, bool *isTestEndpoint )
240{
241 if ( isTestEndpoint )
242 *isTestEndpoint = false;
243
244 QUrl modifiedUrl( url );
245 if ( modifiedUrl.toString().contains( QLatin1String( "fake_qgis_http_endpoint" ) ) )
246 {
247 if ( isTestEndpoint )
248 *isTestEndpoint = true;
249
250 // Just for testing with local files instead of http:// resources
251 QString modifiedUrlString = modifiedUrl.toString();
252 // Qt5 does URL encoding from some reason (of the FILTER parameter for example)
253 modifiedUrlString = QUrl::fromPercentEncoding( modifiedUrlString.toUtf8() );
254 modifiedUrlString.replace( QLatin1String( "fake_qgis_http_endpoint/" ), QLatin1String( "fake_qgis_http_endpoint_" ) );
255 QgsDebugMsgLevel( QStringLiteral( "Get %1" ).arg( modifiedUrlString ), 2 );
256 modifiedUrlString = modifiedUrlString.mid( QStringLiteral( "http://" ).size() );
257 QString args = modifiedUrlString.indexOf( '?' ) >= 0 ? modifiedUrlString.mid( modifiedUrlString.indexOf( '?' ) ) : QString();
258 if ( modifiedUrlString.size() > 150 )
259 {
260 args = QCryptographicHash::hash( args.toUtf8(), QCryptographicHash::Md5 ).toHex();
261 }
262 else
263 {
264 args.replace( QLatin1String( "?" ), QLatin1String( "_" ) );
265 args.replace( QLatin1String( "&" ), QLatin1String( "_" ) );
266 args.replace( QLatin1String( "<" ), QLatin1String( "_" ) );
267 args.replace( QLatin1String( ">" ), QLatin1String( "_" ) );
268 args.replace( QLatin1String( "'" ), QLatin1String( "_" ) );
269 args.replace( QLatin1String( "\"" ), QLatin1String( "_" ) );
270 args.replace( QLatin1String( " " ), QLatin1String( "_" ) );
271 args.replace( QLatin1String( ":" ), QLatin1String( "_" ) );
272 args.replace( QLatin1String( "/" ), QLatin1String( "_" ) );
273 args.replace( QLatin1String( "\n" ), QLatin1String( "_" ) );
274 }
275#ifdef Q_OS_WIN
276 // Passing "urls" like "http://c:/path" to QUrl 'eats' the : after c,
277 // so we must restore it
278 if ( modifiedUrlString[1] == '/' )
279 {
280 modifiedUrlString = modifiedUrlString[0] + ":/" + modifiedUrlString.mid( 2 );
281 }
282#endif
283 modifiedUrlString = modifiedUrlString.mid( 0, modifiedUrlString.indexOf( '?' ) ) + args;
284 QgsDebugMsgLevel( QStringLiteral( "Get %1 (after laundering)" ).arg( modifiedUrlString ), 2 );
285 modifiedUrl = QUrl::fromLocalFile( modifiedUrlString );
286 if ( !QFile::exists( modifiedUrlString ) )
287 {
288 QgsDebugError( QStringLiteral( "Local test file %1 for URL %2 does not exist!!!" ).arg( modifiedUrlString, url.toString() ) );
289 }
290 }
291
292 return modifiedUrl;
293}
294
295void QgsArcGisRestQueryUtils::adjustBaseUrl( QString &baseUrl, const QString &name )
296{
297 const QStringList parts = name.split( '/' );
298 QString checkString;
299 for ( const QString &part : parts )
300 {
301 if ( !checkString.isEmpty() )
302 checkString += QString( '/' );
303
304 checkString += part;
305 if ( baseUrl.indexOf( QRegularExpression( checkString.replace( '/', QLatin1String( "\\/" ) ) + QStringLiteral( "\\/?$" ) ) ) > -1 )
306 {
307 baseUrl = baseUrl.left( baseUrl.length() - checkString.length() - 1 );
308 break;
309 }
310 }
311}
312
313void QgsArcGisRestQueryUtils::visitFolderItems( const std::function< void( const QString &, const QString & ) > &visitor, const QVariantMap &serviceData, const QString &baseUrl )
314{
315 QString base( baseUrl );
316 bool baseChecked = false;
317 if ( !base.endsWith( '/' ) )
318 base += QLatin1Char( '/' );
319
320 const QStringList folderList = serviceData.value( QStringLiteral( "folders" ) ).toStringList();
321 for ( const QString &folder : folderList )
322 {
323 if ( !baseChecked )
324 {
325 adjustBaseUrl( base, folder );
326 baseChecked = true;
327 }
328 visitor( folder, base + folder );
329 }
330}
331
332void QgsArcGisRestQueryUtils::visitServiceItems( const std::function<void ( const QString &, const QString &, Qgis::ArcGisRestServiceType )> &visitor, const QVariantMap &serviceData, const QString &baseUrl )
333{
334 QString base( baseUrl );
335 bool baseChecked = false;
336 if ( !base.endsWith( '/' ) )
337 base += QLatin1Char( '/' );
338
339 const QVariantList serviceList = serviceData.value( QStringLiteral( "services" ) ).toList();
340 for ( const QVariant &service : serviceList )
341 {
342 const QVariantMap serviceMap = service.toMap();
343 const QString serviceTypeString = serviceMap.value( QStringLiteral( "type" ) ).toString();
344 const Qgis::ArcGisRestServiceType serviceType = QgsArcGisRestUtils::serviceTypeFromString( serviceTypeString );
345
346 switch ( serviceType )
347 {
351 // supported
352 break;
353
358 // unsupported
359 continue;
360 }
361
362 const QString serviceName = serviceMap.value( QStringLiteral( "name" ) ).toString();
363 const QString displayName = serviceName.split( '/' ).last();
364 if ( !baseChecked )
365 {
366 adjustBaseUrl( base, serviceName );
367 baseChecked = true;
368 }
369
370 visitor( displayName, base + serviceName + '/' + serviceTypeString, serviceType );
371 }
372}
373
374void QgsArcGisRestQueryUtils::addLayerItems( const std::function<void ( const QString &, ServiceTypeFilter, Qgis::GeometryType, const QString &, const QString &, const QString &, const QString &, bool, const QString &, const QString & )> &visitor, const QVariantMap &serviceData, const QString &parentUrl, const QString &parentSupportedFormats, const ServiceTypeFilter filter )
375{
376 const QString authid = QgsArcGisRestUtils::convertSpatialReference( serviceData.value( QStringLiteral( "spatialReference" ) ).toMap() ).authid();
377
378 bool found = false;
379 const QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
380 const QStringList supportedImageFormatTypes = serviceData.value( QStringLiteral( "supportedImageFormatTypes" ) ).toString().isEmpty() ? parentSupportedFormats.split( ',' ) : serviceData.value( QStringLiteral( "supportedImageFormatTypes" ) ).toString().split( ',' );
381 QString format = supportedImageFormatTypes.value( 0 );
382 for ( const QString &encoding : supportedImageFormatTypes )
383 {
384 for ( const QByteArray &fmt : supportedFormats )
385 {
386 if ( encoding.startsWith( fmt, Qt::CaseInsensitive ) )
387 {
388 format = encoding;
389 found = true;
390 break;
391 }
392 }
393 if ( found )
394 break;
395 }
396 const QStringList capabilities = serviceData.value( QStringLiteral( "capabilities" ) ).toString().split( ',' );
397
398 // If the requested layer type is vector, do not show raster-only layers (i.e. non query-able layers)
399 const bool serviceMayHaveQueryCapability = capabilities.contains( QStringLiteral( "Query" ) ) ||
400 serviceData.value( QStringLiteral( "serviceDataType" ) ).toString().startsWith( QLatin1String( "esriImageService" ) );
401
402 const bool serviceMayRenderMaps = capabilities.contains( QStringLiteral( "Map" ) ) ||
403 serviceData.value( QStringLiteral( "serviceDataType" ) ).toString().startsWith( QLatin1String( "esriImageService" ) );
404
405 const QVariantList layerInfoList = serviceData.value( QStringLiteral( "layers" ) ).toList();
406 for ( const QVariant &layerInfo : layerInfoList )
407 {
408 const QVariantMap layerInfoMap = layerInfo.toMap();
409 const QString id = layerInfoMap.value( QStringLiteral( "id" ) ).toString();
410 const QString parentLayerId = layerInfoMap.value( QStringLiteral( "parentLayerId" ) ).toString();
411 const QString name = layerInfoMap.value( QStringLiteral( "name" ) ).toString();
412 const QString description = layerInfoMap.value( QStringLiteral( "description" ) ).toString();
413
414 // Yes, potentially we may visit twice, once as as a raster (if applicable), and once as a vector (if applicable)!
415 if ( serviceMayRenderMaps && ( filter == ServiceTypeFilter::Raster || filter == ServiceTypeFilter::AllTypes ) )
416 {
417 if ( !layerInfoMap.value( QStringLiteral( "subLayerIds" ) ).toList().empty() )
418 {
419 visitor( parentLayerId, ServiceTypeFilter::Raster, Qgis::GeometryType::Unknown, id, name, description, parentUrl + '/' + id, true, QString(), format );
420 }
421 else
422 {
423 visitor( parentLayerId, ServiceTypeFilter::Raster, Qgis::GeometryType::Unknown, id, name, description, parentUrl + '/' + id, false, authid, format );
424 }
425 }
426
427 if ( serviceMayHaveQueryCapability && ( filter == ServiceTypeFilter::Vector || filter == ServiceTypeFilter::AllTypes ) )
428 {
429 const QString geometryType = layerInfoMap.value( QStringLiteral( "geometryType" ) ).toString();
430#if 0
431 // we have a choice here -- if geometryType is unknown and the service reflects that it supports Map capabilities,
432 // then we can't be sure whether or not the individual sublayers support Query or Map requests only. So we either:
433 // 1. Send off additional requests for each individual layer's capabilities (too expensive)
434 // 2. Err on the side of only showing services we KNOW will work for layer -- but this has the side effect that layers
435 // which ARE available as feature services will only show as raster mapserver layers, which is VERY bad/restrictive
436 // 3. Err on the side of showing services we THINK may work, even though some of them may or may not work depending on the actual
437 // server configuration
438 // We opt for 3, because otherwise we're making it impossible for users to load valid vector layers into QGIS
439
440 if ( serviceMayRenderMaps )
441 {
442 if ( geometryType.isEmpty() )
443 continue;
444 }
445#endif
446
447 const Qgis::WkbType wkbType = QgsArcGisRestUtils::convertGeometryType( geometryType );
448
449
450 if ( !layerInfoMap.value( QStringLiteral( "subLayerIds" ) ).toList().empty() )
451 {
452 visitor( parentLayerId, ServiceTypeFilter::Vector, QgsWkbTypes::geometryType( wkbType ), id, name, description, parentUrl + '/' + id, true, QString(), format );
453 }
454 else
455 {
456 visitor( parentLayerId, ServiceTypeFilter::Vector, QgsWkbTypes::geometryType( wkbType ), id, name, description, parentUrl + '/' + id, false, authid, format );
457 }
458 }
459 }
460
461 const QVariantList tableInfoList = serviceData.value( QStringLiteral( "tables" ) ).toList();
462 for ( const QVariant &tableInfo : tableInfoList )
463 {
464 const QVariantMap tableInfoMap = tableInfo.toMap();
465 const QString id = tableInfoMap.value( QStringLiteral( "id" ) ).toString();
466 const QString parentLayerId = tableInfoMap.value( QStringLiteral( "parentLayerId" ) ).toString();
467 const QString name = tableInfoMap.value( QStringLiteral( "name" ) ).toString();
468 const QString description = tableInfoMap.value( QStringLiteral( "description" ) ).toString();
469
470 if ( serviceMayHaveQueryCapability && ( filter == ServiceTypeFilter::Vector || filter == ServiceTypeFilter::AllTypes ) )
471 {
472 if ( !tableInfoMap.value( QStringLiteral( "subLayerIds" ) ).toList().empty() )
473 {
474 visitor( parentLayerId, ServiceTypeFilter::Vector, Qgis::GeometryType::Null, id, name, description, parentUrl + '/' + id, true, QString(), format );
475 }
476 else
477 {
478 visitor( parentLayerId, ServiceTypeFilter::Vector, Qgis::GeometryType::Null, id, name, description, parentUrl + '/' + id, false, authid, format );
479 }
480 }
481 }
482
483 // Add root MapServer as raster layer when multiple layers are listed
484 if ( filter != ServiceTypeFilter::Vector && layerInfoList.count() > 1 && serviceData.contains( QStringLiteral( "supportedImageFormatTypes" ) ) )
485 {
486 const QString name = QStringLiteral( "(%1)" ).arg( QObject::tr( "All layers" ) );
487 const QString description = serviceData.value( QStringLiteral( "Comments" ) ).toString();
488 visitor( nullptr, ServiceTypeFilter::Raster, Qgis::GeometryType::Unknown, nullptr, name, description, parentUrl, false, authid, format );
489 }
490
491 // Add root ImageServer as layer
492 if ( serviceData.value( QStringLiteral( "serviceDataType" ) ).toString().startsWith( QLatin1String( "esriImageService" ) ) )
493 {
494 const QString name = serviceData.value( QStringLiteral( "name" ) ).toString();
495 const QString description = serviceData.value( QStringLiteral( "description" ) ).toString();
496 visitor( nullptr, ServiceTypeFilter::Raster, Qgis::GeometryType::Unknown, nullptr, name, description, parentUrl, false, authid, format );
497 }
498}
499
500
502
503//
504// QgsArcGisAsyncQuery
505//
506
507QgsArcGisAsyncQuery::QgsArcGisAsyncQuery( QObject *parent )
508 : QObject( parent )
509{
510}
511
512QgsArcGisAsyncQuery::~QgsArcGisAsyncQuery()
513{
514 if ( mReply )
515 mReply->deleteLater();
516}
517
518void QgsArcGisAsyncQuery::start( const QUrl &url, const QString &authCfg, QByteArray *result, bool allowCache, const QgsHttpHeaders &headers, const QString &urlPrefix )
519{
520 mResult = result;
521 QUrl mUrl = url;
522 if ( !urlPrefix.isEmpty() )
523 mUrl = QUrl( urlPrefix + url.toString() );
524 QNetworkRequest request( mUrl );
525
526 headers.updateNetworkRequest( request );
527
528 if ( !authCfg.isEmpty() && !QgsApplication::authManager()->updateNetworkRequest( request, authCfg ) )
529 {
530 const QString error = tr( "network request update failed for authentication config" );
531 emit failed( QStringLiteral( "Network" ), error );
532 return;
533 }
534
535 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsArcGisAsyncQuery" ) );
536 if ( allowCache )
537 {
538 request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache );
539 request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );
540 }
541 mReply = QgsNetworkAccessManager::instance()->get( request );
542 connect( mReply, &QNetworkReply::finished, this, &QgsArcGisAsyncQuery::handleReply );
543}
544
545void QgsArcGisAsyncQuery::handleReply()
546{
547 mReply->deleteLater();
548 // Handle network errors
549 if ( mReply->error() != QNetworkReply::NoError )
550 {
551 QgsDebugError( QStringLiteral( "Network error: %1" ).arg( mReply->errorString() ) );
552 emit failed( QStringLiteral( "Network error" ), mReply->errorString() );
553 return;
554 }
555
556 // Handle HTTP redirects
557 const QVariant redirect = mReply->attribute( QNetworkRequest::RedirectionTargetAttribute );
558 if ( !QgsVariantUtils::isNull( redirect ) )
559 {
560 QNetworkRequest request = mReply->request();
561 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsArcGisAsyncQuery" ) );
562 QgsDebugMsgLevel( "redirecting to " + redirect.toUrl().toString(), 2 );
563 request.setUrl( redirect.toUrl() );
564 mReply = QgsNetworkAccessManager::instance()->get( request );
565 connect( mReply, &QNetworkReply::finished, this, &QgsArcGisAsyncQuery::handleReply );
566 return;
567 }
568
569 *mResult = mReply->readAll();
570 mResult = nullptr;
571 emit finished();
572}
573
574//
575// QgsArcGisAsyncParallelQuery
576//
577
578QgsArcGisAsyncParallelQuery::QgsArcGisAsyncParallelQuery( const QString &authcfg, const QgsHttpHeaders &requestHeaders, QObject *parent )
579 : QObject( parent )
580 , mAuthCfg( authcfg )
581 , mRequestHeaders( requestHeaders )
582{
583}
584
585void QgsArcGisAsyncParallelQuery::start( const QVector<QUrl> &urls, QVector<QByteArray> *results, bool allowCache )
586{
587 Q_ASSERT( results->size() == urls.size() );
588 mResults = results;
589 mPendingRequests = mResults->size();
590 for ( int i = 0, n = urls.size(); i < n; ++i )
591 {
592 QNetworkRequest request( urls[i] );
593 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsArcGisAsyncParallelQuery" ) );
594 QgsSetRequestInitiatorId( request, QString::number( i ) );
595
596 mRequestHeaders.updateNetworkRequest( request );
597 if ( !mAuthCfg.isEmpty() && !QgsApplication::authManager()->updateNetworkRequest( request, mAuthCfg ) )
598 {
599 const QString error = tr( "network request update failed for authentication config" );
600 mErrors.append( error );
601 QgsMessageLog::logMessage( error, tr( "Network" ) );
602 continue;
603 }
604
605 request.setAttribute( QNetworkRequest::HttpPipeliningAllowedAttribute, true );
606 if ( allowCache )
607 {
608 request.setAttribute( QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache );
609 request.setAttribute( QNetworkRequest::CacheSaveControlAttribute, true );
610 request.setRawHeader( "Connection", "keep-alive" );
611 }
612 QNetworkReply *reply = QgsNetworkAccessManager::instance()->get( request );
613 reply->setProperty( "idx", i );
614 connect( reply, &QNetworkReply::finished, this, &QgsArcGisAsyncParallelQuery::handleReply );
615 }
616}
617
618void QgsArcGisAsyncParallelQuery::handleReply()
619{
620 QNetworkReply *reply = qobject_cast<QNetworkReply *>( QObject::sender() );
621 const QVariant redirect = reply->attribute( QNetworkRequest::RedirectionTargetAttribute );
622 const int idx = reply->property( "idx" ).toInt();
623 reply->deleteLater();
624 if ( reply->error() != QNetworkReply::NoError )
625 {
626 // Handle network errors
627 mErrors.append( reply->errorString() );
628 --mPendingRequests;
629 }
630 else if ( !QgsVariantUtils::isNull( redirect ) )
631 {
632 // Handle HTTP redirects
633 QNetworkRequest request = reply->request();
634 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsArcGisAsyncParallelQuery" ) );
635 QgsDebugMsgLevel( "redirecting to " + redirect.toUrl().toString(), 2 );
636 request.setUrl( redirect.toUrl() );
637 reply = QgsNetworkAccessManager::instance()->get( request );
638 reply->setProperty( "idx", idx );
639 connect( reply, &QNetworkReply::finished, this, &QgsArcGisAsyncParallelQuery::handleReply );
640 }
641 else
642 {
643 // All OK
644 ( *mResults )[idx] = reply->readAll();
645 --mPendingRequests;
646 }
647 if ( mPendingRequests == 0 )
648 {
649 emit finished( mErrors );
650 mResults = nullptr;
651 mErrors.clear();
652 }
653}
654
ArcGisRestServiceType
Available ArcGIS REST service types.
Definition qgis.h:3550
@ GeocodeServer
GeocodeServer.
@ Unknown
Other unknown/unsupported type.
@ FeatureServer
FeatureServer.
GeometryType
The geometry types are used to group Qgis::WkbType in a coarse way.
Definition qgis.h:255
@ Unknown
Unknown types.
@ Null
No geometry.
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:182
static QgsAuthManager * authManager()
Returns the application's authentication manager instance.
static void visitFolderItems(const std::function< void(const QString &folderName, const QString &url)> &visitor, const QVariantMap &serviceData, const QString &baseUrl)
Calls the specified visitor function on all folder items found within the given service data.
static QVariantMap queryServiceJSON(const QUrl &url, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders=QgsHttpHeaders(), QgsFeedback *feedback=nullptr, const QString &urlPrefix=QString())
Performs a blocking request to a URL and returns the retrieved JSON content.
static QVariantMap getObjects(const QString &layerurl, const QString &authcfg, const QList< quint32 > &objectIds, const QString &crs, bool fetchGeometry, const QStringList &fetchAttributes, bool fetchM, bool fetchZ, const QgsRectangle &filterRect, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders=QgsHttpHeaders(), QgsFeedback *feedback=nullptr, const QString &urlPrefix=QString())
Retrieves all matching objects from the specified layer URL.
static QgsRectangle getExtent(const QString &layerurl, const QString &whereClause, const QString &authcfg, const QgsHttpHeaders &requestHeaders=QgsHttpHeaders(), const QString &urlPrefix=QString())
Retrieves the extent for the features matching a whereClause.
static QVariantMap getServiceInfo(const QString &baseurl, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders=QgsHttpHeaders(), const QString &urlPrefix=QString())
Retrieves JSON service info for the specified base URL.
static QVariantMap getObjectIds(const QString &layerurl, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders=QgsHttpHeaders(), const QString &urlPrefix=QString(), const QgsRectangle &bbox=QgsRectangle(), const QString &whereClause=QString())
Retrieves all object IDs for the specified layer URL.
static QUrl parseUrl(const QUrl &url, bool *isTestEndpoint=nullptr)
Parses and processes a url.
static void addLayerItems(const std::function< void(const QString &parentLayerId, ServiceTypeFilter serviceType, Qgis::GeometryType geometryType, const QString &layerId, const QString &name, const QString &description, const QString &url, bool isParentLayer, const QString &authid, const QString &format)> &visitor, const QVariantMap &serviceData, const QString &parentUrl, const QString &parentSupportedFormats, const ServiceTypeFilter filter=ServiceTypeFilter::AllTypes)
Calls the specified visitor function on all layer items found within the given service data.
static QVariantMap getLayerInfo(const QString &layerurl, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders=QgsHttpHeaders(), const QString &urlPrefix=QString())
Retrieves JSON layer info for the specified layer URL.
static void visitServiceItems(const std::function< void(const QString &serviceName, const QString &url, Qgis::ArcGisRestServiceType serviceType)> &visitor, const QVariantMap &serviceData, const QString &baseUrl)
Calls the specified visitor function on all service items found within the given service data.
static QByteArray queryService(const QUrl &url, const QString &authcfg, QString &errorTitle, QString &errorText, const QgsHttpHeaders &requestHeaders=QgsHttpHeaders(), QgsFeedback *feedback=nullptr, QString *contentType=nullptr, const QString &urlPrefix=QString())
Performs a blocking request to a URL and returns the retrieved data.
static QList< quint32 > getObjectIdsByExtent(const QString &layerurl, const QgsRectangle &filterRect, QString &errorTitle, QString &errorText, const QString &authcfg, const QgsHttpHeaders &requestHeaders=QgsHttpHeaders(), QgsFeedback *feedback=nullptr, const QString &whereClause=QString(), const QString &urlPrefix=QString())
Gets a list of object IDs which fall within the specified extent.
static QgsCoordinateReferenceSystem convertSpatialReference(const QVariantMap &spatialReferenceMap)
Converts a spatial reference JSON definition to a QgsCoordinateReferenceSystem value.
static Qgis::WkbType convertGeometryType(const QString &type)
Converts an ESRI REST geometry type to a WKB type.
static Qgis::ArcGisRestServiceType serviceTypeFromString(const QString &type)
Converts a string value to a REST service type.
static QgsRectangle convertRectangle(const QVariant &value)
Converts a rectangle value to a QgsRectangle.
bool updateNetworkRequest(QNetworkRequest &request, const QString &authcfg, const QString &dataprovider=QString())
Provider call to update a QNetworkRequest with an authentication config.
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr)
Performs a "get" operation on the specified request.
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.
@ 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...
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
This class implements simple http header management.
bool updateNetworkRequest(QNetworkRequest &request) const
Updates a request by adding all the HTTP headers.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
static QgsNetworkAccessManager * instance(Qt::ConnectionType connectionType=Qt::BlockingQueuedConnection)
Returns a pointer to the active QgsNetworkAccessManager for the current thread.
Encapsulates a network reply within a container which is inexpensive to copy and safe to pass between...
QByteArray content() const
Returns the reply content.
QByteArray rawHeader(const QByteArray &headerName) const
Returns the content of the header with the specified headerName, or an empty QByteArray if the specif...
A rectangle specified with double values.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double xMaximum() const
Returns the x maximum value (right side of rectangle).
bool isNull() const
Test if the rectangle is null (holding no spatial information).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
static bool isNull(const QVariant &variant, bool silenceNullWarnings=false)
Returns true if the specified variant should be considered a NULL value.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:39
#define QgsDebugError(str)
Definition qgslogger.h:38
#define QgsSetRequestInitiatorClass(request, _class)
#define QgsSetRequestInitiatorId(request, str)
const QgsCoordinateReferenceSystem & crs