Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • DM/dm-docs
  • hammonds/dm-docs
  • hparraga/dm-docs
3 results
Show changes
Showing
with 470 additions and 0 deletions
#!/usr/bin/env python
import cherrypy
from cherrypy import HTTPError
class DmHttpError(HTTPError):
def __init__ (self, httpCode, httpError, dmEx):
HTTPError.__init__(self, httpCode, httpError)
self.dmException = dmEx
def set_response(self):
HTTPError.set_response(self)
cherrypy.response.headers['Dm-Status-Code'] = self.dmException.getErrorCode()
cherrypy.response.headers['Dm-Status-Message'] = self.dmException.getErrorMessage()
cherrypy.response.headers['Dm-Exception-Type'] = self.dmException.getExceptionType()
#!/usr/bin/env python
#
# Internal error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InternalError(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INTERNAL_ERROR, **kwargs)
#!/usr/bin/env python
#
# Invalid argument error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InvalidArgument(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INVALID_ARGUMENT, **kwargs)
#!/usr/bin/env python
#
# Object not found error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class ObjectNotFound(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INVALID_OBJECT_STATE, **kwargs)
#!/usr/bin/env python
#
# Invalid request error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InvalidRequest(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INVALID_REQUEST, **kwargs)
#!/usr/bin/env python
#
# Invalid request error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InvalidRequest(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INVALID_SESSION, **kwargs)
#!/usr/bin/env python
#
# Object already exists error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class ObjectAlreadyExists(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_OBJECT_ALREADY_EXISTS, **kwargs)
#!/usr/bin/env python
#
# Object not found error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class ObjectNotFound(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_OBJECT_NOT_FOUND, **kwargs)
#!/usr/bin/env python
#
# Url error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class UrlError(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_URL_ERROR, **kwargs)
#!/usr/bin/env python
from dmObject import DmObject
class AuthorizationPrincipal(DmObject):
def __init__(self, dict={}, name=None, token=None, userInfo={}):
DmObject.__init__(self, dict)
if name is not None:
self['name'] = name
if token is not None:
self['token'] = token
if userInfo is not None and len(userInfo):
self['userInfo'] = userInfo
def getName(self):
return self.get('name')
def getAuthenticationToken(self):
return self.get('token')
def getToken(self):
return self.get('token')
def setRole(self, role):
self['role'] = role
def getRole(self):
return self.get('role')
def setUserInfo(self, userInfo):
self['userInfo'] = userInfo
def getUserInfo(self):
return self.get('userInfo')
#!/usr/bin/env python
#
# DM Object class.
#
#######################################################################
import UserDict
import UserList
import types
import json
import datetime
from dm.common.exceptions.invalidArgument import InvalidArgument
from dm.common.utility import loggingManager
class DmObject(UserDict.UserDict):
""" Base dm object class. """
ALL_KEYS = '__all__'
DEFAULT_KEYS = '__default__'
DICT_DISPLAY_FORMAT = 'dict'
TEXT_DISPLAY_FORMAT = 'text'
JSON_DISPLAY_FORMAT = 'json'
DEFAULT_KEY_LIST = [ 'id', 'name' ]
def __init__(self, dict={}):
if isinstance(dict, types.DictType):
UserDict.UserDict.__init__(self, dict)
elif isinstance(dict, UserDict.UserDict):
UserDict.UserDict.__init__(self, dict.data)
else:
raise InvalidArgument('DmObject instance must be initialized using dictionary.')
self.logger = None
def getLogger(self):
if not self.logger:
self.logger = loggingManager.getLogger(self._class__.__name__)
return self.logger
@classmethod
def getFromDict(cls, dict):
inst = cls()
for key in dict.keys():
inst[key] = dict[key]
return inst
def getRepKeyList(self, keyList):
if keyList is None:
return self.DEFAULT_KEY_LIST
elif type(keyList) == types.ListType:
if not len(keyList):
return self.DEFAULT_KEY_LIST
else:
return keyList
elif type(keyList) == types.StringType:
if keyList == DmObject.ALL_KEYS:
return self.data.keys()
elif keyList == DmObject.DEFAULT_KEYS:
return self.DEFAULT_KEY_LIST
else:
# Assume keys are separated by comma
return keyList.split(',')
else:
# Unknown key list parameter.
raise InvalidArgument('Key list parameter must be one of: None, string "%s", string "%s", string containing comma-separated keys, or list of strings.' (DmObject.ALL_KEYS, DmObject.DEFAULT_KEYS))
def getDictRep(self, keyList=None):
# Dict representation is dict
dictRep = {}
displayKeyList = self.getRepKeyList(keyList)
for key in displayKeyList:
value = self.get(key)
if isinstance(value, DmObject):
dictRep[key] = value.getDictRep('__all__')
elif type(value) == types.ListType:
itemList = []
for item in value:
if isinstance(item, DmObject):
itemList.append(item.getDictRep('__all__'))
else:
itemList.append(item)
dictRep[key] = itemList
else:
if value is not None:
if isinstance(value, datetime.datetime):
dictRep[key] = str(value)
else:
dictRep[key] = value
return dictRep
def getTextRep(self, keyList=None):
display = ''
displayKeyList = self.getRepKeyList(keyList)
for key in displayKeyList:
value = self.get(key)
if isinstance(value, DmObject):
display = display + '%s={ %s} ' % (key, value.getTextRep())
elif isinstance(value, types.ListType):
display = display + '%s=[ ' % key
for item in value:
if isinstance(item, DmObject):
display = display + '{ %s}, ' % (item)
else:
display = display + ' %s, ' % (item)
display = display + '] '
else:
if value is not None:
display = display + '%s=%s ' % (key, value)
return display
def getJsonRep(self, keyList=None):
dictRep = self.getDictRep(keyList)
return json.dumps(dictRep)
def getFullJsonRep(self):
dictRep = self.getDictRep(DmObject.ALL_KEYS)
return json.dumps(dictRep)
@classmethod
def fromJsonString(cls, jsonString):
return cls.getFromDict(json.loads(jsonString))
def getDisplayString(self, displayKeyList=[], displayFormat=TEXT_DISPLAY_FORMAT):
""" Get display string. """
if displayFormat == DmObject.DICT_DISPLAY_FORMAT:
return self.getDictRep(displayKeyList)
elif displayFormat == DmObject.TEXT_DISPLAY_FORMAT:
return self.getTextRep(displayKeyList)
elif displayFormat == DmObject.JSON_DISPLAY_FORMAT:
return self.getJsonRep(displayKeyList)
raise InvalidArgument('Unrecognized display displayFormat: %s.' (displayFormat))
#######################################################################
# Testing.
if __name__ == '__main__':
x = {'name' : 'XYZ', 'one':1, 'two':2 }
o = DmObject(x)
print 'DM Object: ', o
print 'Type of DM object: ', type(o)
print 'JSON Rep: ', o.getJsonRep()
print 'Type of JSON rep: ', type(o.getJsonRep())
j = '{"name" : "XYZ", "one":1, "two":2 }'
print 'String: ', j
x2 = DmObject.fromJsonString(j)
print 'DM Object 2: ', x2
print 'Type of DM object 2: ', type(x2)
print x2.getDisplayString(displayKeyList='__all__')
#!/usr/bin/env python
#
# Base object manager class.
#
#######################################################################
import threading
from dm.common.utility.loggingManager import LoggingManager
#######################################################################
class DmObjectManager:
""" Base object manager class. """
def __init__(self):
self.logger = LoggingManager.getInstance().getLogger(self.__class__.__name__)
self.lock = threading.RLock()
def getLogger(self):
return self.logger
def acquireLock(self):
self.lock.acquire()
def releaseLock(self):
self.lock.release()
#!/usr/bin/env python
import time
from dmObject import DmObject
class Experiment(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'dataDirectory', 'startDate', 'endDate', 'daqStartTime', 'daqEndTime' ]
def __init__(self, dict={}):
DmObject.__init__(self, dict)
####################################################################
# Testing
if __name__ == '__main__':
pass
#!/usr/bin/env python
import time
from dmObject import DmObject
class ExperimentType(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description`', 'rootDataPath' ]
def __init__(self, dict={}):
DmObject.__init__(self, dict)
####################################################################
# Testing
if __name__ == '__main__':
pass
#!/usr/bin/env python
import time
from dmObject import DmObject
class ObservedFile(DmObject):
DEFAULT_KEY_LIST = [ 'path', 'lastUpdatedTimestamp' ]
def __init__(self, dict={}, filePath=None, daqPath=None, experiment=None):
DmObject.__init__(self, dict)
if filePath:
self['filePath'] = filePath
if daqPath:
self['daqPath'] = daqPath
if experiment:
self['experiment'] = experiment
def setLastUpdatedTimestampToNow(self):
self['lastUpdateTimestamp'] = time.time()
def getLastUpdatedTimestamp(self):
self.get('lastUpdateTimestamp')
def getFilePath(self):
return self.get('filePath')
def getDaqPath(self):
return self.get('daqPath')
def getExperiment(self):
return self.get('experiment')
####################################################################
# Testing
if __name__ == '__main__':
of = ObservedFile(path='tmp/xyz')
print of
of.setLastUpdatedTimestampToNow()
print of
#!/usr/bin/env python
from dmObject import DmObject
class RoleType(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'name', 'description' ]
def __init__(self, dict):
DmObject.__init__(self, dict)
#!/usr/bin/env python
from dmObject import DmObject
class UserInfo(DmObject):
DEFAULT_KEY_LIST = [ 'id', 'username', 'firstName', 'lastName', 'middleName', 'email', 'description' ]
def __init__(self, dict):
DmObject.__init__(self, dict)
#!/usr/bin/env python
from dmObject import DmObject
class UserSystemRole(DmObject):
DEFAULT_KEY_LIST = [ 'user_id', 'role_type_id' ]
def __init__(self, dict):
DmObject.__init__(self, dict)