source: MILK/trunk/milk_server/milk_server/models/ndgdoc.py @ 5022

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/MILK/trunk/milk_server/milk_server/models/ndgdoc.py@5023
Revision 5022, 8.6 KB checked in by cbyrom, 11 years ago (diff)

Create new data model, NDGDoc, to handle generic lookup of NDG Docs +
provide uniform info for use with the genshi templates. Implement
usage of this new class by retrieve - removing duplicated code and
simplifying the controller in the process.

Line 
1# Copyright (C) 2007 STFC & NERC (Science and Technology Facilities Council).
2# This software may be distributed under the terms of the
3# Q Public License, version 1.0 or later.
4# http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
5#
6"""
7 Wrapper class to allow general treatment of the different types of ndg documents
8 in a consistent manner
9 
10 @author C Byrom Feb 09
11"""
12
13import logging
14import milk_server.lib.helpers as h
15from milk_server.lib import Utilities
16from milk_server.lib.ndgInterface import ndgInterface
17from ndg.common.src.lib.ETxmlView import et2html
18from ndg.common.src.models import stubB, DIF, ndgObject
19from ndg.common.src.models.ndgObject import ndgObject
20from ndg.common.src.models.Atom import Atom
21from ndg.common.src.models.vocabtermdata import VocabTermData as VTD
22
23# allow re-use of this doc getter class
24NDG_INTERFACE = ndgInterface()
25           
26class NDGDoc:
27
28    def __init__(self, ndgURI = None, config = None):
29        '''
30        Constructor for NDGDoc
31        @keyword ndgURI: ndgURI string representing the ndg doc - see ndgObject
32        for accepted formats
33        @keyword config: config data to be used with ndgURI
34        '''
35        logging.debug("Instantiated NDGDoc - for doc, '%s'" %ndgURI)
36       
37        self.__initiatiliseFields()
38        self.__setupNDGObject(ndgURI, config)
39
40       
41        logging.debug("NDGDoc instantiated")
42
43
44    def __initiatiliseFields(self):
45        '''
46        Initialise the object instance fields
47        '''
48        logging.debug("Initialising object fields")
49        self.outputSchema = None
50       
51        # NB, legacy code uses kid templates - newer stuff should use genshi
52        self.templateType = 'kid'
53        self.renderTemplate = 'error'
54
55        self.name = ''
56        self.docModel = None
57        self.htmlCode = None
58       
59        # getDoc populates these fields
60        self.xmlString = ""
61        self.xmlh = None    # xml object version of doc
62        self.status = 0
63       
64        # the atom doc model has a few extra fields - set a simple tag to
65        # check if the doc is an atom or not to make it easier to use these
66        self.isAtom = False
67        logging.debug("- fields initialised")
68
69
70    def setupDocumentModel(self, ndgUri = None, config = None,
71                             outputSchema = None, format = None):
72        '''
73        Retrieve and set up document model relating to specified ndgUri
74        @keyword ndgURI: ndgURI string representing the ndg doc
75        @keyword config: config data to be used with ndgURI
76        @keyword outputSchema: format to return doc in. Default = None =>
77        return doc in its original format
78        @keyword format: display format of doc - currently can specify
79        'xml' (return html visible xml), 'raw' (return as is) or None - defaults
80        to standard type of data model.  Default = None   
81        '''
82        self.__initiatiliseFields()
83        if ndgUri or config:
84            self.__setupNDGObject(ndgUri = ndgUri, config = config)
85           
86        self.getDoc(outputSchema = outputSchema)
87        self.processDoc(outputSchema = outputSchema, format = format)
88
89
90    def __setupNDGObject(self, ndgUri = None, config = None):
91        '''
92        Set up the underlying ndgObject, used to retrieve the doc and set the
93        data model details
94       
95        @keyword ndgURI: ndgURI string representing the ndg doc
96        @keyword config: config data to be used with ndgURI
97        '''
98        if ndgUri:
99            self.ndgUri = ndgUri
100           
101        if config:
102            self.config = config
103
104        if self.ndgUri:
105            self.ndgObject = ndgObject(self.ndgUri, config = self.config)
106           
107       
108    def getDoc(self, outputSchema = None):
109        '''
110        Retrieves the ndg doc
111        @keyword outputSchema: format to return doc in. Default = None =>
112        return doc in its original format
113        @keyword format: display format of doc - currently can specify
114        'xml' (return html visible xml), 'raw' (return as is) or None - defaults
115        to standard type of data model.  Default = None   
116        '''
117        logging.info("Retrieving document to view")
118        if not self.ndgUri:
119            raise ValueError("No NDG uri specified!")
120
121        useCache = True
122        viewFormat = self.ndgObject.schema
123        # NB, don't use cache if we're looking up atoms as these can change quickly
124        # when using the atom editor
125        if viewFormat == ndgObject.ATOM_DOC_TYPE or \
126            viewFormat ==  ndgObject.ATOM_BACKUP_DOC_TYPE:
127            useCache = False
128           
129        self.status, self.xmlString = NDG_INTERFACE.GetXML(self.ndgUri, 
130                                                           outputSchema = outputSchema,
131                                                           useCache = useCache)
132        logging.info("Document retrieve complete")
133
134
135    def processDoc(self, outputSchema = None, format = None):
136        '''
137        Extract details from the NDG Doc, according to the doc type
138        '''
139        logging.debug("Processing document...")
140        if not self.status:
141            self.renderTemplate = 'error'
142            self.htmlCode = 400
143            if self.xmlString.startswith('<p> Access Denied'):
144                self.htmlCode = 401
145            logging.error(self.xmlString)
146            return
147       
148        logging.debug("Document retrieved ok - now processing results")
149
150        viewFormat = self.ndgObject.schema
151        if outputSchema: 
152            viewFormat = outputSchema
153           
154        if not format:
155            format = 'default'
156
157        logging.debug("Doc format: '%s', View format: '%s'" \
158                       %(format, viewFormat))
159
160        # get name to pass to trackback rdf - make more general, if possible
161        # using the doc details
162        self.name = self.ndgUri
163       
164        # now set up any additional info for the different document models
165        # - NB, raw and xml formats just return the info unadorned - so don't
166        # need to worry about setting up underlying data models
167        if format == 'xml':
168            self.xml = et2html(ET.fromstring(self.xmlString))
169            self.renderTemplate = 'content'
170
171        elif format == 'raw':
172            self.xml = self.xmlString
173           
174        elif viewFormat == ndgObject.ATOM_DOC_TYPE or \
175            viewFormat ==  ndgObject.ATOM_BACKUP_DOC_TYPE:
176
177            self.isAtom = True
178            atom = Atom(xmlString = self.xmlString, ndgObject = self.ndgObject)
179            self.templateType = "genshi"
180            self.renderTemplate = 'atom_editor/atom_editor'
181            self.name = atom.title
182           
183            # get the current publication state
184            edc = Utilities.getExistClient(atom.ME.providerID)
185            atom.state = edc.getAtomPublicationState(atom.datasetID,
186                                                          atom.ME.providerID)
187           
188            atom.deploymentsURL = h.url_for(controller='browse/retrieve',
189                                            action='viewAssociatedData',
190                                            type = VTD.DEPLOYMENT_TERM,
191                                            uri = self.ndgUri)
192            atom.dataEntitiesURL = h.url_for(controller='browse/retrieve',
193                                             action='viewAssociatedData',
194                                             type = VTD.DE_TERM,
195                                             uri = self.ndgUri)
196            self.docModel = atom
197
198        elif viewFormat == ndgObject.MOLES_DOC_TYPE:
199
200            self.docModel = stubB.stubB(ET.fromstring(self.xmlString), self.config)
201            self.renderTemplate = 'browse/stubB'
202            self.name = self.docModel.abbreviation
203           
204        elif viewFormat == ndgObject.NDGA0_DOC_TYPE:
205            self.renderTemplate = 'content'
206            self.name = self.ndgObject.localID
207            #for now we'll handle as pretty print xml
208            self.xml = et2html(ET.fromstring(self.xmlString))
209           
210        elif viewFormat == ndgObject.DIF_DOC_TYPE or \
211            viewFormat == ndgObject.BROWSE_DIF_DOC_TYPE:
212
213            self.docModel = DIF.DIF(self.xmlString, ndgObj = self.ndgObject)
214            self.renderTemplate = 'browse/dif'
215            self.name = self.docModel.name
216           
217        elif viewFormat == ndgObject.NUMSIM_DOC_TYPE:
218
219            self.renderTemplate = 'browse/numsim'
220            self.xmlh = ET.fromstring(self.xmlString)
221            self.name = self.xmlh.findtext('NS_Name')
222           
223        else:
224            self.renderTemplate = 'content'
225            self.xml = et2html(ET.fromstring(self.xmlString))
226
227        self.htmlCode = 200
228        logging.debug("- finished processing document")
229           
Note: See TracBrowser for help on using the repository browser.