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

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

Latest working version with install method.
Can accept more than one file but doesn't combine variables yet.

  • 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
59
60# Import package modules
61from pygss.common import *
62from pygss.GSController import *
63from pygss.serverConfig import *
64from pygss.GSErrors import *
65
66# Set global variables
67sessionID=None
68
69 
70def callGSControllerDirectly(argList):
71    """
72    Function wrapper to GSController class. This can be called directly
73    to perform all operations or the other Web Service methods can be
74    called in the appropriate order.
75    """   
76    for key, value in argList:
77        args[key]=value
78    return GSController(args)
79
80
81
82def startSession(username=None, password=None, secureToken=None):
83    """
84    Logs a user in and supplies them with a session ID as well
85    as an encoded security token. The session ID connects them to their
86    current request serverside whilst the security token is used to
87    authorise their access. Also takes the list of files being provided
88    by the user for visualising from.
89    Returns: sessionID, secureToken
90    """
91    print "Method called: startSession\n"     
92    args={"username":deUnicodeObject(username), "password":deUnicodeObject(password), 
93             "secureToken":deUnicodeObject(secureToken)}       
94
95    controller=GSController(args)
96
97    if controller.error!=None:
98        return controller.error
99       
100    sessionID=controller.bag["sessionID"]
101    secureToken=controller.secureToken
102
103    return [[sessionID], [secureToken]]
104   
105
106def provideFileURIs(sessionID, secureToken, fileURIList):
107    """
108    Takes in the fileURIs and saves them to the session, returns the appropriate
109    options.
110    """
111    print "Method called: provideFileURIs\n"
112   
113    print "FileURIList:", fileURIList   
114   
115    uniqueFileList=[]
116    if type(fileURIList) in (type(""), type(u'1')):
117        uniqueFileList=[deUnicodeObject(fileURIList)]
118    else:       
119      for f in fileURIList:
120        if f not in uniqueFileList:
121            uniqueFileList.append(f)
122
123    print "LLLLLL", uniqueFileList
124    args={"sessionID":deUnicodeObject(sessionID), "secureToken":deUnicodeObject(secureToken),
125          "fileURIList":deUnicodeObject(uniqueFileList)}
126
127    try:
128        controller=GSController(args)
129    except Exception, error:
130        return str(error)
131       
132    sessionID=controller.bag["sessionID"]
133    secureToken=controller.secureToken
134    optionsObject=controller.options
135    rtopts=[optionsObject[0], optionsObject[1], optionsObject[2], [secureToken]]
136
137    return rtopts
138       
139       
140def getOptions(sessionID, secureToken=None, optionCategoryRequested=None):
141    """
142    Returns a category description of the next set of options (or the option category
143    requested by the user), a list of options based
144    on what the user has yet to request, a string explaining some more about this and a
145    security token.
146    """   
147    print "Method called: getOptions\n"
148   
149    return [[["fileVariables_1", "fileVariables_2"]],
150      [[["myfile1.nc", ["v", "u"]], ["myfile3.csml", ["t", "w"]]]],
151      [[["myfile1.nc", ["windv", "windu"]], ["myfile3.csml", ["tmp", "wwind"]]]],["securityo"]]
152   
153    print "ARGS: sessionID: %s\nsecureToken: %s, optionCategoryRequested:%s" % (sessionID, 
154              secureToken, optionCategoryRequested)
155    if type(sessionID)==type(u""):
156        sessionID=str(sessionID)
157    args={"sessionID":sessionID, "secureToken":secureToken, "optionCategoryRequested":optionCategoryRequested}
158 
159    controller=GSController(args)
160    if controller.error!=None:
161        return controller.error       
162
163    optionsObject=controller.options
164             
165    print "\nOPTIONS\n==========\n", options, "\n", "OPTIONSTRINGS:\n=================\n", optionStrings, "\nOPTIONCATS:\n================\n",  optionCategories
166    return [[optionCategories], [options], [optionStrings], [secureToken]]   
167
168
169def selectOptions(sessionID, argList):
170    """
171    Makes a selection based on user requirements. This will typically follow a call
172    to getOptions() to find out what the options are.
173    Returns a call to getOptions() to grab the next set of options available to the
174    user. Alternatively, if it fails, an errorString is returned.
175    """
176    print "Method called: selectOptions\n"   
177    print sessionID
178   
179   
180   
181    args={"sessionID":sessionID}
182    for key,value in argList:
183        key=deUnicodeObject(key)
184        value=deUnicodeObject(value)
185        if type(key)==type(u""):
186            newkey=str(key)
187        else:
188            newkey=key
189        if type(value)==type(u""):
190            value=str(value)
191        args[newkey]=value   
192        print newkey, value
193       
194        if newkey=="fileURIList":
195            if type(value)==type(""):
196                args[newkey]=[value]
197               
198    try:
199        controller=GSController(args)
200    except Exception, error:
201        return str(error)
202       
203    sessionID=controller.bag["sessionID"]
204    print "Controller.bag:",controller.bag
205   
206    secureToken=controller.secureToken
207    optionsObject=controller.options
208    print controller.options
209
210    rtopts=[optionsObject[0], optionsObject[1], optionsObject[2], [secureToken]]
211
212    return rtopts
213   
214   
215def isComplete(sessionID, secureToken=None):
216    """
217    Returns 1 if the request is complete (i.e. ready to create output file(s))
218    and 0 if not. Also returns a security token.
219    """
220    if secureToken=="rubbish":
221      return [[1], ["dsfdsffsd"]]
222    return [[0], ["dsfdsffsd"]]
223    print "Method called: isComplete\n"
224    optionsObject=getOptions(sessionID, secureToken)
225    optionCategories=optionsObject[0][0]
226    secureToken=optionsObject[3][0]
227
228    if optionCategories=="No category":
229        return [[1], [secureToken]]
230    else:
231        return [[0], [secureToken]]
232   
233
234def createOutput(sessionID, secureToken=None):
235    """
236    Creates the outputs specified by user selections. It writes these files
237    locally and returns a list of paths to the data as either FTP or HTTP
238    locations.
239    Returns a list of paths and a security token.
240    """
241    print "Method called: createOutput\n"
242    args={"sessionID":deUnicodeObject(sessionID), 
243          "secureToken":deUnicodeObject(secureToken), 
244          "getOutput":"getOutput"}
245
246    try:
247        controller=GSController(args)
248    except Exception, error:
249        return str(error)   
250
251    print controller.bag
252
253    if controller.bag.has_key("graphicalOutputType") and \
254       re.match("PointValueAndMetadata", controller.bag["graphicalOutputType"]):
255        return [[controller.message], [secureToken]]
256
257       
258    URLPath=controller.bag["outputURLPath"]
259
260    return [[URLPath], [secureToken]]
261   
262    """if hasattr(controller, "message"):
263        message=controller.message
264        URLPath=""
265    else:
266        message=""
267        URLPath=controller.bag["outputURLPath"]
268   
269    statusFlag=0 # 0=allgood;1=selectionerrorfixed;2=?;3=dxerrorcannotfix
270    print  [[statusFlag], [message], [URLPath], [secureToken]]   
271    return [[statusFlag], [message], [URLPath], [secureToken]]  """ 
272   
273
274def newSession(sessionID, secureToken=None):
275    """
276    Deletes content of current request.
277    Returns the sessionID and the security token..
278    """
279    print "Method called: newSession\n"   
280    args={"sessionID":sessionID, "secureToken":secureToken, "clearSession":"clearSession"}
281     
282    controller=GSController(args)
283    if controller.error!=None:
284        return controller.error   
285   
286    secureToken=controller.secureToken
287    return [[sessionID], [secureToken]]
288
289       
290def summariseRequest(sessionID, secureToken=None):
291    """
292    Returns a listing of the current request in a string and a security token.
293    """   
294    print "Method called: summariseRequest\n"
295   
296    #return [[("%s:\t%s\n" % ("stuff", "things"))*10], ["securio"]]
297   
298    args={"sessionID":sessionID, "secureToken":secureToken}
299   
300    controller=GSController(args)   
301
302    req=controller.bag
303    summaryString="\n"+"*"*40
304    summaryString=summaryString+"\nSummary of current request follows\n"
305    summaryString=summaryString+"*"*40+"\n\n" 
306    orderedSortedKeys=[]
307
308    keylist=req.keys()
309   
310    exclusions=("callMethod", "secureToken", "optionCategoryRequested", 
311                "action", "targetPage")
312    for key in keylist:
313        if req[key]!="" and key not in exclusions:  summaryString=summaryString+("%s:\t%s\n" % (key, req[key]))
314
315    secureToken=controller.secureToken 
316    print summaryString
317    return [[summaryString], [secureToken]]
318     
319
320def uploadRequest(sessionID, requestXMLString, secureToken=None):
321    """
322    Allows the user to send a request in the form of a string containing the
323    contents of an XML file conforming to the dx request specification (not
324    yet written). This is also called a Data Subset Specifier.
325    This function parses the XML into a dictionary and then uploads the arguments.
326    Returns a status flag (1=success, None=failure) and the secure token.
327    """
328    args=dxrmlHandler.DXRMLParser(requestXMLString).getDictionary()
329    args["sessionID"]=sessionID
330    args["secureToken"]=secureToken
331    try:
332        controller=GSController(args)   
333        secureToken=controller.secureToken 
334        return [[1], [secureToken]]
335    except:
336        return [[0], [secureToken]] 
337
338
339def getDataSubsetSpecifier(sessionID, secureToken=None):
340    """
341    Returns the dataSubsetSpecifier XML document (which might be S-metadata)
342    required by a Delivery Service to describe the subset requested, and a
343    security token.
344    """
345    print "Method called: getDataSubsetSpecifier\n"
346    args={"sessionID":sessionID, "secureToken":secureToken}
347    controller=GSController(args)
348    secureToken=controller.secureToken
349    sessionObj=controller.bag
350    dataSubsetSpecifierXMLString=dxrmlHandler.DXRMLGenerator(sessionObj).xmlString
351    print dataSubsetSpecifierXMLString
352    return [[dataSubsetSpecifierXMLString], [secureToken]]
353
354
355def getExtractionCosts(sessionID, secureToken=None):
356    """
357    Returns an estimated duration for the creation of the output data and the
358    estimated volume of the output.
359    """
360    print "Method called: getExtractionCosts\n"   
361    args={"sessionID":sessionID, "secureToken":secureToken, "action":"requestCosts"}
362    controller=GSController(args)
363    secureToken=controller.secureToken
364    if hasattr(controller, "errorString"):
365        return controller.errorString
366    (estimatedDuration, estimatedVolume)=(controller.estimatedDuration, controller.estimatedVolume)
367    print "Returning...", [[estimatedDuration], [estimatedVolume], [secureToken]]
368    return [[estimatedDuration], [estimatedVolume], [secureToken]]       
369
370
371if __name__=="__main__": 
372    """
373    Serve all functions as Web Service methods.
374    """
375    print "Importing SOAP library (ZSI)."
376    from ZSI import dispatch
377    print "Setting up server"
378    portNumber=SOAP_SERVER_PORT
379    print "Serving Web Service on port: %s" % portNumber   
380    dispatch.AsServer(port=portNumber)   
381
382
383
Note: See TracBrowser for help on using the repository browser.