-
Notifications
You must be signed in to change notification settings - Fork 3
/
qgswcsclient2dialog.py
1380 lines (1090 loc) · 53.1 KB
/
qgswcsclient2dialog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
/***************************************************************************
QgsWcsClient2
A QGIS plugin
A OGC WCS 2.0/EO-WCS Client
-------------------
begin : 2014-06-26; 2017-04-10
copyright : (C) 2014 by Christian Schiller / EOX IT Services GmbH, Vienna, Austria
email : christian dot schiller at eox dot at
***************************************************************************/
/*********************************************************************************/
* The MIT License (MIT) *
* *
* Copyright (c) 2014 EOX IT Services GmbH *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE *
* SOFTWARE. *
* *
*********************************************************************************/
The main QgsWcsClient2 Plugin Application -- an OGC WCS 2.0/EO-WCS Client
"""
import os, sys, pickle
from lxml import etree
from glob import glob
from itertools import izip_longest
from qgis.core import *
from qgis.gui import *
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import QProgressDialog, QDialog, QMessageBox, QFileDialog, QApplication, QCursor
from PyQt4.QtNetwork import QNetworkRequest, QNetworkAccessManager
from PyQt4 import QtXml
from ui_qgswcsclient2 import Ui_QgsWcsClient2
from qgsnewhttpconnectionbasedialog import qgsnewhttpconnectionbase
from display_txtdialog import display_txt
from downloader import download_url
from EOxWCSClient.wcs_client import wcsClient
#global setttings and saved server list
global config
import config
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
#---------------
# running clock icon
def mouse_busy(function):
"""
set the mouse icon to show clock
"""
#def new_function(self):
def new_function(*args, **kwargs):
"""
set the mouse icon to show clock
"""
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
QApplication.processEvents()
try:
#function(self)
return function(*args, **kwargs)
except Exception as e:
raise e
print("Error {}".format(e.args[0]))
finally:
QApplication.restoreOverrideCursor()
QApplication.restoreOverrideCursor()
return new_function
#---------------
# provide a pop-up warning message
def warning_msg(msg):
"""
present a message in a popup dialog-box
"""
msgBox = QtGui.QMessageBox()
msgBox.setText(msg)
msgBox.addButton(QtGui.QPushButton('OK'), QtGui.QMessageBox.YesRole)
msgBox.exec_()
#---------------
## ====== Main Class ======
class QgsWcsClient2Dialog(QtGui.QDialog, Ui_QgsWcsClient2):
"""
main QGis-WCS plugin dialog
"""
def __init__(self, iface):
global config
#print "I'm in "+sys._getframe().f_code.co_name
QtGui.QDialog.__init__(self)
self.setupUi(self)
self.iface = iface
# if server information is already available, activate the Edit-Button, and the update the
# selectionBar
if len(config.srv_list['servers']) > 0:
self.btnEdit_Serv.setEnabled(True)
self.btnDelete_Serv.setEnabled(True)
self.updateServerListing()
# creating progress dialog for download
self.progress_dialog = QProgressDialog(self)
self.progress_dialog.setAutoClose(True) # False # was set originally
title = self.tr("WSC-2.0/EO-WCS Downloader")
self.progress_dialog.setWindowTitle(title)
# instantiate the wcsClient
self.myWCS = wcsClient()
self.treeWidget_GCa.itemClicked.connect(self.on_GCa_clicked)
self.treeWidget_DC.itemClicked.connect(self.on_DC_clicked)
self.treeWidget_DCS.itemClicked.connect(self.on_DCS_clicked)
self.treeWidget_GCov.itemClicked.connect(self.on_GCov_clicked)
#---------------
# remove all 'keys' which are set to 'None' from the request-parameter dictionary
def clear_req_params(self, req_params):
#print "I'm in "+sys._getframe().f_code.co_name
for k, v in req_params.items():
if v is None:
req_params.pop(k)
return req_params
## ====== Beginning Server Tab-section ======
#---------------
# add a new server to the list
def newServer(self):
global config
#print 'btnNew: I am adding a New ServerName/URL'
flags = Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint
dlgNew = qgsnewhttpconnectionbase(self, flags, toEdit=False, choice='')
dlgNew.show()
self.btnConnectServer_Serv.setFocus(True)
#---------------
# read the selected server/url params
def get_serv_url(self):
global serv
sel_serv = self.cmbConnections_Serv.currentText()
idx = serv.index(sel_serv)
sel_url = config.srv_list['servers'][idx][1]
return sel_serv, sel_url
#---------------
# modify a server entry
def editServer(self):
global config
#print "btnEdit: here we are editing... "
flags = Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint
idx = self.cmbConnections_Serv.currentIndex()
select_serv = config.srv_list['servers'][idx]
print "Editing: ", idx, " -- ", select_serv, " -- Check: ", serv[idx]
dlgEdit = qgsnewhttpconnectionbase(self, flags, toEdit=True, choice=idx)
dlgEdit.txt_NewSrvName.setText(select_serv[0])
dlgEdit.txt_NewSrvUrl.setText(select_serv[1])
dlgEdit.show()
self.btnConnectServer_Serv.setFocus(True)
#---------------
# delete a server entry
def deleteServer(self):
global config
#print "btnDelete: here we are deleting...."
idx = self.cmbConnections_Serv.currentIndex()
print "Deleting: ", serv[idx]," -- ",config.srv_list['servers'][idx]
config.srv_list['servers'].pop(idx)
self.write_srv_list()
self.updateServerListing()
self.btnConnectServer_Serv.setFocus(True)
#---------------
#sort the server list alphabetically
def sortServerListing(self):
#print "btnSort_Serv: here we are sorting...."
config.srv_list = config.read_srv_list()
config.srv_list['servers'].sort()
self.write_srv_list()
self.updateServerListing()
self.btnConnectServer_Serv.setFocus(True)
#---------------
# update the server-listing shown in the selectionBar
def updateServerListing(self):
global serv
global config
#print "btnUpdateServerListing: here we are updating the ServerList...."
serv = []
config.srv_list = config.read_srv_list()
idx = self.cmbConnections_Serv.currentIndex()
for ii in range(len(config.srv_list['servers'])):
serv.append(config.srv_list['servers'][ii][0][:])
self.cmbConnections_Serv.clear()
self.cmbConnections_Serv.addItems(serv)
#---------------
# write the sever names/urls to a file
@mouse_busy
def write_srv_list(self):
#print "btnwriteServerListing: here we are writing the ServerList...."
plugin_dir = os.path.dirname(os.path.realpath(__file__))
outsrvlst = os.path.join(plugin_dir, 'config_srvlist.pkl')
fo = open(outsrvlst, 'wb')
pickle.dump(config.srv_list, fo, 0)
fo.close()
#---------------
# import WCS Names & Urls from the antive Qgis-settings location
@mouse_busy
def importQgis_ServList(self):
global config
from PyQt4.QtCore import QSettings
#print "btnImport_QgsWcsUrls: here we are importing the Qgis-WCS ServerList...."
qgs_settings = QSettings(QSettings.NativeFormat, QSettings.UserScope, 'QGIS', 'QGIS2')
qgis_wcs_urls = []
for elem in qgs_settings.allKeys():
if elem.startswith('Qgis/connections-wcs') and elem.endswith('url'):
print 'Importing WCS-Url: ', str.rsplit(str(elem),'/',2)[-2], qgs_settings.value(elem)
qgis_wcs_urls.append([str.rsplit(str(elem),'/',2)[-2], str(qgs_settings.value(elem))])
# append qgis_wcs_urls to the QgsWcsClient2 plugin settings
config.srv_list = config.read_srv_list()
for elem in qgis_wcs_urls:
config.srv_list['servers'].append((unicode(elem[0]), elem[1]))
# write the imported settings to the QgsWcsClient2 plugin settings file
self.write_srv_list()
self.updateServerListing()
self.btnConnectServer_Serv.setFocus(True)
#---------------
# get the path where the downloaded datasets shall be stored
@mouse_busy
def get_outputLoc(self):
global req_outputLoc
start_dir = os.getenv("HOME")
req_outputLoc = QFileDialog.getExistingDirectory(self, "Select Output Path", start_dir)
if len(req_outputLoc) > 0:
if not req_outputLoc.endswith(os.sep):
req_outputLoc = req_outputLoc+os.sep
self.lineEdit_Serv_OutputLoc.setText(str(req_outputLoc))
#---------------
# check if the url exist and if we get a respond to a simple OWS request
@mouse_busy
def connectServer(self):
global config
global serv
FGCa_sect = False
selected_serv, selected_url = self.get_serv_url()
print 'You choose: ', selected_serv, "URL:", selected_url
if self.tab_GCa.isEnabled():
self.tab_GCa.setEnabled(False)
if self.tab_DC.isEnabled():
self.tab_DC.setEnabled(False)
if self.tab_DCS.isEnabled():
self.tab_DCS.setEnabled(False)
if self.tab_GCov.isEnabled():
self.tab_GCov.setEnabled(False)
if self.checkBox_GCaFull.isChecked():
self.checkBox_GCaFull.setChecked(False)
if self.checkBox_DCSFull.isChecked():
self.checkBox_DCSFull.setChecked(False)
url_base = selected_url
# request only §ions=ServiceMetadata -- this makes if faster (especially on large sites),
# but some Servers don't provide/accept it, so there is a fallback implemented
url_ext1 = "service=WCS&request=GetCapabilities§ions=ServiceMetadata,ServiceIdentification"
url_ext2 = "service=WCS&request=GetCapabilities"
myUrl = url_base + url_ext1
myUrl2 = url_base + url_ext2
msg = "Your choice: "+selected_serv.encode()+"\n"
msg = msg+"URL: "+selected_url.encode()+"\n"
srv_valid = QUrl(myUrl).isValid()
if srv_valid is True:
msg = msg+"Server address is valid \n"
msg = msg+"Now testing the connection and response.....\n "
msg = msg+" this may take some time (depending on the server and the volume of its offering)\n"
self.textBrowser_Serv.setText(msg)
self.progress_dialog.done(QDialog.Accepted)
self.progress_dialog.cancel()
self.progress_dialog.show()
#after changing a server connection --> reset all fields (at least the combo-boxes)
self.reset_comboboxes()
req_qgsmng = QNetworkAccessManager(self)
# start the download
response = download_url(req_qgsmng, myUrl, None, self.progress_dialog)
#print 'myUrl: ', response[0:1] , type(response[1])
#print 'Payload: ',response[2]
# check if response is valid and useful, else try the fallback or issue an error
if response[0] is not True:
response = download_url(req_qgsmng, myUrl2, None, self.progress_dialog)
#print 'myUrl2',response[0:1]
if response[0] is not True:
msg = msg+"Response: An Error occurred: --> "+str(response[1])+"\n HTTP-Code received: "+str(response[0])+"\n"
self.progress_dialog.close()
else:
msg = self.eval_response(response, msg)
elif response[0] is True and ((type(response[2]) is unicode or type(response[2]) is str) and response[2].startswith('Redirection-URL:')):
msg = msg+"\n\t**** ATTENTION! ****\nThe server you selected:\n\t"+selected_serv +"\nresponded with a:\n\t"+response[2]+"\n"
msg = msg+"Please VERIFY(!) URL and change your Server-List accordingly."
self.progress_dialog.close()
elif response[0] is True and ((response[2] is not None or len(response[2]) == 0)):
FGCa_sect = True
msg = self.eval_response(response, msg)
else:
msg = msg+"Response: An Error occurred: --> "+str(response[1])+"\n HTTP-Code received: "+str(response[0])+"\n"
self.progress_dialog.close()
self.textBrowser_Serv.setText(msg)
if FGCa_sect is True:
self.checkBox_GCaDaSerSum.setChecked(True)
self.checkBox_GCaCovSum.setChecked(True)
else:
self.checkBox_GCaDaSerSum.setChecked(False)
self.checkBox_GCaCovSum.setChecked(False)
#---------------
# reset content of combo-boxes and tree-widgets
def reset_comboboxes(self):
global config
#print 'Config.Interpol: ', config.default_interpol
self.treeWidget_GCa.clear()
self.treeWidget_DC.clear()
self.treeWidget_DCS.clear()
self.treeWidget_GCov.clear()
self.comboBox_GCOvOutFormat.clear()
self.comboBox_GCovOutCRS.clear()
self.comboBox_GCovInterpol.clear()
for elem in range(0, 3):
self.comboBox_GCovInterpol.addItem(_fromUtf8(""))
self.comboBox_GCovInterpol.setItemText(elem, _translate("QgsWcsClient2", config.default_interpol[elem], None))
#---------------
# evaluate a valid response and enable settings in the tabs
def eval_response(self, response, msg):
msg = msg+"Response: Server OK\n"
ret_msg = self.parse_first_xml(response[2])
if ret_msg is not None:
msg = msg + "\n"+ret_msg
self.treeWidget_GCa.clear()
self.treeWidget_DC.clear()
self.treeWidget_DCS.clear()
self.treeWidget_GCov.clear()
self.progress_dialog.close()
# all tabs (except Server/Help/About) are disabled until server connection is OK
# once server connection is verifyed, activate all other tabs
if not self.tab_GCa.isEnabled():
self.tab_GCa.setEnabled(True)
if not self.tab_DC.isEnabled():
self.tab_DC.setEnabled(True)
if not self.tab_DCS.isEnabled():
self.tab_DCS.setEnabled(True)
if not self.tab_GCov.isEnabled():
self.tab_GCov.setEnabled(True)
if not self.checkBox_GCa_ActiveDate.isEnabled():
self.checkBox_GCa_ActiveDate.setEnabled(True)
if not self.checkBox_DCS_ActiveDate.isEnabled():
self.checkBox_DCS_ActiveDate.setEnabled(True)
if not self.checkBox_DCS_ActiveCount.isEnabled():
self.checkBox_DCS_ActiveCount.setEnabled(True)
if self.dateTimeEdit_DCSBegin.isEnabled():
self.dateTimeEdit_DCSBegin.setEnabled(False)
if self.dateTimeEdit_DCSEnd.isEnabled():
self.dateTimeEdit_DCSEnd.setEnabled(False)
if not self.spinBox_DCSCount.isEnabled():
self.spinBox_DCSCount.setEnabled(True)
if self.radioButton_GCovSubCRS.isChecked():
self.radioButton_GCovSubCRS.setChecked(False)
if self.radioButton_GCovSubPixel.isChecked():
self.radioButton_GCovSubPixel.setChecked(False)
if not self.radioButton_GCovSubOrig.isChecked():
self.radioButton_GCovSubOrig.setChecked(True)
if self.radioButton_GCovXSize.isChecked():
self.radioButton_GCovXSize.setChecked(False)
if self.radioButton_GCovXRes.isChecked():
self.radioButton_GCovXRes.setChecked(False)
if self.radioButton_GCovYSize.isChecked():
self.radioButton_GCovYSize.setChecked(False)
if self.radioButton_GCovYRes.isChecked():
self.radioButton_GCovYRes.setChecked(False)
return msg
#---------------
# get a mapping of the namespaces
def get_namespace(self, result_xml):
my_nsp=result_xml.getroot().nsmap
return my_nsp
#---------------
# get a listing of interpoation methods offered
def getlist_interpol(self, result_xml, my_nsp):
interpol=[]
for k,v in my_nsp.iteritems():
if 'int' in k:
prefix = './/' +k+ ':'
#print prefix
for elem in (result_xml.findall(prefix+'InterpolationSupported', my_nsp)):
interpol.append(os.path.basename(elem.text))
if len(interpol) == 0:
for elem in (result_xml.findall(prefix+'interpolationSupported', my_nsp)):
interpol.append(elem.text.rsplit('/',1)[1])
if len(interpol) == 0:
interpol = config.default_interpol
return interpol
#---------------
# get a listing of CRSs offered
def getlist_crs(self, result_xml, my_nsp):
crs=[]
for k,v in my_nsp.iteritems():
if 'crs' in k:
prefix = './/' +k+ ':'
#print prefix
for elem in (result_xml.findall(prefix+'crsSupported', my_nsp)):
#print elem.text
crs.append(os.path.basename(elem.text))
if 'wcscrs' in k:
prefix = './/' +k+ ':'
#print prefix
for elem in (result_xml.findall(prefix+'crsSupported', my_nsp)):
#print elem.text
crs.append(os.path.basename(elem.text))
return crs
#---------------
# get a listing of fromats offered
def getlist_formats(self, result_xml, my_nsp):
formats=[]
for k,v in my_nsp.iteritems():
if 'wcs' in k:
prefix = './/' +k+ ':'
#print prefix
for elem in (result_xml.findall(prefix+'formatSupported', my_nsp)):
#print elem.text
formats.append(elem.text)
return formats
#---------------
# parse the response issued during "Server Connect" and set some parameters
def parse_first_xml(self, in_xml):
global offered_version
global config
global use_wcs_GCo_call
use_wcs_GCo_call = 0
join_xml = ''.join(in_xml)
#fix by hkristen
tree1 = etree.XML(join_xml)
offered_version = tree1.attrib['version']
print 'WCS-Version: ', offered_version
# since this is for plugin WCS >2.0 and EO-WCS, we skip the WCS 1.x and issue an error
if offered_version.startswith('1'):
msg = "WARNING: \nThe selected Site doesn't support WCS 2.0 or above. \n\n"
msg = msg+"The server responded with supported version: "+ offered_version +"\n"
msg = msg+" (Hint: try to use the QGis internal WCS for this site)"
self.progress_dialog.close()
warning_msg(msg)
return msg
# check which additional profiles are offered
# especially for the "WCS_service-extension_crs/1.0/conf/crs" profile, since this one changes the request syntax
target_profile = "WCS_service-extension_crs/1.0/conf/crs"
profiles = tree1.xpath("ows:ServiceIdentification/ows:Profile/text()", namespaces=tree1.nsmap)
res_prof = [x for x in profiles if (target_profile in x)]
if res_prof.__len__() > 0:
# set global parameter for WCS-GetCoverage call selection
use_wcs_GCo_call = 1
my_nsp = self.get_namespace(tree1.getroottree())
#print 'MY_NSP: ',my_nsp
interpol = self.getlist_interpol(tree1, my_nsp)
outcrs = self.getlist_crs(tree1, my_nsp)
outformat = self.getlist_formats(tree1, my_nsp)
oformat_num = len(outformat)
ocrs_num = len(outcrs)
interpol_num = len(interpol)
support_outcrs = []
support_interpol = []
#print 'INT-1: ', interpol
#print 'INT-1a: ', outcrs
# set the output-crs, output-format, and interpolation possibilities
# in the corresponding combo-boxes
for elem in outcrs:
support_outcrs.append(os.path.basename(elem))
for elem in interpol:
support_interpol.append(os.path.basename(elem))
#print 'supported_format: ',oformat_num, type(outformat), outformat
#print 'supported_outcrs: ',ocrs_num, type(outcrs), outcrs
#print 'supported_interpol: ', interpol_num, type(interpol), interpol
for elem in range(0, oformat_num):
self.comboBox_GCOvOutFormat.addItem(_fromUtf8(""))
self.comboBox_GCOvOutFormat.setItemText(elem, _translate("QgsWcsClient2", outformat[elem], None))
for elem in range(0, ocrs_num):
self.comboBox_GCovOutCRS.addItem(_fromUtf8(""))
self.comboBox_GCovOutCRS.setItemText(elem, _translate("QgsWcsClient2", support_outcrs[elem], None))
self.comboBox_GCovInterpol.clear()
for elem in range(0, interpol_num):
self.comboBox_GCovInterpol.addItem(_fromUtf8(""))
self.comboBox_GCovInterpol.setItemText(elem, _translate("QgsWcsClient2", support_interpol[elem], None))
## ====== End of Server Tab-section ======
#---------------
@mouse_busy
def exeGetCapabilities(self):
"""
read-out params from the GetCapabilities Tab, execute the request and show results
"""
global cov_ids
global dss_ids
global req_outputLoc
self.treeWidget_GCa.clear()
req_sections = []
req_full_GCa = False
req_updateDate = ''
selected_serv, selected_url = self.get_serv_url()
if self.checkBox_GCaAll.isChecked():
req_sections.append("All")
if self.checkBox_GCaDaSerSum.isChecked():
req_sections.append("DatasetSeriesSummary")
if self.checkBox_GCaCovSum.isChecked():
req_sections.append("CoverageSummary")
if self.checkBox_GCaServId.isChecked():
req_sections.append("ServiceIdentification")
if self.checkBox_GCaServProv.isChecked():
req_sections.append("ServiceProvider")
if self.checkBox_GCaServMeta.isChecked():
req_sections.append("ServiceMetadata")
if self.checkBox_GCaOpMeta.isChecked():
req_sections.append("OperationsMetadata")
if self.checkBox_GCaCont.isChecked():
req_sections.append("Content")
if self.checkBox_GCaLang.isChecked():
req_sections.append("Languages")
if self.checkBox_GCaFull.isChecked():
req_full_GCa = True
req_outputLoc = self.lineEdit_Serv_OutputLoc.text()
if self.dateEdit_GCaDocUpdate.isEnabled():
req_updateDate = self.dateEdit_GCaDocUpdate.text()
else:
req_updateDate = None
req_sections = ','.join(req_sections)
if len(req_sections) == 0:
req_sections = None
# basic request setting
req_params = {'request': 'GetCapabilities',
'server_url': selected_url,
'updateSequence': req_updateDate,
'sections' : req_sections}
req_params = self.clear_req_params(req_params)
#print 'GCa: ',req_params
# issue the WCS request
GCa_result = self.myWCS.GetCapabilities(req_params)
#print "GCa_result: ", type(GCa_result), GCa_result[0], GCa_result[1], GCa_result
if type(GCa_result) is list and GCa_result[0] == 'ERROR':
self.textBrowser_Serv.setText(GCa_result[0]+'\n'+GCa_result[1]+'\n HINT: Select only the "All" setting or select none')
warning_msg(GCa_result[0]+'\n'+GCa_result[1]+'\n HINT: Select only the All setting or select none')
return
#print 'RESULT: ',GCa_result
if req_full_GCa is False:
# parse the results and place them in the crespective widgets
try:
cov_ids, dss_ids, dss_begin, dss_end, cov_lcorn, cov_ucorn, dss_lcorn, dss_ucorn = self.parse_GCa_xml(GCa_result)
except TypeError:
self.textBrowser_Serv.setText("No usable results received"+'\n HINT: Select only the "All" setting or select none')
warning_msg("No usable results received"+'\n HINT: Select only the All setting or select none')
return
# TODO -- add the coverage extension (BoundingBox) information to the respective Tabs
if len(cov_ids) > 0:
for ids, uc, lc, in izip_longest(cov_ids, cov_ucorn, cov_lcorn, fillvalue = ""):
inlist = (ids, "", "", uc, lc, "C")
item = QtGui.QTreeWidgetItem(self.treeWidget_GCa, inlist)
if len(dss_ids) > 0:
for a, b, c, d, e in izip_longest(dss_ids, dss_begin, dss_end, dss_ucorn, dss_lcorn, fillvalue = ""):
inlist = (a, b, c, d, e, "S")
item = QtGui.QTreeWidgetItem(self.treeWidget_GCa, inlist)
self.treeWidget_GCa.resizeColumnToContents(0)
else:
myDisplay_txt = display_txt(self)
myDisplay_txt.textBrowser_Disp.setText(GCa_result)
myDisplay_txt.show()
if self.checkBox_GCaFull.isChecked():
self.checkBox_GCaFull.setChecked(False)
QApplication.changeOverrideCursor(Qt.ArrowCursor)
#---------------
# GetCapabilities button
def on_GCa_clicked(self):
global cov_ids
global dss_ids
sel_GCa_items = self.treeWidget_GCa.selectedItems()
self.treeWidget_DC.clear()
self.treeWidget_DCS.clear()
self.treeWidget_GCov.clear()
# place selected items also in the DescribeCoverage, DescribeEOCoverageSet, GetCoverage Tab widgets
for elem in sel_GCa_items:
# covID BeginTime EndTime UpperCorner LowerCorner [C]/[S]
print 'Selected Item: ', elem.data(0, 0), elem.data(1, 0), elem.data(2, 0), elem.data(3, 0), elem.data(4, 0), elem.data(5, 0)
if elem.data(0, 0) in cov_ids:
item = QtGui.QTreeWidgetItem(self.treeWidget_DC, (elem.data(0, 0), ))
item2 = QtGui.QTreeWidgetItem(self.treeWidget_GCov, (elem.data(0, 0), ))
elif elem.data(0, 0) in dss_ids:
item1 = QtGui.QTreeWidgetItem(self.treeWidget_DCS, (elem.data(0, 0), elem.data(1, 0), elem.data(2, 0), elem.data(3, 0), elem.data(4, 0)))
self.treeWidget_DC.resizeColumnToContents(0)
self.treeWidget_DCS.resizeColumnToContents(0)
self.treeWidget_GCov.resizeColumnToContents(0)
#---------------
# updateDate field
def updateDateChanged(self):
if self.dateEdit_GCaDocUpdate.isEnabled():
self.dateEdit_GCaDocUpdate.setEnabled(False)
else:
self.dateEdit_GCaDocUpdate.setEnabled(True)
#---------------
# parse GetCapabilities XML-response
def parse_GCa_xml(self, GCa_result):
join_xml = ''.join(GCa_result)
tree = etree.fromstring(join_xml).getroottree()
nsmap=tree.getroot().nsmap
if len(tree.xpath("wcs:Contents", namespaces=nsmap)) == 0:
return
# Coverages ID
try:
coverage_ids = tree.xpath("wcs:Contents/wcs:CoverageSummary/wcs:CoverageId/text()", namespaces=nsmap)
except etree.XPathEvalError:
coverage_ids = []
# Coverages ID - Corner Coordinates
try:
cov_lower_corner = tree.xpath("wcs:Contents/wcs:CoverageSummary/ows:WGS84BoundingBox/ows:LowerCorner/text()", namespaces=nsmap)
except etree.XPathEvalError:
cov_lower_corner = []
try:
cov_upper_corner = tree.xpath("wcs:Contents/wcs:CoverageSummary/ows:WGS84BoundingBox/ows:UpperCorner/text()", namespaces=nsmap)
except etree.XPathEvalError:
cov_upper_corner = []
# DatasetSeries ID
try:
datasetseries_ids = tree.xpath("wcs:Contents/wcs:Extension/wcseo:DatasetSeriesSummary/wcseo:DatasetSeriesId/text()", namespaces=nsmap)
except etree.XPathEvalError:
datasetseries_ids = []
# DatasetSeries - Time Period
try:
datasetseries_timeBegin = tree.xpath("wcs:Contents/wcs:Extension/wcseo:DatasetSeriesSummary/gml:TimePeriod/gml:beginPosition/text()", namespaces=nsmap)
except etree.XPathEvalError:
datasetseries_ids = []
datasetseries_timeBegin = []
try:
datasetseries_timeEnd = tree.xpath("wcs:Contents/wcs:Extension/wcseo:DatasetSeriesSummary/gml:TimePeriod/gml:endPosition/text()", namespaces=nsmap)
except etree.XPathEvalError:
datasetseries_timeEnd = []
# DatasetSeries - Corner Coordinates
try:
datasetseries_lower_corner = tree.xpath("wcs:Contents/wcs:Extension/wcseo:DatasetSeriesSummary/ows:WGS84BoundingBox/ows:LowerCorner/text()", namespaces=nsmap)
except etree.XPathEvalError:
datasetseries_lower_corner = []
try:
datasetseries_upper_corner = tree.xpath("wcs:Contents/wcs:Extension/wcseo:DatasetSeriesSummary/ows:WGS84BoundingBox/ows:UpperCorner/text()", namespaces=nsmap)
except etree.XPathEvalError:
datasetseries_upper_corner = []
return coverage_ids, datasetseries_ids, datasetseries_timeBegin, datasetseries_timeEnd, cov_lower_corner, cov_upper_corner, datasetseries_lower_corner, datasetseries_upper_corner
## ====== End of GetCapabilities section ======
## ====== Beginning DescribeCoverage section ======
# read-out the DescribeCoverage Tab, execute a DescribeCoverage request and display response
# in a general purpose window
@mouse_busy
def exeDescribeCoverage(self):
global selected_covid
global offered_crs
global offered_version
selected_serv, selected_url = self.get_serv_url()
try:
# a basic DescribeCoverage request
req_params = {'version': offered_version,
'request': 'DescribeCoverage',
'server_url': selected_url,
'coverageID': selected_covid }
except NameError:
msg = "Error: You need to select a CoverageID first!\n (see also GetCapabilities TAB)"
warning_msg(msg)
return
req_params = self.clear_req_params(req_params)
#print "DC: ", req_params
DC_result = self.myWCS.DescribeCoverage(req_params)
# also read out the gml:Envelope axisLabels - use only first returned entry
# TODO - associate the right axisLabe / CRS etc. with each cooverage
join_xml = ''.join(DC_result)
tree = etree.fromstring(join_xml)
axis_labels = tree.xpath("wcs:CoverageDescription/gml:boundedBy/gml:Envelope/@axisLabels|wcs:CoverageDescription/gml:boundedBy/gml:EnvelopeWithTimePeriod/@axisLabels", namespaces=tree.nsmap)
axis_labels = axis_labels[0].encode().split(" ")
#print 'AxisLabels: ',axis_labels
offered_crs = tree.xpath("wcs:CoverageDescription/gml:boundedBy/gml:Envelope/@srsName|wcs:CoverageDescription/gml:boundedBy/gml:EnvelopeWithTimePeriod/@srsName", namespaces=tree.nsmap)
offered_crs = os.path.basename(offered_crs[0])
#print 'Offered CRS: ',offered_crs
# set a default if AxisdLabels, offered_crs are not presented
if len(axis_labels) == 0:
axis_labels = ["", ""]
if len(offered_crs) == 0:
offered_crs = '4326'
# now set the parameters in the GetCoverage Tab, consider change of order for lat/lon
if offered_crs == '4326':
self.lineEdit_GCovXAxisLabel.setText(axis_labels[1])
self.lineEdit_GCovYAxisLabel.setText(axis_labels[0])
else:
self.lineEdit_GCovXAxisLabel.setText(axis_labels[0])
self.lineEdit_GCovYAxisLabel.setText(axis_labels[1])
combo_idx = self.comboBox_GCovOutCRS.findText(offered_crs)
if combo_idx == -1:
self.comboBox_GCovOutCRS.addItem(_fromUtf8(""))
self.comboBox_GCovOutCRS.setItemText(0, _translate("QgsWcsClient2", offered_crs, None))
else:
self.comboBox_GCovOutCRS.setCurrentIndex(combo_idx)
# open a new window to display the returned DescribeCoverage-Response XMl
myDisplay_txt = display_txt(self)
myDisplay_txt.textBrowser_Disp.setText(DC_result)
myDisplay_txt.show()
QApplication.changeOverrideCursor(Qt.ArrowCursor)
#---------------
# the DescribeCoverage Button
def on_DC_clicked(self):
global selected_covid
sel_DC_items = self.treeWidget_DC.selectedItems()
selected_covid = sel_DC_items[0].data(0, 0).encode()
#---------------
# parse DescribeCoverage XML-response
# def parse_DC_xml(self, DC_result):
#
# #print "I'm in "+sys._getframe().f_code.co_name
# join_xml = ''.join(DC_result)
## ====== End of DescribeCoverage section ======
## ====== Beginning DescribeEOCoverageSet section ======
# read-out the DescribeEOCoverageSet Tab, execute a DescribeEOCoverageSet request and display response
# in the GetCoverage Tab (for further selection and execution)
@mouse_busy
def exeDescribeEOCoverageSet(self):
global selected_eoid
global offered_crs
global offered_version
req_sections = []
selected_serv, selected_url = self.get_serv_url()
if self.checkBox_DCSAll.isChecked():
req_sections.append("All")
if self.checkBox_DCSDatSerDesc.isChecked():
req_sections.append("DatasetSeriesDescriptions")
if self.checkBox_DCSCovDesc.isChecked():
req_sections.append("CoverageDescriptions")
req_sections = ','.join(req_sections)
if len(req_sections) == 0:
req_sections = None
if self.radioButton_ContCont.isChecked():
req_contain = "contains"
if self.radioButton_ContOver.isChecked():
req_contain = "overlaps"
if self.checkBox_DCS_ActiveCount.isChecked():
req_count = self.spinBox_DCSCount.text().encode()
else:
req_count = None
if self.checkBox_DCSFull.isChecked():
req_IDs_only = False
else:
req_IDs_only = True
if self.checkBox_DCSFull.isChecked():
self.checkBox_DCSFull.setChecked(False)
min_x = self.lineEdit_DCSMinLon.text()
max_x = self.lineEdit_DCSMaxLon.text()
min_y = self.lineEdit_DCSMinLat.text()
max_y = self.lineEdit_DCSMaxLat.text()
if len(min_x) == 0 or len(max_x) == 0:
req_lon = None
else:
req_lon = str(min_x+","+max_x)
if len(min_y) == 0 or len(max_y) == 0:
req_lat = None
else:
req_lat = str(min_y+","+max_y)
if self.checkBox_DCS_ActiveDate.isChecked():
beginTime = self.dateTimeEdit_DCSBegin.text()
endTime = self.dateTimeEdit_DCSEnd.text()
# check if begin is before end; otherwise err_msg
if beginTime > endTime:
msg="Dates entered: End-Time before Start-Time\nPlease correct the Dates"
warning_msg(msg)
return
req_toi = str(beginTime.strip()+","+endTime.strip())
else:
req_toi = None
try:
# a basic DescribeEOCoverageSet request
if type(selected_eoid) is list:
selected_eoid = ','.join(selected_eoid)
req_params = {'version': offered_version,
'request': 'DescribeEOCoverageSet',
'server_url': selected_url,
'eoID': selected_eoid,
'subset_lon': req_lon,
'subset_lat': req_lat,
'subset_time': req_toi,
'containment' : req_contain,
'count' : req_count,
'sections' : req_sections,
'IDs_only': req_IDs_only}
#print 'req_params: ', req_params
except NameError:
msg = "Error: You need to select an DatasetSeriesID (eoID) first!\n (see also GetCapabilities TAB)"
warning_msg(msg)
return