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