Projet

Général

Profil

0001-trivial-remove-unused-id-wsf-files-1781.patch

Frédéric Péters, 27 décembre 2014 11:44

Télécharger (15,5 ko)

Voir les différences:

Subject: [PATCH] trivial: remove unused id-wsf files (#1781)

 wcs/qommon/idwsf.py | 351 ----------------------------------------------------
 wcs/qommon/soap.py  |  57 ---------
 2 files changed, 408 deletions(-)
 delete mode 100644 wcs/qommon/idwsf.py
 delete mode 100644 wcs/qommon/soap.py
wcs/qommon/idwsf.py
1
# w.c.s. - web application for online forms
2
# Copyright (C) 2005-2010  Entr'ouvert
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, see <http://www.gnu.org/licenses/>.
16

  
17
try:
18
    import lasso
19
except ImportError:
20
    lasso = None
21
import soap
22
import sys
23

  
24
class IdWsfInteraction(Exception):
25
    '''Signal the need for an ID-WSF 2.0 Interaction redirect.
26

  
27
       URL of the redirect and ID to refer and the new request are returned
28
       through this exception.
29
    '''
30
    url = None
31
    id = None
32
    def __init__(self, profile):
33
        self.url = profile.msgUrl
34
        self.id = profile.getSoapEnvelopeResponse().getMessageId()
35

  
36
    def __str__(self):
37
        return '<IdWsfInteraction url:%s id:%s>' % (self.ulr, self.id)
38

  
39
# FIXME: move me somewhere else found useful
40
class CanLog(object):
41
    '''Encapsulate what is needed for an object which wants to log some
42
    messages.
43

  
44
       Use setLogger(logger) to give specific logging capabilities to your
45
       object. If not set warn(), error() and info() will print on stderr.
46
    '''
47
    __logger = None
48

  
49
    def __formatMessage(self, args):
50
        context=''
51
        if hasattr(self, 'loggerContext'):
52
            context=self.loggerContext()
53
        return context+' '.join(map(str, args))
54

  
55
    def setLogger(self, logger):
56
        __logger = logger
57

  
58
    def getLogger(self):
59
        return __logger
60

  
61
    def __do(self, what, prefix, args):
62
        message = self.__formatMessage(args)
63
        if self.__logger and hasattr(self.__logger, what):
64
            getprop(self.__logger, what)(message)
65
        else:
66
            print >>sys.stderr, prefix, message
67

  
68
    def warn(self, *args):
69
        self.__do('warn', 'Warning:', args)
70

  
71
    def error(self, *args):
72
        self.__do('error', 'Error:', args)
73

  
74
    def info(self, *args):
75
        self.__do('info', 'Info:', args)
76

  
77
class IdWsfClient(CanLog,object):
78
    '''Do basic work flow to make ID-WSF 2.0 requests.
79

  
80
       reply_id allows to re-iterate a request which necessitates an
81
       interaction, you must fill it with the value of id attribute
82
       of an IdWsfInteraction exception.
83

  
84
       interactions is a boolean telling the remote services whether we support
85
       interactions.
86
       '''
87

  
88
    interactions = False
89
    epr = None
90
    url = None
91
    reply_id = None
92
    client_cert = None
93

  
94
    def __init__(self, epr = None, server = None, url = None, logger = None):
95
        self.epr = epr
96
        self.server = server
97
        self.url = url
98
        self.logger = logger
99

  
100
    def _initRequest(self, profile, *args, **kwargs):
101
        profile.setEpr(self.epr)
102

  
103
    def _doRequest(self, profile, *args, **kwargs):
104
        try:
105
            envelope = profile.getSoapEnvelopeRequest()
106
            if self.reply_id:
107
                envelope.setRelatesTo(self.reply_id)
108
            if self.interactions and not self.reply_id:
109
                envelope.setSb2UserInteractionHint( \
110
                        lasso.IDWSF2_SB2_USER_INTERACTION_HINT_INTERACT_IF_NEEDED)
111
            else:
112
                envelope.setSb2UserInteractionHint( \
113
                        lasso.IDWSF2_SB2_USER_INTERACTION_HINT_DO_NOT_INTERACT)
114
            profile.buildRequestMsg(*args, **kwargs)
115
            url = profile.msgUrl
116
            if not url:
117
                url = self.url
118
            response = soap.soapCall(url, profile.msgBody,
119
                    key = kwargs.get('key'), cert = kwargs.get('cert'))
120
            profile.processResponseMsg(response)
121
        # Handle Interaction Service
122
        except lasso.WsfprofileRedirectRequestError:
123
            if self.interactions:
124
                e=IdWsfInteraction(profile)
125
                self.reply_id=e.id
126
                raise e
127
            else:
128
                raise
129

  
130
class IdWsfService(CanLog,object):
131
    interactions = False
132
    epr = None
133
    url = None
134
    reply_id = None
135
    client_cert = None
136
    tracer = None
137

  
138
    def __init__(self, server = None, logger = None):
139
        self.server = server
140
        self.logger = None
141

  
142
    def soapFail(self, profile, message = None, code = 'server'):
143
        '''Return a SOAP fault to requester'''
144
        if not message:
145
            message = "Unknown server error"
146
        if code == 'server':
147
            profile.initSoapFaultResponse(lasso.SOAP_FAULT_CODE_SERVER, message)
148
        else:
149
            profile.initSoapFaultResponse(lasso.SOAP_FAULT_CODE_CLIENT, message)
150

  
151
    def processRequest(self, message, check_security = False, security_mechanism = None):
152
        profile = self.profile
153
        try:
154
            profile.processRequestMsg(message)
155
            if check_security:
156
                profile.checkSecurityMechanism(security_mechanism)
157
            request_type = profile.getRequestType()
158
            handler=self._dispatch_table.get(request_type, self.soapFail)
159
            handler(profile, True)
160
            profile.validateRequest()
161
            handler(profile, False)
162
        except Exception, e:
163
            self.error('SOAP Request failed:',e)
164
            self.soapFail(profile)
165
        else:
166
            if not profile.response:
167
                self.soapFail(profile)
168
        profile.buildResponseMsg()
169
        return profile.msgBody
170

  
171
    def _doNothing(self, disco, before):
172
        pass
173

  
174

  
175
class DiscoveryClient2(IdWsfClient):
176
    def __init__(self, *args, **kwargs):
177
        super(DiscoveryClient2, self).__init__(*args, **kwargs)
178
        self.profile = lasso.IdWsf2Discovery(self.server)
179

  
180
    def loggerContext(self):
181
        context={}
182
        if self.profile and self.profile.msgUrl:
183
            context['url'] = self.profile.msgUrl
184
        context['interactions'] = self.interactions
185
        if self.reply_id:
186
            context['reply_id'] = self.reply_id
187
        return 'DiscoClient context: %s -- ' % context
188

  
189
    def lookupService(self, *service_types):
190
        try:
191
            disco = self.profile
192
            self._initRequest(disco)
193
            disco.initQuery()
194
            disco.addRequestedService(service_types=service_types)
195
            self._doRequest(disco)
196
            return disco.getEndpointReferences()
197
        except IdWsfInteraction, interaction:
198
            raise
199
        except Exception, e:
200
            self.error(e)
201
            return []
202

  
203
    def queryServices(self, svcmdids=()):
204
        try:
205
            disco = self.profile
206
            self._initRequest(disco)
207
            disco.initMetadataQuery()
208
            disco.svcmdids = tuple(svcmdids)
209
            self._doRequest(disco)
210
            return disco.metadatas
211
        except IdWsfInteraction, interaction:
212
            raise
213
        except Exception, e:
214
            self.error(e)
215
            return []
216

  
217
    def registerService(self, service_types=(), provider_id=None, abstract = None, address = None, security_mechanisms = ()):
218
        try:
219
            disco = self.profile
220
            self._initRequest(disco)
221
            disco.initMetadataRegister()
222
            disco.addSimpleServiceMetadata(service_types=service_types,
223
                    provider_id = provider_id, abstract=abstract,
224
                    address = address,
225
                    security_mechanisms = tuple(security_mechanisms))
226
            self._doRequest(disco)
227
            return disco.metadatas[0].svcMDID
228
        except IdWsfInteraction, interaction:
229
            raise
230
        except Exception, e:
231
            self.error(e)
232
            return None
233

  
234
    def deleteService(self, svcMDIDs):
235
        try:
236
            disco = self.profile
237
            self._initRequest(disco)
238
            disco.initMetadataDelete()
239
            disco.svcmdids = tuple(svcMDIDs)
240
            self._doRequest(disco)
241
            return True
242
        except IdWsfInteraction, interaction:
243
            raise
244
        except lasso.Idwsf2DiscoveryNotFoundError:
245
            self.error('Cannot delete service mdid %s: %s said not found ' % (svcMDIDs, self.profile.msgUrl))
246
            return True
247
        except Exception, e:
248
            raise
249

  
250
    def associate(self, svcMDIDs):
251
        try:
252
            disco = self.profile
253
            self._initRequest(disco)
254
            disco.initMetadataAssociationAdd()
255
            disco.svcmdids = tuple(svcMDIDs)
256
            self._doRequest(disco)
257
            return True
258
        except IdWsfInteraction, interaction:
259
            raise
260
        except Exception, e:
261
            self.error('Cannot associate with services', svcMDIDs, ':', e)
262
            return False
263

  
264
    def dissociate(self, svcMDIDs):
265
        try:
266
            disco = self.profile
267
            self._initRequest(disco)
268
            disco.initMetadataAssociationDelete()
269
            disco.svcmdids = tuple(svcMDIDs)
270
            self._doRequest(disco)
271
            return True
272
        except IdWsfInteraction, interaction:
273
            raise
274
        except Exception, e:
275
            self.error('Could not dissociate for', svcMDIDs, ':', e)
276
            return False
277

  
278
    def queryAssociations(self, svcMDIDs):
279
        try:
280
            disco = self.profile
281
            self._initRequest(disco)
282
            disco.initMetadataAssociationQuery()
283
            disco.svcmdids = tuple(svcMDIDs)
284
            self._doRequest(disco)
285
            return disco.svcmdids
286
        except IdWsfInteraction, interaction:
287
            raise
288
        except Exception, e:
289
            self.error('Could not query associations for', svcMDIDs, ':', e)
290
            return []
291

  
292
class DiscoveryService2(IdWsfService):
293
    def __init__(self, *args, **kwargs):
294
        super(DiscoveryService2, self).__init__(*args, **kwargs)
295
        self._dispatch_table = {
296
            lasso.IDWSF2_DISCOVERY_REQUEST_TYPE_MD_REGISTER: self.handleMdRegister,
297
            lasso.IDWSF2_DISCOVERY_REQUEST_TYPE_MD_QUERY: self.handleMdQuery,
298
            lasso.IDWSF2_DISCOVERY_REQUEST_TYPE_MD_DELETE: self.handleMdDelete,
299
            lasso.IDWSF2_DISCOVERY_REQUEST_TYPE_MD_ASSOCIATION_ADD: self.handleMdAssociationAdd,
300
            lasso.IDWSF2_DISCOVERY_REQUEST_TYPE_MD_ASSOCIATION_DELETE: self.handleMdAssociationDelete,
301
            lasso.IDWSF2_DISCOVERY_REQUEST_TYPE_MD_ASSOCIATION_QUERY: self.handleMdAssociationQuery,
302
            lasso.IDWSF2_DISCOVERY_REQUEST_TYPE_QUERY: self.handleQuery,
303
            }
304
        self.profile = lasso.IdWsf2Discovery(self.server)
305

  
306
    handleMdRegister = IdWsfService._doNothing
307
    handleMdQuery = IdWsfService._doNothing
308
    handleMdDelete = IdWsfService._doNothing
309
    handleMdAssociationAdd = IdWsfService._doNothing
310
    handleMdAssociationDelete = IdWsfService._doNothing
311
    handleMdAssociationQuery = IdWsfService._doNothing
312
    handleQuery = IdWsfService._doNothing
313

  
314
class DSTClient2(IdWsfClient):
315
    def __init__(self, *args, **kwargs):
316
        super(DSTClient2, self).__init__(*args, **kwargs)
317
        self.profile = lasso.IdWsf2DataService(self.server)
318

  
319
    def query(self, queries, flatten=True, namespaces={}):
320
        try:
321
            dst=self.profile
322
            for key, value in namespaces.items():
323
                dst.addNamespace(key, value)
324
            self._initRequest(dst)
325
            dst.initQuery()
326
            for key, query in queries.items():
327
                dst.addQueryItem(query, key)
328
            self._doRequest(dst)
329
            results = {}
330
            for key in queries:
331
                if flatten:
332
                    v=dst.getQueryItemResultContent(key)
333
                else:
334
                    v=dst.getQueryItemResult(key)
335
                results[key]=v
336
            return results
337
        except IdWsfInteraction, interaction:
338
            raise
339
        except Exception, e:
340
            self.error('DST query failed', e)
341
            return {}
342

  
343
class DSTService2(IdWsfService):
344
    def __init__(self, *args, **kwargs):
345
        super(DSTService2, self).__init__(*args, **kwargs)
346
        self._dispatch_table = {
347
            lasso.IDWSF2_DATA_SERVICE_REQUEST_TYPE_QUERY: self.handleQuery,
348
            }
349
        self.profile = lasso.IdWsf2DataService(self.server)
350

  
351
    handleQuery = IdWsfService._doNothing
wcs/qommon/soap.py
1
# w.c.s. - web application for online forms
2
# Copyright (C) 2005-2010  Entr'ouvert
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, see <http://www.gnu.org/licenses/>.
16

  
17
import urllib
18
import httplib
19

  
20
class SOAPException(Exception):
21
    def __init__(self, msg, err = None, url = None, body = None):
22
        """SOAP call failure, this is not related to SOAP Fault, which
23
           are normal SOAP response"""
24
        self.err = err
25
        self.url = url
26
        self.body = body
27
        super(SOAPException, self).__init__(msg)
28

  
29
    def __str__(self):
30
        return '<SOAPException url:%s sub-err:%s>' % (self.url, self.err)
31

  
32

  
33
def soapCall(url, msg, key = None, cert = None):
34
    """Use httplib to make a SOAP call, the content of the SOAP message must
35
       be passed in @msg and the destination in @url.
36
    """
37

  
38
    if url.startswith('http://'):
39
        host, query = urllib.splithost(url[5:])
40
        conn = httplib.HTTPConnection(host)
41
    else:
42
        host, query = urllib.splithost(url[6:])
43
        conn = httplib.HTTPSConnection(host,
44
                key_file = key or cert, cert_file = cert)
45
    try:
46
        conn.request('POST', query, msg, {'Content-Type': 'text/xml'})
47
        response = conn.getresponse()
48
    except Exception, err:
49
        # exception could be raised by request
50
        raise SOAPException("Connection failed",
51
                url = url, err = err, body = msg)
52
    data = response.read()
53
    conn.close()
54
    if response.status not in (200, 204): # 204 ok for federation termination
55
        raise SOAPException("Response status is not OK", url = url,
56
                body = msg)
57
    return data
58
-