Пример #1
0
def checkLoggingResult(result):
    assert isinstance(result, iApiTransportResponse)
    response = result.response()
    assert isinstance(response, iLoggingResult)
    l = LogManager()
    if l.isOn() == True:
        assert response.isOn() == eLoggingState.ON
    else:
        assert response.isOn() == eLoggingState.OFF
    assert response.location() == l.FILENAME
Пример #2
0
 def __init__(self, q, parent):
     super(ApiAsyncWorker, self).__init__()
     self._q = q
     self._parent = parent
     self._name = "ApiAsyncWorker_%(C)s" % {"C":ApiAsyncWorker.ID.next()}
     self._logger = LogManager().getLogger(self._name)
     self.setDaemon(True)
     self.setName(self._name)
     self._cancel = False
     self._runLock = Semaphore(0)
Пример #3
0
class ConfigurationManager(Singleton):
    _instance = None
    _instanceLock = RLock()

    def _setup(self, cwd=None):
        if not cwd: cwd = os.getcwd()
        existingCwd = os.getcwd()

        self.logger = LogManager().getLogger(self.__class__.__name__)
        self.logger.debug('Current Directory: %s' % os.getcwd())

        try:
            xml = None
            os.chdir(cwd)
            self.xmls = {}
            self.logger.info("Loading configuration from: %s" % os.getcwd())

            for xml in glob("config/*.xml"):
                name = xml.split("/")[-1].split(".")[0]
                xsd = "config/validation/%s.xsd" % name
                if not os.path.exists(xsd): continue
                self.loadConfiguration(xml, xsd)
        except Exception, e:
            self.logger.info("Failed to load %s" % xml)
            self.__raiseError(str(e))
            raise
        finally:
Пример #4
0
class ApiAsyncWorker(threading.Thread):
    ID = itertools.count(1)
    @staticmethod
    def startAll(workers=[]):
        for worker in workers:
            worker.start()
        for worker in workers:
            worker.waitUntilRunning()
    @staticmethod
    def create(q, parent, start=False):
        worker = ApiAsyncWorker(q, parent)
        if start:
            ApiAsyncWorker.startAll([worker])
        return worker
    def __init__(self, q, parent):
        super(ApiAsyncWorker, self).__init__()
        self._q = q
        self._parent = parent
        self._name = "ApiAsyncWorker_%(C)s" % {"C":ApiAsyncWorker.ID.next()}
        self._logger = LogManager().getLogger(self._name)
        self.setDaemon(True)
        self.setName(self._name)
        self._cancel = False
        self._runLock = Semaphore(0)
    def stop(self):
        self._cancel = True
    def waitUntilRunning(self, timeout=None):
        # Wait until we become running:
        return self._runLock.acquire(block=True, timeout=timeout)
    def run(self):
        self._logger.debug("Thread running...")
        self._runLock.release()
        #    Now do the work:
        try:
            self._work()
        except EOFError, _e:
            self._logger.warn("EOF in thread...")
        except Exception, _e:
            self._logger.exception("Unhandled error in thread:")
Пример #5
0
    def __init__(self, xml, xsd):
        self.logger = LogManager().getLogger(self.__class__.__name__)

        self.cwd = os.path.abspath('.')
        self.xmlFile = os.path.abspath(xml)
        self.xsdFile = os.path.abspath(xsd)

        if not os.path.exists(self.xmlFile) or not os.path.exists(self.xsdFile):
            raise InvalidConfigurationFiles("Given Files: %s - %s"
                % (self.xmlFile, self.xsdFile))

        self.logger.debug("Attempting to find XML hash")
        successfulLoad, xmlHash, xsdHash = self.__loadFromCache(xml, xsd)

        if not successfulLoad:  # Hashes are incorrect
            self.logger.debug("Validating XML against XSD")
            self.__loadAndValidate(xml, xsd, xmlHash, xsdHash)
Пример #6
0
class Objectify(object):
    """
    The objectify class allows the application
    to setup and use Objectify by using the
    constructor, then accessing Objectify
    by using the .instance attribute
    @param xml: XML file path
    @param xsd: XSD file path 
    @raise InvalidConfigurationXML: Non existent XML/XSD. Invalid formatted files 
    """

    KWARGS = {
      "xmlIfClass"      : pyxsval.XMLIF_ELEMENTTREE,
      "warningProc"     : pyxsval.PRINT_WARNINGS,
      "errorLimit"      : 200,
      "verbose"         : 0,
      "useCaching"      : 0,
      "processXInclude" : 0
    }

    def __init__(self, xml, xsd):
        self.logger = LogManager().getLogger(self.__class__.__name__)

        self.cwd = os.path.abspath('.')
        self.xmlFile = os.path.abspath(xml)
        self.xsdFile = os.path.abspath(xsd)

        if not os.path.exists(self.xmlFile) or not os.path.exists(self.xsdFile):
            raise InvalidConfigurationFiles("Given Files: %s - %s"
                % (self.xmlFile, self.xsdFile))

        self.logger.debug("Attempting to find XML hash")
        successfulLoad, xmlHash, xsdHash = self.__loadFromCache(xml, xsd)

        if not successfulLoad:  # Hashes are incorrect
            self.logger.debug("Validating XML against XSD")
            self.__loadAndValidate(xml, xsd, xmlHash, xsdHash)

    def __loadFromCache(self, xml, xsd):
        hashPath = self.__getXmlHashFile(xml)
        xmlHash = self.__hashFile(xml)
        xsdHash = self.__hashFile(xsd)

        if not os.path.exists(hashPath):
            self.logger.debug("Hash doesn't exist: %s" % hashPath)
            return (False, xmlHash, xsdHash)

        hashFile = open(hashPath, 'r')
        cachedXMLHash = hashFile.readline().strip()
        cachedXSDHash = hashFile.readline().strip()
        hashFile.close()

        if cachedXMLHash != xmlHash or cachedXSDHash != xsdHash:
            self.logger.info("Incorrect Hashes: %s - %s, %s - %s" % 
                (cachedXMLHash, xmlHash, cachedXSDHash, xsdHash))
            return (False, xmlHash, xsdHash)

        self.configuration = make_instance(xml)
        return (True, xmlHash, xsdHash)

    def __hashFile(self, path):
        xmlFile = open(path, 'rb')
        shaHash = hashlib.sha1()

        while True:
            data = xmlFile.read(4096)
            if not data: break
            shaHash.update(hashlib.sha1(data).hexdigest())
        xmlFile.close()

        return shaHash.hexdigest()

    def __loadAndValidate(self, xml, xsd, xmlHash, xsdHash):
        try:  # Validate the config file
            pyxsval.parseAndValidate(\
                 inputFile=xml,
                 xsdFile=xsd,
                 **Objectify.KWARGS)
        except Exception:
            raise InvalidConfigurationXML(format_exc())
        self.logger.debug("Validated XML against XSD")

        # gnosis.xml.objectify._XO_node = Node.Node
        # gnosis.xml.objectify._XO_interface = Interface.Interface
        self.configuration = make_instance(xml)
        hashPath = self.__getXmlHashFile(xml)

        try:
            hashFile = open(hashPath, 'w')
            hashFile.write("%s\n%s" % (xmlHash, xsdHash))
            hashFile.close()
        except IOError, e:
            self.logger.error(e)
Пример #7
0
 def tearDown(self):
     LogManager.destroySingleton()