43
|
1 '''
|
|
2 Created on 2.9.2010
|
|
3
|
|
4 @author: casties, fknauft
|
|
5 '''
|
|
6
|
|
7 from OFS.Folder import Folder
|
|
8 from Products.PageTemplates.PageTemplateFile import PageTemplateFile
|
|
9 from Products.ZSQLExtend import ZSQLExtend
|
|
10 import logging
|
|
11 import re
|
|
12 import time
|
61
|
13 import datetime
|
57
|
14 import urllib
|
43
|
15
|
|
16 from RestDbInterface import *
|
|
17
|
|
18
|
|
19
|
55
|
20 def kmlEncode(s):
|
|
21 """returns string encoded for displaying in KML attribute"""
|
|
22 res = s.replace("'","__Apostroph__")
|
|
23 res = res.replace('"','__DoubleApostroph__')
|
|
24 res = res.replace(';','__$$__')
|
|
25 res = res.replace('&','&')
|
|
26 return res
|
|
27
|
|
28
|
43
|
29 class RestDbGisApi(RestDbInterface):
|
|
30 """Object for RESTful GIS database queries
|
|
31 path schema: /db/{schema}/{table}/
|
|
32 omitting table gives a list of schemas
|
|
33 omitting table and schema gives a list of schemas
|
|
34 """
|
|
35
|
|
36 meta_type="RESTgis"
|
|
37
|
|
38 # data templates
|
|
39 GIS_schema_table = PageTemplateFile('zpt/GIS_schema_table', globals())
|
55
|
40 KML_schema_table = PageTemplateFile('zpt/KML_schema_table', globals())
|
61
|
41 HTML_schema_usertables = PageTemplateFile('zpt/HTML_schema_usertables', globals())
|
55
|
42
|
44
|
43 # and scripts
|
|
44 def KML_URL_schema_table(self,schema,table):
|
|
45 """KML_URL table function"""
|
|
46 self.REQUEST.RESPONSE.setHeader("Content-Type", "text/plain")
|
|
47 id = self.REQUEST.get('id',[])
|
|
48 doc = self.REQUEST.get('doc',None)
|
57
|
49 return self.getLiveKmlUrl(schema=schema,table=table)
|
43
|
50
|
61
|
51 #
|
|
52 # database methods
|
|
53 #
|
70
|
54 toSqlTypeMap = {
|
|
55 "text": "text",
|
|
56 "number": "numeric",
|
|
57 "id": "text",
|
|
58 "gis_id": "text",
|
|
59 "coord_lat": "numeric",
|
|
60 "coord_lon": "numeric"
|
|
61 }
|
|
62
|
60
|
63 def getTableOwner(self,schema,table):
|
|
64 """returns the owner of the table"""
|
61
|
65 # what do we do with the schema?
|
|
66 sql = 'select table_owner from public.gis_table_meta where table_name = %s'
|
|
67 res = self.executeSQL(sql,(table,))
|
|
68 if len(res['rows']) > 0:
|
|
69 return res['rows'][0][0]
|
60
|
70 return None
|
|
71
|
|
72 def isAllowed(self,action,schema,table,user=None,owner=None):
|
43
|
73 """returns if the requested action on the table is allowed"""
|
|
74 if user is None:
|
|
75 user = self.REQUEST.get('AUTHENTICATED_USER',None)
|
60
|
76 logging.debug("isAllowed action=%s schema=%s table=%s user=%s"%(action,schema,table,user))
|
|
77 if action == "create":
|
|
78 if user is not None and str(user) != 'Anonymous User':
|
|
79 # any authenticated user can create
|
|
80 return True
|
|
81 else:
|
|
82 return False
|
|
83
|
|
84 if action == "update":
|
|
85 if owner is None:
|
|
86 owner = self.getTableOwner(schema,table)
|
61
|
87 logging.debug("isAllowed user=%s owner=%s"%(user,owner))
|
60
|
88 if user is not None and str(user) == str(owner):
|
|
89 # update only your own table
|
|
90 return True
|
|
91 else:
|
|
92 return False
|
|
93
|
62
|
94 # anything else is allowed
|
43
|
95 return True
|
|
96
|
61
|
97 def setTableMetaTypes(self,schema,table,fields,user=None):
|
43
|
98 """sets the GIS meta information for table"""
|
61
|
99 if user is None:
|
|
100 user = self.REQUEST.get('AUTHENTICATED_USER',None)
|
|
101
|
|
102 logging.debug("settablemetatypes schema=%s, table=%s, fields=%s user=%s"%(schema,table,fields,user))
|
43
|
103
|
61
|
104 today = datetime.date.today().isoformat()
|
|
105
|
|
106 res = self.executeSQL('select * from public.gis_table_meta where table_name = %s', (table,))
|
43
|
107 if len(res['rows']) > 0:
|
|
108 # meta record exists
|
61
|
109 sql = 'update public.gis_table_meta set table_owner=%s, table_modified=%s where table_name=%s'
|
|
110 self.executeSQL(sql, (str(user),today,table), hasResult=False)
|
43
|
111 else:
|
|
112 # new meta record
|
61
|
113 sql = 'insert into public.gis_table_meta (table_name,table_owner,table_created) values (%s,%s,%s)'
|
|
114 self.executeSQL(sql, (table,str(user),today), hasResult=False)
|
|
115
|
|
116 # update row info
|
|
117 sql = 'delete from public.gis_table_meta_rows where table_name=%s'
|
|
118 self.executeSQL(sql,(table,),hasResult=False)
|
|
119 sql = 'insert into public.gis_table_meta_rows (table_name,field_name,gis_type) values (%s,%s,%s)'
|
|
120 for f in fields:
|
|
121 t = f['type']
|
|
122 fn = f['name']
|
|
123 self.executeSQL(sql, (table,fn,t), hasResult=False)
|
43
|
124
|
|
125
|
61
|
126 def getListOfUserTables(self,schema='public',username='guest'):
|
|
127 """return list of tables"""
|
|
128 logging.debug("getlistofusertables")
|
|
129 # get list of db tables
|
100
|
130 # qstr = """SELECT t.table_name FROM information_schema.tables t, public.gis_table_meta m WHERE t.table_type = 'BASE TABLE'
|
|
131 # AND t.table_schema = %s AND t.table_name = m.table_name ORDER BY 1"""
|
|
132 qstr = """SELECT t.table_name FROM information_schema.tables t, public.gis_table_meta m
|
|
133 WHERE t.table_schema = %s AND t.table_name = m.table_name ORDER BY 1"""
|
43
|
134
|
61
|
135 data=self.executeSQL(qstr,(schema,))
|
|
136 return data
|
|
137
|
43
|
138
|
|
139 def createEmptyTable(self,schema,table,fields):
|
|
140 """create a table with the given fields
|
|
141 returns list of created fields"""
|
61
|
142 sqlFields = RestDbInterface.createEmptyTable(self,schema,table,fields)
|
|
143 if sqlFields is not None:
|
43
|
144 self.setTableMetaTypes(schema,table,sqlFields)
|
61
|
145
|
|
146 return sqlFields
|
43
|
147
|
|
148
|
59
|
149 def getLiveKmlUrl(self,schema,table,useTimestamp=True,REQUEST=None):
|
57
|
150 if REQUEST is None:
|
|
151 REQUEST = self.REQUEST
|
55
|
152 logging.debug("getLiveKmlUrl")
|
|
153 baseUrl = self.absolute_url()
|
57
|
154 timestamp = time.time()
|
59
|
155 # filter parameters in URL and add to new URL
|
57
|
156 params = [p for p in REQUEST.form.items() if p[0] not in ('format','timestamp')]
|
|
157 params.append(('format','KML'))
|
59
|
158 if useTimestamp:
|
|
159 # add timestamp so URL changes every time
|
|
160 params.append(('timestamp',timestamp))
|
57
|
161 paramstr = urllib.urlencode(params)
|
|
162 return "%s/db/%s/%s?%s"%(baseUrl,schema,table,paramstr)
|
55
|
163
|
127
|
164 def getKmlData(self, schema, table, ids=None, sortBy=1, gisIdField=None, latField=None, lonField=None, geomField="point", colorField="red"):
|
55
|
165 """returns data structure for KML template"""
|
148
|
166 logging.debug("getKMLdata gid=%s lat=%s lon=%s geom=%s color=%s"%(gisIdField,latField,lonField,geomField,colorField))
|
|
167 if geomField is None:
|
|
168 geomField="point"
|
|
169 if colorField is None:
|
|
170 colorField="red"
|
55
|
171 # Mapping a set of points from table-based SQL-query:
|
|
172 qstr='SELECT * FROM "%s"."%s"'%(schema,table)
|
|
173 idList = None
|
|
174 if ids is not None:
|
|
175 qstr += ' WHERE '
|
|
176 if table=='mpdl':
|
|
177 qstr += 'mpdl_xmlsource_id IN ('
|
|
178 else:
|
|
179 qstr += 'CAST(id AS text) IN ('
|
|
180
|
|
181 idList = ids.split(",")
|
|
182 qstr += ','.join(['%s' for i in idList])
|
|
183 qstr += ')'
|
|
184
|
58
|
185 if sortBy:
|
|
186 # add sort clause
|
59
|
187 if sortBy == 1:
|
|
188 qstr += ' ORDER BY 1'
|
|
189 else:
|
|
190 # TODO: proper quoting for names
|
|
191 qstr += ' ORDER BY "%s"'%sortBy.replace('"','')
|
|
192
|
55
|
193 data = self.executeSQL(qstr,idList)
|
|
194
|
|
195 fieldMap = self.getFieldNameMap(data['fields'])
|
117
|
196 try:
|
153
|
197 geomstr='select astext(st_simplify(transform(the_geom,4326),0.01)) from "%s"."%s"'%(schema,table)
|
117
|
198 geomdata=self.executeSQL(geomstr)
|
|
199 except:
|
|
200 geomdata=None
|
|
201
|
55
|
202 if (gisIdField is None) and (latField is None or lonField is None):
|
|
203 # no fields given - choose automagically
|
93
|
204 sql = 'SELECT field_name FROM public.gis_table_meta_rows WHERE table_name = %s and gis_type = %s'
|
55
|
205 # gis id in metadata first
|
61
|
206 res = self.executeSQL(sql, (table,'gis_id'))
|
55
|
207 if len(res['rows']) > 0:
|
|
208 gisIdField = res['rows'][0][0]
|
|
209 else:
|
93
|
210 # latitude in metadata
|
|
211 res = self.executeSQL(sql, (table,'coord_lat'))
|
|
212 if len(res['rows']) > 0:
|
|
213 latField = res['rows'][0][0]
|
|
214 # longitude in metadata
|
|
215 res = self.executeSQL(sql, (table,'coord_lon'))
|
|
216 if len(res['rows']) > 0:
|
|
217 lonField = res['rows'][0][0]
|
|
218
|
|
219 if (gisIdField is None) and (latField is None or lonField is None):
|
|
220 logging.warning("no entry in metadata table for table %s" % table)
|
|
221 # still no fields - try field names
|
|
222 if 'latitude' in fieldMap and 'longitude' in fieldMap:
|
|
223 latField = 'latitude'
|
|
224 lonField = 'longitude'
|
|
225 elif 'x_coord' in fieldMap and 'y_coord' in fieldMap:
|
|
226 latField = 'x_coord'
|
|
227 lonField = 'y_coord'
|
|
228 else:
|
|
229 logging.error("getKMLdata unable to find position fields")
|
|
230 return None
|
|
231
|
55
|
232
|
|
233 # convert field names to row indexes
|
|
234 gisIdIdx = fieldMap.get(gisIdField,None)
|
|
235 latIdx = fieldMap.get(latField,None)
|
|
236 lonIdx = fieldMap.get(lonField,None)
|
117
|
237 the_geom=fieldMap.get("the_geom",None)
|
55
|
238 logging.debug("gisidfield=%s idx=%s"%(gisIdField,gisIdIdx))
|
|
239
|
|
240 # convert data
|
|
241 kmlData = []
|
151
|
242 geom_list = {}
|
150
|
243 if geomField=='poly' and len(geomdata)>0:
|
|
244 geom_list=geomdata.values()[1]
|
|
245 data_list=data['rows']
|
|
246 for k in range (len(data_list)):
|
|
247 dataset = data_list[k]
|
|
248 if len(geom_list)>k:
|
|
249 geom_value = geom_list[k]
|
|
250
|
|
251
|
|
252
|
|
253 # for dataset in data['rows']:
|
65
|
254 xCoord = 0.0
|
|
255 yCoord = 0.0
|
55
|
256 if gisIdIdx is not None:
|
|
257 gisID = dataset[gisIdIdx]
|
58
|
258 coords=self.getPointForChGisId(gisID)
|
55
|
259 if coords!=None:
|
|
260 xCoord=coords[0]
|
|
261 yCoord=coords[1]
|
|
262
|
|
263 elif latIdx is not None:
|
|
264 xCoord = dataset[lonIdx]
|
|
265 yCoord = dataset[latIdx]
|
|
266
|
|
267 else:
|
|
268 logging.error("getKMLdata unable to find position")
|
|
269 return None
|
|
270
|
|
271 if float(xCoord) == 0.0:
|
|
272 continue
|
|
273
|
|
274 if float(yCoord) == 0.0:
|
|
275 continue
|
|
276
|
|
277 kmlPlace = {}
|
|
278
|
|
279 # description
|
|
280 desc = ''
|
150
|
281
|
|
282
|
|
283 for i in range (len(dataset)):
|
|
284 value = dataset[i]
|
|
285
|
55
|
286 name = data['fields'][i][0]
|
58
|
287 #logging.debug("value=%s"%value)
|
150
|
288 if name != 'the_geom':
|
|
289 if value != None:
|
57
|
290 #if name.find('name')>-1:
|
|
291 # desc += "<name>%s</name>\n"%value
|
|
292 # continue
|
|
293 #elif name.find('place')>-1:
|
|
294 # desc += "<name>%s</name>\n"%value
|
|
295 # continue
|
55
|
296
|
|
297 val = "%s: %s"%(name, value)
|
187
|
298 value=unicode(value)
|
188
|
299
|
|
300 # If there is a link within the description data, create a valid href
|
187
|
301 if value.find('http://')>-1:
|
188
|
302 link_str_beg=value.find('http://')
|
|
303 link_str_end = -1
|
|
304 link_str_end0=value.find(' ',link_str_beg)
|
|
305 link_str_end1=value.find('>',link_str_beg)
|
|
306 if link_str_end0 <link_str_end1:
|
|
307 link_str_end=link_str_end0
|
|
308 else:
|
|
309 link_str_end=link_str_end1
|
|
310 if link_str_end > -1:
|
|
311 link_str=value[link_str_beg:link_str_end]
|
|
312 val =name+": "+value[0:link_str_beg]+'<a href="' + link_str + ' " target="_blank">" ' + link_str + ' "</a>' + value[link_str_end:]
|
|
313 else:
|
|
314 link_str=value[link_str_beg:]
|
|
315 val =name+": "+value[0:link_str_beg]+'<a href="' + link_str + ' " target="_blank">" ' + link_str + ' "</a>'
|
|
316
|
|
317
|
57
|
318 #desc += kmlEncode(val)
|
|
319 desc += val
|
55
|
320 desc += '<br/>\n'
|
|
321
|
57
|
322 #kmlPlace['description'] = "<![CDATA[%s]]>"%desc
|
150
|
323
|
124
|
324
|
133
|
325 if geomField=='point':
|
189
|
326 kmlPlace['description'] = desc
|
133
|
327 kmlPlace['icon'] = '#marker_icon_'+colorField
|
|
328 kmlPlace['coord_x'] = str(xCoord)
|
|
329 kmlPlace['coord_y'] = str(yCoord)
|
|
330 kmlPlace['coord_z'] = '0'
|
134
|
331 kmlData.append(kmlPlace)
|
135
|
332 if geomField=='poly' and len(geomdata)>0:
|
150
|
333 polys=str(geom_value).split('(')
|
144
|
334 aaa=len(polys)
|
142
|
335 for poly in polys:
|
150
|
336 kmlPlace = {}
|
|
337 kmlPlace['description'] = desc
|
152
|
338 coords=poly.replace(')','').replace("'","").split(',')
|
150
|
339 coord_string=''
|
144
|
340 if len(coords)>1:
|
146
|
341 for coord in coords:
|
|
342 coord=coord.split(' ')
|
|
343 try:
|
|
344 x_coord=coord[0]
|
150
|
345 if x_coord=='121.675615842265':
|
|
346 a='pause'
|
146
|
347 y_coord=coord[1]
|
|
348 except:
|
|
349 break
|
150
|
350 coord_string+=x_coord+','+y_coord+','+'0 '
|
|
351 if coord_string != '':
|
|
352 kmlPlace['LinearRing']=coord_string
|
|
353 kmlPlace['LineColor']=colorField
|
|
354 kmlData.append(kmlPlace)
|
55
|
355 #logging.debug("kmlData=%s"%(repr(kmlData)))
|
|
356 return kmlData
|
58
|
357
|
|
358 def getPointForChGisId(self, gis_id):
|
|
359 """returns coordinate pair for given gis_id"""
|
59
|
360 def getPoint(id):
|
157
|
361 sql="SELECT x_coord,y_coord FROM chgis.chgis_coords WHERE gis_id = CAST(%s AS text)"
|
|
362 str_gis_id=str(gis_id).split('.')[0]
|
|
363 res = self.executeSQL(sql, (str_gis_id,))
|
59
|
364 if len(res['rows']) > 0:
|
|
365 return res['rows'][0]
|
|
366 return None
|
55
|
367
|
58
|
368 if gis_id is None or gis_id == "":
|
|
369 return None
|
|
370
|
59
|
371 # try gis_id
|
|
372 coords = getPoint(gis_id)
|
|
373 if coords is None:
|
58
|
374 # try to clean gis_id...
|
|
375 gis_id = re.sub(r'[^0-9]','',gis_id)
|
|
376 # try again
|
59
|
377 coords = getPoint(gis_id)
|
|
378 if coords is None:
|
58
|
379 logging.error("CH-GIS ID %s not found!"%repr(gis_id))
|
|
380
|
|
381 # TODO: do we need the getCoordsFromREST_gisID stuff?
|
|
382
|
59
|
383 return coords
|
|
384
|
55
|
385
|
59
|
386 ## legacy methods...
|
|
387
|
|
388 def getKmlUrl(self,schema='chgis',table='mpdl',id=[],doc=None):
|
|
389 logging.debug("getKmlUrl")
|
|
390 data = self.getDataForGoogleMap(schema,table,id,doc)
|
|
391 kml=self.getKMLname(data=data,table=table)
|
|
392 baseUrl = self.absolute_url()
|
|
393 return "%s/daten/%s"%(baseUrl,kml)
|
|
394
|
|
395 def getDataForGoogleMap(self,schema='chgis',table='mpdl',id=None,doc=None):
|
|
396 logging.debug("getDataForGoogleMap")
|
|
397 qstr="SELECT * FROM "+schema+"."+table
|
|
398 try:
|
|
399 if id is not None:
|
|
400 qstr=qstr+" WHERE "
|
|
401 for id_item in id.split(","):
|
|
402 if table=='mpdl':
|
|
403 qstr=qstr+" mpdl_xmlsource_id = '"+id_item+ "' OR"
|
|
404 else:
|
|
405 qstr=qstr+" cast(id as text) LIKE '"+id_item+ "' OR"
|
|
406 qstr=str(qstr).rsplit(" ",1)[0] #to remove last " and "
|
|
407 data=self.ZSQLSimpleSearch(qstr)
|
|
408 return data
|
|
409 except:
|
|
410 return qstr
|
55
|
411
|
|
412
|
43
|
413 def getKMLname(self,data=[],table=""):
|
|
414 logging.debug("getKMLname")
|
|
415 #session=context.REQUEST.SESSION
|
109
|
416 kml4Marker="<kml xmlns=\'http://www.opengis.net/kml/2.2\'><Document>"
|
|
417 kml4Marker+="<Style id=\'marker_icon_red\'><IconStyle><scale>15</scale><Icon><href>http://mappit.mpiwg-berlin.mpg.de/mappit/icons/dot_red.png</href></Icon></IconStyle></Style>\n"
|
|
418 kml4Marker+="<Style id=\'marker_icon_black\'><IconStyle><scale>15</scale><Icon><href>http://mappit.mpiwg-berlin.mpg.de/mappit/icons/dot_black.png</href></Icon></IconStyle></Style>\n"
|
|
419 kml4Marker+="<Style id=\'marker_icon_blue\'><IconStyle><scale>15</scale><Icon><href>http://mappit.mpiwg-berlin.mpg.de/mappit/icons/dot_blue.png</href></Icon></IconStyle></Style>\n"
|
|
420 kml4Marker+="<Style id=\'marker_icon_green\'><IconStyle><scale>15</scale><Icon><href>http://mappit.mpiwg-berlin.mpg.de/mappit/icons/dot_green.png</href></Icon></IconStyle></Style>\n"
|
|
421 kml4Marker+="<Style id=\'marker_icon_violett\'><IconStyle><scale>15</scale><Icon><href>http://mappit.mpiwg-berlin.mpg.de/mappit/icons/dot_violett.png</href></Icon></IconStyle></Style>\n"
|
43
|
422 initializeStringForGoogleMaps=""
|
|
423 #doLine=container.getVar('doLine')
|
|
424 # Mapping a set of points from table-based SQL-query:
|
|
425 if data!=None:
|
|
426 try:
|
|
427 SQL='SELECT "attribute with gis_id" FROM public.metadata WHERE tablename = %s'
|
|
428 res = self.executeSQL(SQL, (table,))
|
|
429 gisIDattribute = res['rows'][0][0]
|
|
430 except:
|
|
431 return "table not registered within metadata"
|
|
432
|
|
433 for dataset in data:
|
|
434 try:
|
|
435 xCoord=getattr(dataset,'longitude')
|
|
436 yCoord=getattr(dataset,'latitude')
|
|
437 except:
|
|
438 try:
|
|
439 xCoord=getattr(dataset,'x_coord')
|
|
440 yCoord=getattr(dataset,'y_coord')
|
|
441 except:
|
|
442 #try:
|
|
443 gisID=getattr(dataset,gisIDattribute)
|
|
444 coords=self.getPoint4GISid(gisID)
|
|
445 if coords!=None:
|
|
446 xCoord=coords[0]
|
|
447 yCoord=coords[1]
|
|
448 # except:
|
|
449 # return "no coordinates found"
|
|
450
|
|
451 if float(xCoord)!=0:
|
|
452 if float(yCoord)!=0:
|
|
453 kml4Marker=kml4Marker+"<Placemark>"
|
|
454 kml4Marker=kml4Marker+"<description> <![CDATA[<b>"
|
|
455 for values in dataset:
|
55
|
456 #logging.debug("values=%s"%repr(values))
|
43
|
457 if values != (None, None):
|
|
458 if str(values).find('name')>-1:
|
|
459 kml4Marker=kml4Marker+"<name>"+str(values[1])+"</name>\n"
|
|
460 continue
|
|
461 elif str(values).find('place')>-1:
|
|
462 kml4Marker=kml4Marker+"<name>"+str(values[1])+"</name>\n"
|
|
463 continue
|
|
464
|
|
465 kml4Marker=kml4Marker+str(values)+": "
|
|
466 attribute_string=str(values).replace("'","__Apostroph__")
|
|
467 attribute_string=str(attribute_string).replace('"','__DoubleApostroph__')
|
|
468 attribute_string=str(attribute_string).replace(';','__$$__')
|
|
469 attribute_string=str(attribute_string).replace('&','&')
|
|
470 if str(attribute_string).find('http')>-1:
|
|
471 attribute_string='<A HREF=' + str(attribute_string) + ' target=_blank>' + str(attribute_string) + '</A>'
|
|
472 kml4Marker=kml4Marker+attribute_string+"</a><br>\n"
|
|
473
|
|
474 kml4Marker=kml4Marker+"]]></description>\n"
|
117
|
475 kml4Marker=kml4Marker+"<styleURL>#marker_icon_red</styleURL>\n"
|
43
|
476 kml4Marker=kml4Marker+"<Point>"
|
|
477
|
|
478 kml4Marker=kml4Marker+"<coordinates>"+str(xCoord)+","+str(yCoord)+",0</coordinates>\n"
|
|
479 kml4Marker=kml4Marker+"</Point>\n"
|
|
480 kml4Marker=kml4Marker+"</Placemark>\n"
|
|
481
|
|
482 kml4Marker=kml4Marker+"</Document>\n</kml>"
|
|
483 kmlFileName="marker"+str(time.time())+".kml"
|
|
484
|
|
485 #kml4Marker=str(kml4Marker).replace('&','$$')
|
|
486 #kml4Marker=str(kml4Marker).replace(';','__$$__')
|
|
487 #kml4Marker=str(kml4Marker).replace('#','__SHARP__')
|
|
488 isLoadReady='false'
|
|
489 while isLoadReady=='false':
|
|
490 isLoadReady=self.RESTwrite2File(self.daten,kmlFileName,kml4Marker)
|
|
491
|
|
492 return kmlFileName
|
|
493
|
44
|
494 # def getGoogleMapString(self,kml):
|
|
495 # logging.debug("getGoogleMapString")
|
|
496 # printed= '<body %s> '%kml +"""\n <div id="map_canvas" style="width: 98%; height: 95%"> </div> \n </body>" \n </html>"""
|
|
497 # return printed
|
43
|
498
|
|
499 def getPoint4GISid(self,gis_id):
|
|
500 j=0
|
|
501 coords=(0,0)
|
|
502 if gis_id != None:
|
|
503 while (True):
|
|
504 j=j+1
|
|
505 if (j>100): # FJK: just to prevent endless loops
|
|
506 break
|
|
507 if (gis_id.isdigit()): # FJK: regular exit from while-loop
|
|
508 break
|
|
509 else:
|
|
510 gis_id=gis_id.strip('abcdefghijklmnopqrstuvwxyz_') # FJK: to strip all letters
|
|
511 gis_id=gis_id.strip() # FJK: to strip all whitespaces
|
|
512 resultpoint = [0,0]
|
|
513 results = None
|
|
514 try:
|
|
515 if int(gis_id)>0:
|
|
516 SQL="SELECT x_coord,y_coord FROM chgis.chgis_coords WHERE gis_id LIKE cast("+ str(gis_id) +" as text);"
|
|
517 results=self.ZSQLSimpleSearch(SQL)
|
|
518 #print results
|
|
519 if results != None:
|
|
520 for result in results:
|
|
521 resultpoint=[getattr(result,str('x_coord')),getattr(result,str('y_coord'))]
|
|
522 if resultpoint !=[0,0]:
|
|
523 return resultpoint
|
|
524 else:
|
|
525 coords=self.getCoordsFromREST_gisID(joinid)
|
|
526 SQL="INSERT INTO chgis.chgis_coords (gis_id,x_coord,y_coord) VALUES (" +gis_id+ "," +coords[0][1]+ "," +coords[0][0]+ "); ANALYZE chgis.chgis_coords;"
|
|
527 returnstring=self.ZSQLSimpleSearch(SQL)
|
|
528 return coords[0]
|
|
529 except:
|
|
530 return "gis_id not to interpretable:"+str(gis_id)
|
|
531 else:
|
|
532 return coords[0]
|
|
533
|
|
534 def getCoordsFromREST_gisID(self,gis_id):
|
|
535 coordlist=[]
|
|
536 i=0
|
|
537 while (i<5 and coordlist==[]):
|
|
538
|
|
539 urlresponse=container.urlFunctions.zUrlopenParseString(container.urlFunctions.zUrlopenRead("http://chgis.hmdc.harvard.edu/xml/id/"+gis_id))
|
|
540 baseDocElement=container.urlFunctions.zUrlopenDocumentElement(urlresponse)
|
|
541 childnodes=container.urlFunctions.zUrlopenChildNodes(baseDocElement)
|
|
542 itemnodes=container.urlFunctions.zUrlopenGetElementsByTagName(baseDocElement,'item')
|
|
543
|
|
544 for i in range(0,container.urlFunctions.zUrlopenLength(itemnodes)):
|
|
545 itemnode=container.urlFunctions.zUrlopenGetItem(itemnodes,i)
|
|
546 itemspatialnodes=container.urlFunctions.zUrlopenGetElementsByTagName(itemnode,'spatial')
|
|
547 for j in range(0,container.urlFunctions.zUrlopenLength(itemspatialnodes)):
|
|
548 coord=[]
|
|
549 itemspatialnode= container.urlFunctions.zUrlopenGetItem(itemspatialnodes,j)
|
|
550 itemspatiallatnodes=container.urlFunctions.zUrlopenGetElementsByTagName(itemspatialnode,'degrees_latitude')
|
|
551 for k in range(0,container.urlFunctions.zUrlopenLength(itemspatiallatnodes)):
|
|
552 itemspatiallatnode= container.urlFunctions.zUrlopenGetItem(itemspatiallatnodes,k)
|
|
553 coord.append(container.urlFunctions.zUrlopenGetTextData(itemspatiallatnode))
|
|
554 itemspatiallngnodes=container.urlFunctions.zUrlopenGetElementsByTagName(itemspatialnode,'degrees_longitude')
|
|
555 for k in range(0,container.urlFunctions.zUrlopenLength(itemspatiallngnodes)):
|
|
556 itemspatiallngnode= container.urlFunctions.zUrlopenGetItem(itemspatiallngnodes,k)
|
|
557 coord.append(container.urlFunctions.zUrlopenGetTextData(itemspatiallngnode))
|
|
558 coordlist.append(coord)
|
|
559 gis_id= "_"+gis_id
|
|
560 return coordlist
|
|
561
|
|
562 # End for GoogleMaps creation
|
|
563
|
|
564 def RESTwrite2File(self,datadir, name,text):
|
|
565 logging.debug("RESTwrite2File datadir=%s name=%s"%(datadir,name))
|
|
566 try:
|
|
567 import cStringIO as StringIO
|
|
568 except:
|
|
569 import StringIO
|
|
570
|
|
571 # make filehandle from string
|
|
572 textfile = StringIO.StringIO(text)
|
|
573 fileid=name
|
|
574 if fileid in datadir.objectIds():
|
|
575 datadir.manage_delObjects(fileid)
|
|
576 fileInZope=datadir.manage_addFile(id=fileid,file=textfile)
|
|
577 return "Write successful"
|
|
578
|
|
579 def manage_editRestDbGisApi(self, title=None, connection_id=None,
|
|
580 REQUEST=None):
|
|
581 """Change the object"""
|
|
582 if title is not None:
|
|
583 self.title = title
|
|
584
|
|
585 if connection_id is not None:
|
|
586 self.connection_id = connection_id
|
|
587
|
|
588 #checkPermission=getSecurityManager().checkPermission
|
|
589 REQUEST.RESPONSE.redirect('manage_main')
|
|
590
|
|
591
|
|
592 manage_addRestDbGisApiForm=PageTemplateFile('zpt/addRestDbGisApi',globals())
|
|
593
|
|
594 def manage_addRestDbGisApi(self, id, title='', label='', description='',
|
|
595 createPublic=0,
|
|
596 createUserF=0,
|
|
597 REQUEST=None):
|
|
598 """Add a new object with id *id*."""
|
|
599
|
|
600 ob=RestDbGisApi(str(id),title)
|
|
601 self._setObject(id, ob)
|
|
602
|
|
603 #checkPermission=getSecurityManager().checkPermission
|
|
604 REQUEST.RESPONSE.redirect('manage_main')
|
|
605
|
|
606
|