source: TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/classfactory.py @ 5372

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/classfactory.py@5372
Revision 5372, 4.7 KB checked in by pjkersha, 11 years ago (diff)

Added code for validation of OpenID Provider by Relying Party using M2Crypto.m2urllib2 for SSL peer authN

Line 
1"""
2Generic parsers to use when reading in configuration data
3- methods available to deal with both XML and INI (flat text key/val) formats
4"""
5__author__ = "C Byrom - Tessella"
6__date__ = "28/08/08"
7__copyright__ = "(C) 2009 Science and Technology Facilities Council"
8__license__ = "BSD - see LICENSE file in top-level directory"
9__contact__ = "Philip.Kershaw@stfc.ac.uk"
10__revision__ = '$Id$'
11
12import logging, os, sys
13log = logging.getLogger(__name__)
14
15class ClassFactoryError(Exception):
16    """Exception handling for NDG classfactory module."""
17    def __init__(self, msg):
18        log.error(msg)
19        Exception.__init__(self, msg)
20
21def importClass(moduleName, className=None, objectType=None):
22    '''Import a class from a string module name and class name.
23   
24    @param moduleName: Name of module containing the class
25    @type moduleName: str
26    @param className: Name of the class to import.  If none is given, the
27    class name will be assumed to be the last component of modulePath
28    @type className: str
29    @rtype: class object
30    @return: imported class'''
31   
32    if className is None:
33        _moduleName, className = moduleName.rsplit('.', 1)
34    else:
35        _moduleName = moduleName
36   
37    log.debug("Importing class %s ..." % className) 
38     
39    module = __import__(_moduleName)
40    components = _moduleName.split('.')
41    for component in components[1:]:
42        module = getattr(module, component)
43
44    importedClass = getattr(module, className)
45
46    # Check class inherits from a base class
47    if objectType and not issubclass(importedClass, objectType):
48        raise TypeError("Specified class %s must be derived from %s; got %s" %
49                        (className, objectType, importedClass))
50   
51    log.info('Imported "%s" class from module, "%s"', className, moduleName)
52    return importedClass
53   
54
55def instantiateClass(moduleName, className, moduleFilePath=None, 
56                     objectType=None, classArgs=(), classProperties={}):
57    '''
58    Create and return an instance of the specified class
59    @param moduleName: Name of module containing the class
60    @type moduleName: str
61    @param className: Name of the class to instantiate.  May be None in
62    which case, the class name is parsed from the moduleName last element
63    @type className: str
64    @keyword moduleFilePath: Path to the module - if unset, assume module on
65    system path already
66    @type moduleFilePath: str
67    @keyword classProperties: dict of properties to use when instantiating the
68    class
69    @type classProperties: dict
70    @keyword objectType: expected type for the object to instantiate - to
71    enforce use of specific interfaces
72    @type objectType: object
73    @return: object - instance of the class specified
74    '''
75
76   
77    # ensure that classproperties is a dict - NB, it may be passed in as a null
78    # value which can override the default val
79    if not classProperties:
80        classProperties = {}
81
82    # variable to store original state of the system path
83    sysPathBak = None
84    try:
85        try:
86            # Module file path may be None if the new module to be loaded
87            # can be found in the existing system path           
88            if moduleFilePath:
89                if not os.path.exists(moduleFilePath):
90                    raise IOError("Module file path '%s' doesn't exist" % 
91                                  moduleFilePath)
92                         
93                # Temporarily extend system path ready for import
94                sysPathBak = sys.path
95                         
96                sys.path.append(moduleFilePath)
97
98           
99            # Import module name specified in properties file
100            importedClass = importClass(moduleName, 
101                                        className=className,
102                                        objectType=objectType)
103        finally:
104            # revert back to original sys path, if necessary
105            # NB, python requires the use of a try/finally OR a try/except
106            # block - not both combined
107            if sysPathBak:
108                sys.path = sysPathBak
109                           
110    except Exception, e:
111        log.error('%s module import raised %s type exception: %s' % 
112                  (moduleName, e.__class__, e))
113        raise 
114
115    # Instantiate class
116    log.debug("Instantiating class '%s'" % importedClass.__name__)
117    try:
118        if classArgs:
119            object = importedClass(*classArgs, **classProperties)
120        else:
121            object = importedClass(**classProperties)
122           
123        return object
124
125    except Exception, e:
126        log.error("Instantiating class, %s: %s" % (importedClass.__name__, e))
127        raise
128           
129                 
Note: See TracBrowser for help on using the repository browser.