Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
#When etree is printed the REPLACEME is subtituted by www.opengis.net, creating the correct namespaces for the DOM parsing.
#The replace is done using module re and set that it has to do only 2 replaces in the beggining. Therefore the replace is independe of the since of XML content
global process
from pywps import processes
processID=tree.tag.split("_",1)[-1]
wps2=pywps.Pywps()
wps2.inputs={'request': 'getCapabilities', 'version': '1.0.0', 'service': 'wps'}
from pywps.Wps import Request
request=Request(wps2)
try:
process=[process for process in request.processes if process.identifier in [processID]][0]
except IndexError:
# #If the server url is incorrect the process request will not be found in the WPS process list
raise pywps.NoApplicableCode("The requested process is not part of the instance. Check pywps conf file and WSDL. WSDL has to point to the correct wrapper, please check location attribute in address element of WSDL document")
XSLTDocIO=open(pywps.XSLT.__path__[0]+"/SOAP2WPS.xsl","r")
XSLTDoc=etree.parse(XSLTDocIO)
transformer=etree.XSLT(XSLTDoc)
WPSTree = transformer(tree)
etree.cleanup_namespaces(WPSTree)
XMLOut=etree.tostring(WPSTree)
XMLOut=re.sub(r'REPLACEME',"www.opengis.net",XMLOut,2)
return XMLOut
# search for ftp identifier in string in outputPath and get the ftp login and password
# TODO: Check if login or password are set, in case they are empty, anonymous is
# used as default
if outputType == "ftp":
try:
ftpLogin = config.getConfigValue("server","ftplogin")
ftpPasswd= config.getConfigValue("server","ftppasswd")
try:
ftpPort=config.getConfigValue("server","ftpport")
except:
ftpPort=21
except Exception, e:
traceback.print_exc(file=pywps.logFile)
self.cleanEnv()
raise pywps.NoApplicableCode("FTP error: " + e.__str__())
ftpURL= outputPath[6:]
# copy the file to output directory or send it to an ftp server
# literal value
#str: BoundingBoxValue
#ATTENTION to the FTP code
if output.type == "LiteralValue" or output.type== "BoundingBoxValue":
#if BounfingBoxValue we'll apply the Execute_Data_Outputs.tml
if output.type=="BoundingBoxValue":
bboxTemplateFileOut = os.path.join(os.path.split(self.templateFile)[0],"inc","Execute_Data_Outputs.tmpl")
bboxTemplateProcessor = TemplateProcessor(bboxTemplateFileOut,compile=True)
#Call private method to generate a proper dictionary
bboxOutput=self._bboxOutput(output,bboxOutput={})
[bboxTemplateProcessor.set(key, value) for (key,value) in bboxOutput.items()]
#No prettyprint to avoid problem with re
# Data
else:
templateOutput["reference"] = 0
if output.type == "LiteralValue":
templateOutput = self._literalOutput(output,templateOutput)
elif output.type == "ComplexValue":
templateOutput = self._complexOutput(output,templateOutput)
elif output.type == "BoundingBoxValue":
templateOutput = self._bboxOutput(output,templateOutput)
templateOutputs.append(templateOutput);
except Exception,e:
self.cleanEnv()
traceback.print_exc(file=pywps.logFile)
raise pywps.NoApplicableCode(
"Process executed. Failed to build final response for output [%s]: %s" % (identifier,e))
self.templateProcessor.set("Outputs",templateOutputs)
self.storeRequired = False
if self.wps.inputs["responseform"]["responsedocument"].has_key("storeexecuteresponse"):
if self.wps.inputs["responseform"]["responsedocument"]["storeexecuteresponse"]:
outputType = "file"
outputPath = config.getConfigValue("server","outputPath")
# Check for ftp storage
if string.find(outputPath.lower(), "ftp://", 0, 6) == 0:
outputType = "ftp"
if outputType == "file":
try:
self.outputFile = open(self.outputFileName,"w")
except Exception, e:
traceback.print_exc(file=pywps.logFile)
self.cleanEnv()
raise pywps.NoApplicableCode(e.__str__())
# Set up the response document ftp object
elif outputType == "ftp":
try:
ftpHost = outputPath[6:]
ftplogin = config.getConfigValue("server","ftplogin")
ftppasswd= config.getConfigValue("server","ftppasswd")
ftpConnection = pywps.Ftp.FTP(ftpHost,port=6666)
ftpConnection.setFileName(os.path.basename(self.outputFileName))
ftpConnection.login(ftplogin, ftppasswd)
# Close to avoid time out, the response call will reconnect and relogin
ftpConnection.close()
self.outputFile = ftpConnection
except Exception, e:
traceback.print_exc(file=pywps.logFile)
if document:
#http://bugs.python.org/issue5762
parser=etree.XMLParser(resolve_entities=False)
try:
if type(input) == type(""):
self.tree=etree.parse(StringIO.StringIO(unescape(document,entities={""":"'"})),parser)
# will cause a crash
#lxml.etree.XMLSyntaxError: XML declaration allowed only at the start of the document, line 1, column 103
else:
try:
self.tree = etree.parse(StringIO.StringIO(unescape(document.toxml(),entities={""":"'"})),parser) # Not very efficient, the XML is converted to string and then back again to XML
except:
document=doCleanBug5762(document)
self.tree = etree.parse(StringIO.StringIO(unescape(document.toxml(),entities={""":"'"})),parser)
except etree.XMLSyntaxError,e: # Generic parsing error
raise pywps.NoApplicableCode(e.message)
self.root=self.tree.getroot()
#Searching of a Envelope element (case sensitive)
self.envElement=self.root.xpath("//*[contains(local-name(),'Envelope')]") #It actually retunrs the node
#Check for SOAP name space
self.nameSpaceSet=set(self.root.nsmap.values()) & set(soap_env_NS)
self.nsIndex = soap_env_NS.index(self.nameSpaceSet.pop())
if (self.nsIndex==1):
self.soapVersion=11
else:
self.soapVersion=12
#Check for ExecuteProcess
ftpConnection.relogin()
# In case the response is a file, we can send it directly
if type(response) == types.FileType:
ftpConnection.storbinary("STOR " + ftpConnection.fileName, response)
else:
# We need a read-only memory file desciptor
responseFile = cStringIO.StringIO(response)
# Send the file to the ftp server use the filename specified in the FTP object
ftpConnection.storbinary("STOR " + ftpConnection.fileName, responseFile)
responseFile.close()
ftpConnection.close()
except Exception, e:
traceback.print_exc(file=pywps.logFile)
self.cleanEnv()
raise pywps.NoApplicableCode("FTP error: " + e.__str__())
def onOutputProblem(self,what,why):
"""This method logs the existance of problens in the complexData mainly (output mimeType?)
:param what: locator of the problem
:param why: possible reason of the problem
"""
exception = None
if what == "FileSizeExceeded":
exception = pywps.FileSizeExceeded
elif what == "NoApplicableCode":
exception = pywps.NoApplicableCode
elif what == "InvalidParameterValue":
exception = pywps.InvalidParameterValue
self.cleanEnv()
raise exception(why)
def getFirstChildNode(self,document):
"""Find first usable child node of the document (no comments)"""
node = None
# get the first child (omit comments)
for node in document.childNodes:
if node.nodeType == xml.dom.minidom.Element.nodeType:
firstChild = node
if firstChild == None:
raise pywps.NoApplicableCode(
"No root Element found!")
return firstChild