source: exist/trunk/python/ndgUtils/ndgObject.py @ 4167

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/exist/trunk/python/ndgUtils/ndgObject.py@4167
Revision 4167, 6.2 KB checked in by cbyrom, 12 years ago (diff)

Pull out common constants into module level variables, to improve
consistency + re-use. Fix setting of some config file defaults.
Extend test suite + improve - add checks for config files and use
module level variables.

Line 
1import ndgRetrieve,xmlHandler2, logging
2
3# The various different document types:
4MOLES_DOC_TYPE = 'NDG-B0'
5DIF_DOC_TYPE = 'DIF'
6DC_DOC_TYPE = 'DC'
7ISO_DOC_TYPE = 'ISO19139'
8NDGB1_DOC_TYPE = 'NDG-B1'
9NDGB0_DOC_TYPE = 'NDG-B0'
10MDIP_DOC_TYPE = 'MDIP'
11NDGA0_DOC_TYPE = 'NDG-A0'
12NUMSIM_DOC_TYPE = 'NumSim'
13ATOM_DOC_TYPE = 'ATOM'
14ATOM_BACKUP_DOC_TYPE = 'ATOM-BACKUP'
15   
16# Group the doc types according to the source they should be retrieved from
17DISCOVERY_SCHEMES = ['DIF','DC','MDIP','ISO19139', 'ISO']
18BROWSE_SCHEMES = ['NDG-B0','NDG-B1','NumSim', 'ATOM', 'ATOM-BACKUP']
19
20class ndgObject:
21    ''' This class instantiates an ndgObject which describes the various ways
22        of obtaining itself, primarily
23                (1) a downloadable xml representation from a repository,
24                (2) a printable xml representation '''
25   
26    def __init__(self,uri,config=None):
27        ''' Parse the uri and prepare for obtaining the actual content'''
28        logging.debug("Initialising ndgObject with uri: '%s'" %uri)
29        #Dom had problem with unicode coming in here ... dunno why @@@@
30        uri=str(uri) 
31       
32        # a priori, assume we can't get content for this object
33        self.gettable=-1 
34       
35        # handle all the known ways of doing an NDG URI ...
36        bits=uri.split(':')
37        bits2=uri.split('__')
38        ok=1
39        if len(bits)==3:
40            repository,schema,localID=bits
41            self.uri=uri.replace(':','__')
42        elif len(bits2)==3:
43            repository,schema,localID=bits2
44            self.uri=uri
45        elif len(bits2)>3:
46            repository,schema,localID=bits2[0],bits2[1],'__'.join(bits2[2:])
47            self.uri=uri
48        else:
49            bits=uri.split('/')
50            if len(bits)==2:
51                schema='NDG-B0'
52                repository,localID=bits
53                self.uri=None  #
54                ok=0  # I reckon we shouldn't ever see any of these again ...
55                # but if we do, the uri will need fixing too ...
56            else: ok=0
57       
58        if not ok:
59            # after all that, we don't think it's an NDG URI ...
60            raise ValueError,'The identifier [%s] is not a valid NDG style URI'%uri
61
62        # yes, it is an NDG URI ...
63        self.repository,self.schema,self.localID=repository,schema,localID
64        logging.debug("Extracted valid NDG values from URI: repository: '%s', schema: '%s', localID: '%s'" \
65                      %(repository, schema, localID))
66        self.setConfig(config)
67       
68    def setConfig(self,config):
69        '''
70        Set up the configuration for retrieving this document
71        '''
72        logging.debug("Setting up configuration for retrieving document")
73        self.config=config
74        if config is None:
75            self.discoveryURL,self.baseURL,self.xmlURL,self.printableURL=None,None,None,None
76            self.BURL=None
77            return
78
79        self.server=self.config.get('DISCOVERY','default')
80        server=self.server
81        qs=None
82        # This NDG object may itself be a discovery record, which makes life easy, but
83        # it might not be, in which case we have to build up all the possible views upon it.
84        # But remember only data entity b records have discovery records ...
85        self.viewService='%s/view/'%server
86        discoveryBASE='%s%s__%s__%s'%(self.viewService,self.repository,self.schema,self.localID)
87
88        # set default return format - if not set, just return in original format
89        fmt=''
90        if self.config.has_option('DISCOVERY','formatDefault'):
91            fmt=self.config.get('DISCOVERY','formatDefault')
92            logging.info("Default discovery format set to: %s" %fmt)
93           
94        self.BURL=None
95        # We'll build the following even if it can't be used (as would be the case for
96        # a non data entity B record or an A record) because it's a useful template.
97        if self.schema!=fmt: qs=('outputSchema',fmt)
98        self.discoveryURL=self.__buildURL(discoveryBASE,[qs])
99        servicehost=self.config.get('NDG_B_SERVICE',self.repository,'unknown')
100        # If this record is itself a discovery record, then we don't have much more to do
101        if self.schema in DISCOVERY_SCHEMES:
102            self.xmlURL=self.__buildURL(
103                discoveryBASE.replace('/view/','/retrieve/'),[qs,('format','raw')])
104            self.printableURL=self.__buildURL(discoveryBASE,[qs,('format','xml')])
105            self.URL=self.discoveryURL
106            if servicehost!='unknown':self.gettable=1
107        elif self.schema in BROWSE_SCHEMES:
108            # One day we'll use a service binding to get this
109            # This is a mapping from the ndg repository id to an actual repository id
110            # understood by the ndg exist interface
111            blank=self.config.get('NDG_B_SERVICE','instance')
112            url=blank.replace('SERVICEHOST',servicehost)
113            url=url.replace('URI',self.uri)
114            self.URL=url
115            self.xmlURL=url.replace('/view/','/retrieve/')+'?format=raw'
116            self.printableURL=url+'?format=xml'
117            if servicehost!='unknown': self.gettable=0
118        else:
119            #currently we don't know how to get this one
120            self.URL='unknown'
121            self.discoveryURL,self.baseURL,self.xmlURL,self.printableURL=None,None,None,None
122
123        logging.debug("Set up URL: '%s'\ndiscoveryURL: '%s'" %(self.URL, self.discoveryURL))
124           
125        #now, we'll build a stub-B url as well, in case that comes in handy
126        if self.schema!='NumSim' and self.gettable<>-1:
127            self.BURL=discoveryBASE.replace(self.schema,'NDG-B1')
128            self.BURL=self.BURL.replace(server,servicehost)
129            logging.debug("Set up stub-B url: '%s'" %self.BURL)
130
131
132    def __buildURL(self,base,queryStuff):
133        ss=''
134        for i in queryStuff: 
135            if i!=None:ss+='&%s=%s'%(i[0],i[1])
136        if ss!='':ss='?'+ss[1:]
137        return base+ss
138           
139    def get(self,securityCredentials=None):
140        ''' Actually retrieve an ORIGINAL xml record corresponding to an ndg URI '''
141        if self.config is None: return None
142        status,xmlh=ndgRetrieve(self,self.config)
143        if status:
144            x=xmlHandler2.xmlHandler(xmlh,string=1)
145            return x.xmls
146        else:
147            return status
148       
149    def __str__(self):
150        return self.uri
151
Note: See TracBrowser for help on using the repository browser.