source: TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/ClassFactory.py @ 4158

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg-security/TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/ClassFactory.py@4158
Revision 4158, 3.7 KB checked in by cbyrom, 13 years ago (diff)

Create new utility module, ClassFactory? - to allow generic instantiation
of classes dynamically.

Implement use of this in the AttAuth? and SessionMgr? services + adjust
the config files for these accordingly + abstract use of MyProxy? in
SessionMgr? to generic authNService - and create packages with real
and test authN services. Adjust the SessionMgr? tests to use the
test authN service.

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) 2008 STFC & NERC"
8__license__ = \
9"""This software may be distributed under the terms of the Q Public
10License, version 1.0 or later."""
11__contact__ = "P.J.Kershaw@rl.ac.uk"
12__revision__ = '$Id$'
13
14import logging, os, sys
15log = logging.getLogger(__name__)
16
17class ClassFactoryError(Exception):
18    """Exception handling for NDG ClassFactory module."""
19    def __init__(self, msg):
20        log.error(msg)
21        Exception.__init__(self, msg)
22
23
24def instantiateClass(moduleName, className, moduleFilePath=None, \
25                     objectType=None, classProperties={}):
26    '''
27    Create and return an instance of the specified class
28    @param moduleName: Name of module containing the class
29    @type moduleName: str
30    @param className: Name of the class to instantiate
31    @type className: str
32    @keyword moduleFilePath: Path to the module - if unset, assume module on system path already
33    @type moduleFilePath: str
34    @keyword classProperties: dict of properties to use when instantiating the class
35    @type classProperties: dict
36    @keyword objectType: expected type for the object to instantiate - to enforce use of
37    specific interfaces
38    @type objectType: object
39    @return: object - instance of the class specified
40    '''
41
42    log.debug("Instantiating class, %s" %className)
43   
44    # ensure that classproperties is a dict - NB, it may be passed in as a null value
45    # which can override the default val
46    if not classProperties:
47        classProperties = {}
48
49    # variable to store original state of the system path
50    sysPathBak = None
51    try:
52        try:
53            # Module file path may be None if the new module to be loaded
54            # can be found in the existing system path           
55            if moduleFilePath:
56                if not os.path.exists(moduleFilePath):
57                    raise IOError, "Module file path '%s' doesn't exist" % \
58                          moduleFilePath
59                         
60                # Temporarily extend system path ready for import
61                sysPathBak = sys.path
62                         
63                sys.path.append(moduleFilePath)
64           
65            # Import module name specified in properties file
66            importModule = __import__(moduleName, globals(), \
67                                      locals(), [className])
68
69            importClass = eval('importModule.' + className)
70        finally:
71            # revert back to original sys path, if necessary
72            # NB, python requires the use of a try/finally OR a try/except block - not both combined
73            if sysPathBak:
74                sys.path = sysPathBak
75                           
76    except Exception, e:
77        raise ClassFactoryError,'Error importing %s module: %s' \
78            %(moduleName, str(e))
79
80    # Check class inherits from AAproxy abstract base class
81    if objectType and not issubclass(importClass, objectType):
82        raise ClassFactoryError, \
83            "Specified class %s must be derived from %s" \
84            %(className, objectType)
85
86    # Instantiate class
87    try:
88        print "Calling %s with dict:" %className
89        print classProperties
90        object=importClass(**classProperties)
91        log.info(\
92                 'Instantiated "%s" class from module, "%s"' \
93                 %(className, moduleName))
94        return object
95       
96    except Exception, e:
97        print e
98        raise ClassFactoryError, \
99            "Error instantiating class, %s: " %(importClass.__name__, str(e))
100           
101                 
Note: See TracBrowser for help on using the repository browser.