source: mauRepo/HPFos/trunk/hpfos/HPFos/osImpl/commons.py @ 8584

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/HPFos/trunk/hpfos/HPFos/osImpl/commons.py@8584
Revision 8584, 5.6 KB checked in by mnagni, 7 years ago (diff)

Incomplete - # 22560: Paging once filtering the results of the OpenSearch? interface does not work as expected
 http://team.ceda.ac.uk/trac/ceda/ticket/22560

moves the ceda_markup version to 0.0.12 in order to fully support polygon/multipolygon for georss:where element

fixes

  • string_to_datetime bug for datetime formatted with "Z"
  • updates some code after the new ceda_markup
Line 
1'''
2BSD Licence
3Copyright (c) 2012, Science & Technology Facilities Council (STFC)
4All rights reserved.
5
6Redistribution and use in source and binary forms, with or without modification,
7are permitted provided that the following conditions are met:
8
9    * Redistributions of source code must retain the above copyright notice,
10        this list of conditions and the following disclaimer.
11    * Redistributions in binary form must reproduce the above copyright notice,
12        this list of conditions and the following disclaimer in the documentation
13        and/or other materials provided with the distribution.
14    * Neither the name of the Science & Technology Facilities Council (STFC)
15        nor the names of its contributors may be used to endorse or promote
16        products derived from this software without specific prior written permission.
17
18THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
22BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
23OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29Created on 16 Aug 2012
30
31@author: mnagni
32'''
33
34from xml.etree.ElementTree import XML
35import urllib2
36from ea_model.iso_19108_2006_temporal_schema.temporal_objects.tm_instant import TM_Instant
37from ea_model.iso_19108_2006_temporal_schema.temporal_objects.tm_period import TM_Period
38import re
39from datetime import tzinfo, timedelta, datetime
40
41class OS_tz(tzinfo):
42    def __init__(self, minutes):
43        self.__offset = timedelta(minutes = minutes)       
44   
45    def utcoffset(self, dt):
46        return self.__offset
47    def dst(self, dt):
48        return timedelta(0)
49    def tzname(self,dt):
50        return "Not Defined"
51
52DATE_FORMAT = '%Y-%m-%d'
53DATETIME_FORMAT = DATE_FORMAT + 'T%H:%M:%S'
54
55def string_to_datetime(datestr):
56    datetimeformat_withtz = r'\d{4}\-([0]{1}\d{1}|[1]{1}[0-2]{1})\-([0-2]{1}\d{1}|[3]{1}[0-1]{1})T([0-1]{1}\d{1}|[2]{1}[0-3]{1})\:([0-5]{1}\d{1})\:([0-5]{1}\d{1})[\-\+]([0-1]{1}\d{1}|[2]{1}[0-3]{1})\:([0-5]{1}\d{1})'
57    datetimeformat_withnotz  = r'\d{4}\-([0]{1}\d{1}|[1]{1}[0-2]{1})\-([0-2]{1}\d{1}|[3]{1}[0-1]{1})T([0-1]{1}\d{1}|[2]{1}[0-3]{1})\:([0-5]{1}\d{1})\:([0-5]{1}\d{1})'
58    datetimeformat_withUTC  = r'\d{4}\-([0]{1}\d{1}|[1]{1}[0-2]{1})\-([0-2]{1}\d{1}|[3]{1}[0-1]{1})T([0-1]{1}\d{1}|[2]{1}[0-3]{1})\:([0-5]{1}\d{1})\:([0-5]{1}\d{1})Z'
59    dateformat  = r'\d{4}\-([0]{1}\d{1}|[1]{1}[0-2]{1})\-([0-2]{1}\d{1}|[3]{1}[0-1]{1})'   
60   
61    datetime_withtz = re.match(datetimeformat_withtz, datestr)
62    datetime_withnotz = re.match(datetimeformat_withnotz, datestr)
63    datetime_withUTC = re.match(datetimeformat_withUTC, datestr)
64
65    tzmins = None
66    if datetime_withtz is not None:
67        mytz = datestr.replace(datetime_withnotz.group(0),'')
68        hours, mins = mytz[1:].split(':')
69        tzmins = int(hours)*60 + int(mins)
70        if mytz.startswith('-'):
71            tzmins = -1*tzmins
72
73    ret_datetime = None
74    if datetime_withUTC is not None:
75        ret_datetime = \
76            datetime.strptime(datetime_withUTC.group(0)[:-1], DATETIME_FORMAT)           
77    elif datetime_withnotz is not None:
78        ret_datetime = \
79            datetime.strptime(datetime_withnotz.group(0), DATETIME_FORMAT)
80           
81    if ret_datetime is not None:
82        if tzmins is not None:             
83            ret_datetime = ret_datetime.replace(tzinfo = OS_tz(tzmins))
84        return ret_datetime
85       
86    datetime_simple = re.match(dateformat, datestr)       
87    if datetime_simple is not None:
88        return datetime.strptime(datetime_simple.group(0), DATE_FORMAT)
89
90def tm_InstantToDatetime(tm_instant):
91    idate = tm_instant.position.date8601
92    return datetime.date(int(idate.year), int(idate.month), int(idate.day))
93
94def from_pt_to_string(phenomenonTime):
95    """
96        Transforms a TM_Instant instance in a date string like '2002-07-22' (startDate) or   
97        a TM_Period instance in a string like '2002-07-22/2011-08-06' (start/endDate)
98        @param phenomenonTime: a aTM_Instace or a TM_Period instance
99        @return a pair startDate, endDate. If endDate does not exists return startDate,
100        None
101    """   
102    if phenomenonTime is None:
103        return None
104    startDate =None
105    endDate = None
106    if isinstance(phenomenonTime, TM_Instant):
107        startDate = _tm_InstantToString(phenomenonTime)
108    elif isinstance(phenomenonTime, TM_Period):
109        startDate = _tm_InstantToString(phenomenonTime.begin)       
110        endDate = _tm_InstantToString(phenomenonTime.end)
111    return startDate, endDate
112
113def _tm_InstantToString(tm_instant):
114    idate = tm_instant.position.date8601
115    return datetime(int(idate.year), int(idate.month), int(idate.day), 0, 0, 0).isoformat()
116
117def return_not_none_text(element):
118    if element is None:
119        return None
120    return element.text
121
122def get_document(host, path, port = 80, proxy = None):
123    if proxy is not None:
124        proxy = urllib2.ProxyHandler({'http': proxy})
125        opener = urllib2.build_opener(proxy)
126        urllib2.install_opener(opener)
127    connect_to = 'http://%s:%s%s' % (host, port, path)
128    response = urllib2.urlopen(connect_to)
129    return  response.read()
130
131def get_xml_document(source):
132    return XML(source)
Note: See TracBrowser for help on using the repository browser.