source: MILK/trunk/milk_server/milk_server/controllers/browse/retrieve.py @ 5128

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/MILK/trunk/milk_server/milk_server/controllers/browse/retrieve.py@5128
Revision 5128, 7.9 KB checked in by cbyrom, 10 years ago (diff)

Adjust atom links when in editor mode to point to the editor instance

  • and correct these when saving the data so that the links actually

point to the browse service + turn of granule delete function when not
in edit mode + remove duplicated inclusion of badc icon + tidy up
config file.

Line 
1'''
2 Class representing pylons controller for the retrieval of metadata records - and
3 records associated with these
4 
5 @author: B Lawrence?, C Byrom, Tessella Sep 2008
6'''
7import logging
8from paste.request import parse_querystring
9from xml.parsers.expat import ExpatError
10from milk_server.lib.base import *
11from milk_server.models.ndgdoc import NDGDoc
12from milk_server.controllers.trackback.trackback import TrackbackController
13from ndg.common.src.models.ndgObject import ndgObject
14from ndg.common.src.models.vocabtermdata import VocabTermData as VTD
15from ndg.common.src.clients.xmldb.eXist.searchclient import SearchClient
16
17class RetrieveController(BaseController):
18    '''
19    Provides the pylons controller for retrieving NDG documents. The simple model
20    is now that an attempt to retrieve/uri will parse the uri, read the config file,
21    and if the local server name is not the same as the uri server name, attempt
22    to retrieve the doc remotely.
23    '''
24   
25    def __setup(self, uri):
26        ''' Common setup stuff for all the actions on this controller '''
27        logging.info("Setting up RetrieveController")
28        self.cf = request.environ['ndgConfig']
29        try:
30            self.uri=ndgObject(uri, config=self.cf)
31        except ValueError,e:
32            return e
33
34        self.inputs=dict(parse_querystring(request.environ))
35
36        # NB: we could have two types of query string argument:
37        #   format= (raw,html) and
38        #   outputSchema=(original, someSchema)
39        self.format=''
40        if 'format' in self.inputs: 
41            self.format = self.inputs['format']
42        self.outputSchema = ''
43        if 'outputSchema' in self.inputs: 
44            self.outputSchema = self.inputs['outputSchema']
45
46        self.ndgDoc = NDGDoc(ndgURI = uri, config = self.cf)
47                             
48        logging.info("RetrieveController set up")
49        return 0
50
51       
52    def index(self,uri):
53        '''
54        Returns the document unadorned in anyway, i.e. the raw xml
55        '''
56        status=self.__setup(uri)
57        if status:
58            c.xml='<p>%s</p>'%status
59            response.status_code = 400
60            return render('error')
61       
62        self.ndgDoc.setupDocumentModel(outputSchema = self.outputSchema,
63                                       format = 'xml')
64
65        if self.ndgDoc.status:
66            response.headers['Content-Type'] = 'application/xml'
67            response.write(self.ndgDoc.xmlString)
68        else:
69            # the error templates should be set up already if there's an error
70            return self.__renderModel(self.ndgDoc)
71
72
73    def viewAssociatedData(self, type, uri):
74        '''
75        Get the specified data associated with the uri
76        @param type: type of associated data to lookup - currently VTD.DEPLOYMENT_TERM
77        or VTD.DE_TERM
78        @param uri: valid ndg uri
79        @return rendered genshi deployments template
80        '''
81        logging.info("Getting %s data for '%s'" %(type, uri))
82        status=self.__setup(uri)
83        if status:
84            c.xml='<p>%s</p>'%status
85            response.status_code = 400
86            return render('error')
87
88        try:
89            # NB, we should have stored the current atom data - so look this up now
90            atom = session.get('currentAtom')
91            if atom:
92                c.atom = atom
93                self.ndgDoc.templateType = "genshi"
94                self.ndgDoc.htmlCode = 200
95            else:
96               
97                self.ndgDoc.setupDocumentModel(outputSchema = self.outputSchema,
98                                               format = self.format)
99                c.atom = self.ndgDoc.docModel
100           
101            # NB, there are two routes through here - if we're viewing a data entity,
102            # the deployment links are available directly from the atom; if not we
103            # need to look them up
104            lookupIndirectReferences = True
105            if c.atom.isDE():
106                lookupIndirectReferences = False
107           
108            searchClient = SearchClient(dbHostName = self.cf.get('NDG_EXIST','local'),
109                                        configFileName = self.cf.get('NDG_EXIST','passwordFile'))
110           
111            c.atom.lookupAssociatedData(type, searchClient, 
112                                        lookupIndirectReferences = lookupIndirectReferences)
113
114            self.ndgDoc.renderTemplate = 'atom_editor/deployments_data'
115            if type == VTD.DE_TERM:
116                self.ndgDoc.renderTemplate = 'atom_editor/data_entities_data'
117
118            # store the atom to retain the looked up info
119            session['currentAtom'] = c.atom
120            session.save()
121               
122            logging.info("- %s data retdrieved - now rendering" %type)
123
124            return self.__renderModel(self.ndgDoc)
125        except Exception, e:
126            c.xml = 'Unexpected error [%s] viewing [%s]'%(str(e), self.ndgDoc.ndgUri)
127            c.doc = ''
128            response.status_code = 400
129            logging.error(c.xml)
130            return render('error')
131           
132
133    def view(self, uri):
134        '''
135        Returns either an html marked up version of the xml, or a properly laid
136        out version of the document
137        '''
138        c.doc=None
139        # NB, this sets up self.uri as an ndgObject
140        status=self.__setup(uri)
141        if status:
142            c.xml='<p>%s</p>'%status
143            response.status_code = 400
144            return render('error')
145       
146        c.tab = 'Details'
147        c.title='Viewing [%s]'%self.uri
148       
149        self.ndgDoc.setupDocumentModel(outputSchema = self.outputSchema,
150                                       format = self.format)
151
152        c.xml = self.ndgDoc.xmlString
153
154        if self.format=='raw':
155            response.headers['Content-Type'] = 'application/xml'
156            return response.write(c.xml)
157
158        c.name = self.ndgDoc.name
159        c.xmlh = self.ndgDoc.xmlh    # xml in object form - NB, only used by NumSim docs
160        c.doc = self.ndgDoc.docModel
161
162        if self.ndgDoc.isAtom:
163            c.atom = self.ndgDoc.docModel
164           
165            # store the atom for easy re-use by asynch calls
166            # - primarily for the viewAssociatedData() method here
167            session['currentAtom'] = c.atom
168            session.save()
169               
170        # set up trackback rdf tag
171        c.tbinfo = TrackbackController().getTrackBackInfo(uri, self.ndgDoc.name)
172
173        needed=0
174        if 'lastViewed' not in session: 
175            needed=1
176           
177        session['lastViewed']=h.current_url()
178        session.save()
179
180        # only add the details tab data to the panel tab, if it is not already there
181        if needed: 
182            c.pageTabs.append(('Details',session['lastViewed']))
183
184        return self.__renderModel(self.ndgDoc)
185
186
187    def __renderModel(self, model):
188        '''
189        Render the requested document model - or handle errors appropriately
190        @param model: doc model - of type NDGDoc
191        '''
192        response.status_code = model.htmlCode
193        try:
194            logging.debug("Rendering output from data model")
195            out = render(model.templateType, model.renderTemplate)
196           
197            # if in atom editor mode, replace any browse links with to links to editor
198            if g.atomEditorEnabled:
199                out = out.replace(VTD.BROWSE_SERVER_URL, g.server)
200           
201            logging.debug("- returning rendered data model")
202            return out
203       
204        except ExpatError, e:
205            c.xml = 'XML content is not well formed'
206            c.doc = model.xmlString
207            response.status_code = 400
208            logging.error("Error retrieving [%s]: %s" % (model.ndgUri, e))
209            return render('error')
210
211        except Exception, e:
212            c.xml = 'Unexpected error [%s] viewing [%s]'%(str(e), model.ndgUri)
213            c.doc = ''
214            response.status_code = 400
215            logging.error(c.xml)
216            return render('error')
217       
218
Note: See TracBrowser for help on using the repository browser.