source: TI04-geosplat/trunk/gss/bin/GSWSInterface.py @ 1210

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI04-geosplat/trunk/gss/bin/GSWSInterface.py@1210
Revision 1210, 12.2 KB checked in by astephen, 15 years ago (diff)

Updated lots of stuff to get zsi working with version 2.0 or lower.

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2
3#   Copyright (C) 2004 CCLRC & NERC( Natural Environment Research Council ).
4#   This software may be distributed under the terms of the
5#   Q Public License, version 1.0 or later. http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
6
7"""
8GSWSInterface.py
9==============
10
11A web service wrapper around the entire package.
12
13Wraps the package functionality into the following Web Service methods:
14
15- callGSControllerDirectly(args)
16
17- startSession(username=None, password=None, secureToken=None, argList=None)
18
19- provideFileURIs(sessionID, secureToken, fileURIList)
20
21- getOptions(sessionID, secureToken=None)
22
23- selectOptions(sessionID, [[opt_1,value_1], [opt_2,value2]...[secureToken, None]])
24
25- isComplete(sessionID, secureToken=None)
26
27- createOutput(sessionID, secureToken=None)
28
29- newSession(sessionID, secureToken=None)
30
31
32Notes about the sessionID and secureToken object
33------------------------------------------------
34
35The sessionID carries information about the current session but has no security
36implications. It is simply a way for the server to keep track of the request
37between calls.
38
39The secureToken is a security object (which should be encoded) that is time limited and provides
40information on what the user is allowed to access on the server. Some servers
41do not run security and so just send around a None type as the secureToken. Those
42implementing security will require that the secureToken (held in a string) is sent
43with each method call. During each call it will updated (to ensure it remains
44time valid) and returned.
45
46All errors will be present in the instance object's self.error variable. Check for
47this after each call to test success.
48
49Notes on ZSI implementation. All objects needed to be wrapped in Python
50lists in order to be returned to the client. Hence a tuple of 4,5 has to
51be represented as [[4],[5]]. Not sure why...
52
53"""
54
55# Import standard library modules
56import sys
57import re
58import os, types
59from ZSI import dispatch
60#from ZSI.version import Version
61Version=(2,0,0)#(1,6,1) # of client ZSI - not this one!
62# Sort the ZSI version out
63zsiversion=float("%s.%s" % Version[:2])
64
65# Import package modules
66from pygss.common import *
67from pygss.GSController import *
68from pygss.serverConfig import *
69from pygss.GSErrors import *
70
71# Set global variables
72sessionID=None
73
74 
75def callGSControllerDirectly(argList):
76    """
77    Function wrapper to GSController class. This can be called directly
78    to perform all operations or the other Web Service methods can be
79    called in the appropriate order.
80    """   
81    for key, value in argList:
82        args[key]=value
83    return GSController(args)
84                                                   
85
86def startSession(username="undefined", password="undefined", secureToken="undefined"):
87    """
88    Logs a user in and supplies them with a session ID as well
89    as an encoded security token. The session ID connects them to their
90    current request serverside whilst the security token is used to
91    authorise their access.
92    Returns: sessionID, secureToken
93    """
94    print "Method called: startSession\n"     
95    args={"username":deUnicodeObject(username), "password":deUnicodeObject(password), 
96             "secureToken":deUnicodeObject(secureToken)}       
97    try:
98        controller=GSController(args)
99    except Exception, error:
100        return str(error)           
101       
102    sessionID=controller.bag["sessionID"]
103    secureToken=controller.secureToken
104    # Have to return list of lists for ZSI to work (?!)
105
106    if zsiversion<2.0:
107        sessionID=[sessionID]
108        secureToken=[secureToken]
109    print "Sending back:", sessionID, secureToken
110   
111    return [sessionID, secureToken]
112
113
114def provideFileURIs(sessionID, secureToken, fileURIList):
115    """
116    Takes in the fileURIs and saves them to the session, returns the appropriate
117    options.
118    """
119    print "Method called: provideFileURIs\n"
120   
121    print "FileURIList:", fileURIList   
122   
123    uniqueFileList=[]
124    if type(fileURIList) in (type(""), type(u'1')):
125        uniqueFileList=[deUnicodeObject(fileURIList)]
126    else:       
127      for f in fileURIList:
128        if f not in uniqueFileList:
129            uniqueFileList.append(f)
130
131    print "LLLLLL", uniqueFileList
132    args={"sessionID":deUnicodeObject(sessionID), "secureToken":deUnicodeObject(secureToken),
133          "fileURIList":deUnicodeObject(uniqueFileList)}
134
135    try:
136        controller=GSController(args)
137    except Exception, error:
138        return str(error)
139       
140    sessionID=controller.bag["sessionID"]
141    secureToken=controller.secureToken
142    optionsObject=controller.options
143    rtopts=[optionsObject[0], optionsObject[1], optionsObject[2], [secureToken]]
144
145    return rtopts
146       
147       
148def getOptions(sessionID, secureToken="undefined", optionCategoryRequested="undefined"):
149    """
150    Returns a category description of the next set of options (or the option category
151    requested by the user), a list of options based
152    on what the user has yet to request, a string explaining some more about this and a
153    security token.
154    """   
155    print "Method called: getOptions\n"
156   
157    return [[["fileVariables_1", "fileVariables_2"]],
158      [[["myfile1.nc", ["v", "u"]], ["myfile3.csml", ["t", "w"]]]],
159      [[["myfile1.nc", ["windv", "windu"]], ["myfile3.csml", ["tmp", "wwind"]]]],["securityo"]]
160   
161    print "ARGS: sessionID: %s\nsecureToken: %s, optionCategoryRequested:%s" % (sessionID, 
162              secureToken, optionCategoryRequested)
163    if type(sessionID)==type(u""):
164        sessionID=str(sessionID)
165    args={"sessionID":sessionID, "secureToken":secureToken, "optionCategoryRequested":optionCategoryRequested}
166 
167    try:
168        controller=GSController(args)
169    except Exception, error:
170        return str(error)   
171
172    optionsObject=controller.options
173             
174    print "\nOPTIONS\n==========\n", options, "\n", "OPTIONSTRINGS:\n=================\n", optionStrings, "\nOPTIONCATS:\n================\n",  optionCategories
175    return [[optionCategories], [options], [optionStrings], [secureToken]]   
176
177
178def selectOptions(sessionID, argList):
179    """
180    Makes a selection based on user requirements. This will typically follow a call
181    to getOptions() to find out what the options are.
182    Returns a call to getOptions() to grab the next set of options available to the
183    user. Alternatively, if it fails, an errorString is returned.
184    """
185    print "Method called: selectOptions\n"   
186    print sessionID
187   
188    args={"sessionID":sessionID}
189    for key,value in argList:
190        key=deUnicodeObject(key)
191        value=deUnicodeObject(value)
192        if type(key)==type(u""):
193            newkey=str(key)
194        else:
195            newkey=key
196        if type(value)==type(u""):
197            value=str(value)
198        args[newkey]=value   
199        print newkey, value
200       
201        if newkey=="fileURIList":
202            if type(value)==type(""):
203                args[newkey]=[value]
204               
205    try:
206        controller=GSController(args)
207    except Exception, error:
208        return str(error)
209       
210    sessionID=controller.bag["sessionID"]
211    print "Controller.bag:",controller.bag
212   
213    secureToken=controller.secureToken
214    optionsObject=controller.options
215    print controller.options
216
217    rtopts=[optionsObject[0], optionsObject[1], optionsObject[2], [secureToken]]
218
219    return rtopts
220   
221   
222def isComplete(sessionID, secureToken="undefined"):
223    """
224    Returns 1 if the request is complete (i.e. ready to create output file(s))
225    and 0 if not. Also returns a security token.
226    """
227    if secureToken=="rubbish":
228      return [[1], ["dsfdsffsd"]]
229    return [[0], ["dsfdsffsd"]]
230    print "Method called: isComplete\n"
231    optionsObject=getOptions(sessionID, secureToken)
232    optionCategories=optionsObject[0][0]
233    secureToken=optionsObject[3][0]
234
235    if optionCategories=="No category":
236        return [[1], [secureToken]]
237    else:
238        return [[0], [secureToken]]
239   
240
241def createOutput(sessionID, secureToken="undefined"):
242    """
243    Creates the outputs specified by user selections. It writes these files
244    locally and returns a list of paths to the data as either FTP or HTTP
245    locations.
246    Returns a list of paths and a security token.
247    """
248    print "Method called: createOutput\n"
249    args={"sessionID":deUnicodeObject(sessionID), 
250          "secureToken":deUnicodeObject(secureToken), 
251          "getOutput":"getOutput"}
252
253    try:
254        controller=GSController(args)
255    except Exception, error:
256        return str(error)   
257
258    print controller.bag
259
260    if controller.bag.has_key("graphicalOutputType") and \
261       re.match("PointValueAndMetadata", controller.bag["graphicalOutputType"]):
262        return [[controller.message], [secureToken]]
263
264       
265    URLPath=controller.bag["outputURLPath"]
266
267    return [[URLPath], [secureToken]]
268   
269    """if hasattr(controller, "message"):
270        message=controller.message
271        URLPath=""
272    else:
273        message=""
274        URLPath=controller.bag["outputURLPath"]
275   
276    statusFlag=0 # 0=allgood;1=selectionerrorfixed;2=?;3=dxerrorcannotfix
277    print  [[statusFlag], [message], [URLPath], [secureToken]]   
278    return [[statusFlag], [message], [URLPath], [secureToken]]  """ 
279   
280
281def newSession(sessionID, secureToken="undefined"):
282    """
283    Deletes content of current request.
284    Returns the sessionID and the security token..
285    """
286    print "Method called: newSession\n"   
287    args={"sessionID":sessionID, "secureToken":secureToken, "clearSession":"clearSession"}
288     
289    try:
290        controller=GSController(args)
291    except Exception, error:
292        return str(error) 
293   
294    secureToken=controller.secureToken
295    return [[sessionID], [secureToken]]
296
297       
298def summariseRequest(sessionID, secureToken="undefined"):
299    """find /home/as56/abstractWebService/releases/ -type d -name .svn -exec rm -rf {}
300\; # is untested
301
302    Returns a listing of the current request in a string and a security token.
303    """   
304    print "Method called: summariseRequest\n"
305   
306    #return [[("%s:\t%s\n" % ("stuff", "things"))*10], ["securio"]]
307   
308    args={"sessionID":sessionID, "secureToken":secureToken}
309   
310    controller=GSController(args)   
311
312    req=controller.bag
313    summaryString="\n"+"*"*40
314    summaryString=summaryString+"\nSummary of current request follows\n"
315    summaryString=summaryString+"*"*40+"\n\n" 
316    orderedSortedKeys=[]
317
318    keylist=req.keys()
319   
320    exclusions=("callMethod", "secureToken", "optionCategoryRequested", 
321                "action", "targetPage")
322    for key in keylist:
323        if req[key]!="" and key not in exclusions:  summaryString=summaryString+("%s:\t%s\n" % (key, req[key]))
324
325    secureToken=controller.secureToken 
326    print summaryString
327    return [[summaryString], [secureToken]]
328     
329
330def uploadRequest(sessionID, requestXMLString, secureToken=None):
331    """
332    Allows the user to send a request in the form of a string containing the
333    contents of an XML file conforming to the dx request specification (not
334    yet written). This is also called a Data Subset Specifier.
335    This function parses the XML into a dictionary and then uploads the arguments.
336    Returns a status flag (1=success, None=failure) and the secure token.
337    """
338    args=dxrmlHandler.DXRMLParser(requestXMLString).getDictionary()
339    args["sessionID"]=sessionID
340    args["secureToken"]=secureToken
341    try:
342        controller=GSController(args)   
343        secureToken=controller.secureToken 
344        return [[1], [secureToken]]
345    except:
346        return [[0], [secureToken]] 
347
348
349def getExtractionCosts(sessionID, secureToken="undefined"):
350    """
351    Returns an estimated duration for the creation of the output data and the
352    estimated volume of the output.
353    """
354    print "Method called: getExtractionCosts\n"   
355    args={"sessionID":sessionID, "secureToken":secureToken, "action":"requestCosts"}
356    controller=GSController(args)
357    secureToken=controller.secureToken
358    if hasattr(controller, "errorString"):
359        return controller.errorString
360    (estimatedDuration, estimatedVolume)=(controller.estimatedDuration, controller.estimatedVolume)
361    print "Returning...", [[estimatedDuration], [estimatedVolume], [secureToken]]
362    return [[estimatedDuration], [estimatedVolume], [secureToken]]       
363
364
365if __name__=="__main__": 
366    """
367    Serve all functions as Web Service methods.
368    """
369    print "Setting up server"
370    portNumber=SOAP_SERVER_PORT
371    print "Serving Web Service on port: %s" % portNumber   
372    dispatch.AsServer(port=portNumber, rpc=True)
373
374
375
Note: See TracBrowser for help on using the repository browser.