source: cows/trunk/cows/builder.py @ 4912

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/cows/trunk/cows/builder.py@4912
Revision 4912, 5.9 KB checked in by spascoe, 11 years ago (diff)

Added LICENSE file and a short banner at the top of each python file.
Use add_license.py to add a license to new files.

NOTE: also contains a couple of files missed at last commit.

Line 
1# BSD Licence
2# Copyright (c) 2009, Science & Technology Facilities Council (STFC)
3# All rights reserved.
4#
5# See the LICENSE file in the source distribution of this software for
6# the full license text.
7
8# Copyright (C) 2007 STFC & NERC (Science and Technology Facilities Council).
9# This software may be distributed under the terms of the
10# Q Public License, version 1.0 or later.
11# http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
12"""
13Construct a ServiceMetadata instance with a simplified interface.
14
15"""
16
17import os
18import ConfigParser
19from cStringIO import StringIO
20
21from cows.model import *
22
23class ServiceMetadataBuilder(object):
24    def __init__(self, serviceMetadata=None):
25        if serviceMetadata is None:
26            self.clear()
27        else:
28            self.serviceMetadata = serviceMetadata
29
30    def clear(self):
31        """
32        Clear the serviceMetadata instance.
33
34        """
35        self.serviceMetadata = ServiceMetadata()
36
37    def fromConfig(self, config):
38        """
39        Load ServiceIdentification and ServiceProvider information from a
40        config file.
41
42        """
43
44        self.serviceMetadata.serviceIdentification =  self._siFromConfig(config)
45        self.serviceMetadata.serviceProvider = self._spFromConfig(config)
46
47
48    #-------------------------------------------------------------------------
49
50    def _siFromConfig(self, config):
51
52        siConfig = dict(config.items('serviceIdentification'))
53
54        # serviceType and versions are typically populated from the framework
55        # They are included here for completeness and because serviceType is
56        # required in the data model
57        type = siConfig.get('type', 'OWS')
58        versions = siConfig.get('versions', '').split()
59       
60        profiles = siConfig.get('profiles', '').split()
61        fees = siConfig.get('fees')
62        accessConstraints = siConfig.get('accessConstraints')
63
64        # Only one title & abstract supported
65        title = siConfig.get('title')
66        abstract = siConfig.get('abstract')
67
68        keywords = siConfig.get('keywords', '').split()
69
70        return ServiceIdentification(serviceType=type,
71                                     serviceTypeVersions=versions,
72                                     profiles=profiles,
73                                     fees=fees,
74                                     accessConstraints=accessConstraints,
75                                     titles=[title],
76                                     abstracts=[abstract],
77                                     keywords=keywords)
78
79    def _spFromConfig(self, config):
80        spConfig = dict(config.items('serviceProvider'))
81
82        provider = spConfig['provider']
83        site = spConfig.get('site')
84
85        # Contact info
86        name = spConfig.get('contact.name')
87        position = spConfig.get('contact.position')
88        role = spConfig.get('contact.role')
89        hos = spConfig.get('contact.hoursOfService')
90        instr = spConfig.get('contact.instructions')
91
92        # Look for all address fields of name contact.address<n>
93        address = []
94        for i in range(1, 8):
95            k = 'contact.address%d' % i
96            try:
97                address.append(spConfig[k])
98            except KeyError:
99                break
100        city = spConfig.get('contact.city')
101        adminArea = spConfig.get('contact.administrativearea') #NOTE, this has changed from administrativeArea as configparser has an apparent problem with camelcase.
102        postalCode = spConfig.get('contact.postalcode')
103        country = spConfig.get('contact.country')
104        email = spConfig.get('contact.email')
105        phone = spConfig.get('contact.phone')
106        fax = spConfig.get('contact.facsimile')
107        onlineResource = spConfig.get('contact.onlineresource')
108
109        a = Address(deliveryPoints=address, city=city,
110                    administrativeArea=adminArea, postalCode=postalCode,
111                    country=country, electronicMailAddress=email)
112        t = Telephone(voice=phone, facsimile=fax)
113        c = Contact(hoursOfService=hos,
114                    contactInstructions=instr,
115                    address=a,
116                    phone=t,
117                    onlineResource=onlineResource)
118        rp = ResponsibleParty(individualName=name,
119                              positionName=position,
120                              role=role,
121                              contactInfo=c)
122
123        return ServiceProvider(providerName=provider,
124                               serviceContact=rp,
125                               providerSite=site)
126   
127   
128#
129# Simple functional interface
130#
131
132def loadConfigFile(filename):
133    if not os.path.exists(filename):
134        raise ValueError('Configuration %s does not exist' % filename)
135
136    b = ServiceMetadataBuilder()
137
138    config = ConfigParser.SafeConfigParser()
139    config.read([filename])
140
141    b.fromConfig(config)
142
143    return b.serviceMetadata
144
145def loadConfig(configString):
146    b = ServiceMetadataBuilder()
147
148    config = ConfigParser.SafeConfigParser()
149    fp = StringIO(configString)
150    config.readfp(fp)
151
152    b.fromConfig(config)
153
154    return b.serviceMetadata
155
156
157#-------------------------------------------------------------------------------
158
159def test_loadConfig():
160    sm = loadConfig("""
161[serviceIdentification]
162type: WMS
163versions: 1.1.1 1.3.0
164fees: Loadsamoney
165accessConstraints: byebye
166title: The quick brown fox jumps
167  over the lazy dog
168abstract: None
169keywords: foo bar baz
170  spud
171
172[serviceProvider]
173provider: Superman
174site: http://example.com
175contact.name: Joe Blogs
176contact.address1: foo
177contact.address2: bar
178contact.email: foo@bar.baz
179
180""")
181
182    from genshi.template import TemplateLoader
183    from pkg_resources import resource_filename
184    loader = TemplateLoader(
185               [resource_filename('cows.pylons.templates', '')])
186    t = loader.load('wms_capabilities_1_1_1.xml')
187
188    # Mock objects
189    class C:
190        service_metadata = sm
191    c = C()
192
193    class H:
194        def url_for(self): return 'http://example.com/'
195    h=H()
196
197    print t.generate(c=c, h=h).render()
Note: See TracBrowser for help on using the repository browser.