class ZTest(IZTest): def __init__(self): self.steps = [] self.listeners = ZListenerSet() self.cancelled = False # end __init__() def getSteps(self): return self.steps # end getSteps() def addStep(self, step): self.steps.append(step) # end addStep() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def cancel(self): self.cancelled = True # end cancel() def run(self): for listener in self.listeners: listener.onTestStart(self) for step in self.steps: if self.cancelled: return try: step.setCurrent() for listener in self.listeners: listener.onStepStart(self, step) # Now actually run the step self._runStep(step) step.setPassed() for listener in self.listeners: listener.onStepPass(self, step) except Exception, e: ze = ZException(unicode(e), rootCause=e) step.setFailed(ze) for listener in self.listeners: listener.onStepFail(self, step, ze) break for listener in self.listeners: listener.onTestComplete(self)
class ZAbstractProfileImporter(IZRunnableProgress): def __init__(self, pathToSourceProfile, pathToRavenProfile, systemProfile): self.stopped = True self.pathToSourceProfile = pathToSourceProfile self.pathToRavenProfile = pathToRavenProfile self.systemProfile = systemProfile self.listeners = ZListenerSet() # end __init__() def addListener(self, listener): if not isinstance(listener, IZRunnableProgressListener): raise ZBlogAppException(_extstr(u"importer.IncorrectListenerType")) #$NON-NLS-1$ self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def _getRavenAccountDir(self): return os.path.join(self.pathToRavenProfile, u"accounts") #$NON-NLS-1$ # end _getRavenAccountDir() def _notifyWorkDone(self, workunits, progressText): for listener in self.listeners: listener.onWorkDone(workunits, progressText) # end _notifyWorkDone def _notifyCancel(self): for listener in self.listeners: listener.onCancel() # end _notifyCancel def stop(self): self.stopped = True # end stop() def run(self): self.stopped = False if self._getWorkAmount() < 1: return for listener in self.listeners: listener.onStarted(self._getWorkAmount()) # do the import self._runImport() # notify done for listener in self.listeners: listener.onComplete() # end run() def _runImport(self): raise ZAbstractMethodCalledException(self.__class__, u"_runImport") #$NON-NLS-1$ # end _runImport() def _getWorkAmount(self): raise ZAbstractMethodCalledException(self.__class__, u"_getWorkAmount") #$NON-NLS-1$
class ZTest(IZTest): def __init__(self): self.steps = [] self.listeners = ZListenerSet() self.cancelled = False # end __init__() def getSteps(self): return self.steps # end getSteps() def addStep(self, step): self.steps.append(step) # end addStep() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def cancel(self): self.cancelled = True # end cancel() def run(self): for listener in self.listeners: listener.onTestStart(self) for step in self.steps: if self.cancelled: return try: step.setCurrent() for listener in self.listeners: listener.onStepStart(self, step) # Now actually run the step self._runStep(step) step.setPassed() for listener in self.listeners: listener.onStepPass(self, step) except Exception, e: ze = ZException(unicode(e), rootCause = e) step.setFailed(ze) for listener in self.listeners: listener.onStepFail(self, step, ze) break for listener in self.listeners: listener.onTestComplete(self)
class ZSystemProperties: u"""Use this class to get and set System Properties.""" #$NON-NLS-1$ def __init__(self, sysPropsFileName): # create a lock for thread synchronization self.lock = ZMutex(u"ZSystemProperties") #$NON-NLS-1$ self.listeners = ZListenerSet() self.sysPropsFileName = sysPropsFileName self.sysPropsDoc = ZDom() self.reloadProperties() # end __init__() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener def _fireEvent(self, key, value): for listener in self.listeners: listener.onSystemPropertyChange(key, value) # end _fireEvent() def reloadProperties(self): self.lock.acquire() try: # Open and parse the system properties file self.sysPropsDoc.load(self.sysPropsFileName) finally: self.lock.release() # end reloadProperties() # Public method - call this to save the system properties. def save(self): u"Public method - call this to save the system properties." #$NON-NLS-1$ self.lock.acquire() self.saveProperties() self.lock.release() self._fireEvent(None, None) # end save() # Note that locking is required prior to calling saveProperties() def saveProperties(self): try: tempSysPropsFileName = self.sysPropsFileName + u".t" #$NON-NLS-1$ self.sysPropsDoc.save(tempSysPropsFileName, True) deleteFile(self.sysPropsFileName) renameFile(tempSysPropsFileName, self.sysPropsFileName) except Exception, e: raise ZException(_extstr(u"sysprops.ErrorSavingPropsFile") % self.sysPropsFileName, e) #$NON-NLS-1$
class ZAccountStore(IZAccountStore): def __init__(self): self.logger = None self.listeners = ZListenerSet() # end __init__() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService( IZAppServiceIDs.LOGGER_SERVICE_ID) self.applicationModel = applicationModel self.accounts = self._loadAccounts() self.logger.debug(u"Account Store started [%d accounts loaded]" % len(self.accounts)) #$NON-NLS-1$ # end start() def stop(self): pass # end stop() # Adds a new account to the store. def addAccount(self, account): # Generate a new id for this account accountId = generate() # Determine the account's directory userProfile = self.applicationModel.getUserProfile() accountsDirPath = userProfile.getDirectory(u"accounts") #$NON-NLS-1$ accountDirPath = os.path.join(accountsDirPath, accountId) os.makedirs(accountDirPath) account.setId(accountId) account.setDirectoryPath(accountDirPath) # auto assign media stores try: accUtil = ZAccountUtil() accountList = [account] blogList = accUtil.getBlogsWithOutMediaStore(accountList) for blog in blogList: accUtil.autoAssignMediaStoreToBlog(blog) except: pass self.accounts.append(account) self._saveAccount(account) self._fireAccountAddedEvent(account) # end addAccount() # Returns True if an account with the given name exists. def hasAccount(self, accountName): if not accountName: return True accountName = accountName.strip() # local folder name is reserved. if accountName.lower() == u"unpublished": #$NON-NLS-1$ return True return self.getAccountByName(accountName) is not None # end hasAccount() # Removes a single account by name. def removeAccountByName(self, accountName): account = self.getAccountByName(accountName) self.removeAccount(account) # end removeAccountByName() # Removes a single account by id. def removeAccountById(self, accountId): account = self.getAccountById(accountId) self.removeAccount(account) # end removeAccountById() # Removes a single account. def removeAccount(self, account): if account is None: return self.accounts.remove(account) self._deleteAccount(account) self._fireAccountDeletedEvent(account) # end removeAccount() # Gets a single account by name. def getAccountByName(self, accountName): if accountName and accountName.strip(): accountName = accountName.strip().lower() for account in self.accounts: if account.getName().strip().lower() == accountName: return account return None # end getAccount() # Gets a single account by id. def getAccountById(self, accountId): for account in self.accounts: if account.getId() == accountId: return account return None # end getAccountById() # Returns a list of all acounts in the store. def getAccounts(self): return self.accounts # end getAccounts() # Called to save any changes to the account to disk. def saveAccount(self, account): self._saveAccount(account) self._fireAccountChangedEvent(account) # end saveAccount() def _saveAccount(self, account): saveAccount(account) # end _saveAccount() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def _loadAccounts(self): userProfile = self.applicationModel.getUserProfile() accountsDirName = userProfile.getDirectory(u"accounts") #$NON-NLS-1$ accountDirs = getDirectoryListing(accountsDirName, accountDirectoryFilter) return map(loadAccount, accountDirs) # end _loadAccounts() def _deleteAccount(self, account): accountDir = account.getDirectoryPath() fileutil.deleteDirectory(accountDir, True) # end _deleteAccount() def _fireAccountAddedEvent(self, account): for listener in self.listeners: try: listener.onAccountAdded(account) except Exception, e: self.logger.exception(e)
class ZAccountStore(IZAccountStore): def __init__(self): self.logger = None self.listeners = ZListenerSet() # end __init__() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService(IZAppServiceIDs.LOGGER_SERVICE_ID) self.applicationModel = applicationModel self.accounts = self._loadAccounts() self.logger.debug(u"Account Store started [%d accounts loaded]" % len(self.accounts)) # $NON-NLS-1$ # end start() def stop(self): pass # end stop() # Adds a new account to the store. def addAccount(self, account): # Generate a new id for this account accountId = generate() # Determine the account's directory userProfile = self.applicationModel.getUserProfile() accountsDirPath = userProfile.getDirectory(u"accounts") # $NON-NLS-1$ accountDirPath = os.path.join(accountsDirPath, accountId) os.makedirs(accountDirPath) account.setId(accountId) account.setDirectoryPath(accountDirPath) # auto assign media stores try: accUtil = ZAccountUtil() accountList = [account] blogList = accUtil.getBlogsWithOutMediaStore(accountList) for blog in blogList: accUtil.autoAssignMediaStoreToBlog(blog) except: pass self.accounts.append(account) self._saveAccount(account) self._fireAccountAddedEvent(account) # end addAccount() # Returns True if an account with the given name exists. def hasAccount(self, accountName): if not accountName: return True accountName = accountName.strip() # local folder name is reserved. if accountName.lower() == u"unpublished": # $NON-NLS-1$ return True return self.getAccountByName(accountName) is not None # end hasAccount() # Removes a single account by name. def removeAccountByName(self, accountName): account = self.getAccountByName(accountName) self.removeAccount(account) # end removeAccountByName() # Removes a single account by id. def removeAccountById(self, accountId): account = self.getAccountById(accountId) self.removeAccount(account) # end removeAccountById() # Removes a single account. def removeAccount(self, account): if account is None: return self.accounts.remove(account) self._deleteAccount(account) self._fireAccountDeletedEvent(account) # end removeAccount() # Gets a single account by name. def getAccountByName(self, accountName): if accountName and accountName.strip(): accountName = accountName.strip().lower() for account in self.accounts: if account.getName().strip().lower() == accountName: return account return None # end getAccount() # Gets a single account by id. def getAccountById(self, accountId): for account in self.accounts: if account.getId() == accountId: return account return None # end getAccountById() # Returns a list of all acounts in the store. def getAccounts(self): return self.accounts # end getAccounts() # Called to save any changes to the account to disk. def saveAccount(self, account): self._saveAccount(account) self._fireAccountChangedEvent(account) # end saveAccount() def _saveAccount(self, account): saveAccount(account) # end _saveAccount() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def _loadAccounts(self): userProfile = self.applicationModel.getUserProfile() accountsDirName = userProfile.getDirectory(u"accounts") # $NON-NLS-1$ accountDirs = getDirectoryListing(accountsDirName, accountDirectoryFilter) return map(loadAccount, accountDirs) # end _loadAccounts() def _deleteAccount(self, account): accountDir = account.getDirectoryPath() fileutil.deleteDirectory(accountDir, True) # end _deleteAccount() def _fireAccountAddedEvent(self, account): for listener in self.listeners: try: listener.onAccountAdded(account) except Exception, e: self.logger.exception(e)
class ZTemplateService(IZTemplateService): def __init__(self): self.templateDir = None self.templates = None self.listeners = ZListenerSet() # end __init__() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService(IZAppServiceIDs.LOGGER_SERVICE_ID) self.applicationModel = applicationModel userProfile = self.applicationModel.getUserProfile() self.templateDir = userProfile.getDirectory(u"templates") #$NON-NLS-1$ self.templates = self._loadTemplates() self.logger.debug(u"Template Service started [%d templates loaded]" % len(self.templates)) #$NON-NLS-1$ # end start() def stop(self): self.templateDir = None self.templates = None # end stop() def getTemplates(self): return self.templates # end getTemplates() def createTemplate(self): guid = generate() templateDir = self._getDirForNewTemplate(guid) template = ZTemplate(templateDir, guid) template.setCreationTime(ZSchemaDateTime()) template.setLastModifiedTime(ZSchemaDateTime()) return template # end createTemplate() def getTemplate(self, templateId): for template in self.templates: if template.getId() == templateId: return template return None # end getTemplate() def getTemplateByName(self, templateName): for template in self.templates: if template.getName() == templateName: return template return None # end getTemplateByName() def deleteTemplate(self, templateId): template = self.getTemplate(templateId) if template is not None: self.templates.remove(template) deleteDirectory(template.getTemplateDirectory(), True) self._fireDeletedTemplateEvent(template) return True return False # end deleteTemplate() def saveTemplate(self, template): if not (template in self.templates): self.templates.append(template) self._fireNewTemplateEvent(template) else: self._fireModifiedTemplateEvent(template) saveTemplate(template) # end saveTemplate() def _getDirForNewTemplate(self, guid): path = os.path.join(self.templateDir, guid) return path # end _getDirForNewTemplate() def _loadTemplates(self): templateDirs = getDirectoryListing(self.templateDir, templateDirectoryFilter) templates = [] for template in map(self._loadTemplate, templateDirs): if template is not None: templates.append(template) return templates # end _loadTemplates() def _loadTemplate(self, templateDir): try: return loadTemplate(templateDir) except Exception, e: self.logger.exception(e) return None
class ZSpellChecker(IZSpellChecker): def __init__(self, directoryPath, dictionaryLang, provider, personalWordList = None, autoCorrections = None): self.directoryPath = directoryPath self.listeners = ZListenerSet() self.builtInDictionary = [] self.dictionaryLang = dictionaryLang # An IZSpellCheckDictionaryLanguage self.provider = provider # An IZSpellCheckProvider self.personalWordList = personalWordList # A List of strings self.autoCorrections = autoCorrections # A Map of string -> string if self.personalWordList is None: self.personalWordList = [] if self.autoCorrections is None: self.autoCorrections = {} # end __init__() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def setBuiltInDictionary(self, builtInDictionary): self.builtInDictionary = builtInDictionary # end setBuiltInDictionary() def check(self, word): lword = string.lower(word) # Check the built-in dictionary if lword in self.builtInDictionary: return True # Check the personal dictionary if lword in self.personalWordList: return True # Use the provider return self.provider.check(word) # end check() def suggest(self, word): return self.provider.suggest(word) # end suggest() def autoCorrect(self, word): lword = string.lower(word) if lword in self.autoCorrections: newWord = self.autoCorrections[lword] if self._isCapitalized(word): newWord = string.capitalize(newWord) return newWord return None # end autoCorrect() def destroy(self): self.provider.destroy() # end destroy() def addAutoCorrection(self, word, replacement): self.autoCorrections[string.lower(word)] = replacement self._save() for listener in self.listeners: listener.onAutoCorrectionAdded(word, replacement) # end addAutoCorrection() def removeAutoCorrection(self, word): lword = string.lower(word) if lword in self.autoCorrections: del self.autoCorrections[lword] self._save() for listener in self.listeners: listener.onAutoCorrectionRemoved(word) # end removeAutoCorrection() def getAutoCorrections(self): return self.autoCorrections # end getAutoCorrections() def getAutoCorrection(self, word): lword = string.lower(word) if lword in self.autoCorrections: return self.autoCorrections[lword] return None # end getAutoCorrection() def clearAutoCorrections(self): self.autoCorrections = {} self._save() for listener in self.listeners: listener.onAutoCorrectionsCleared() # end clearAutoCorrections() def addWord(self, word): lword = string.lower(word) if not lword in self.personalWordList: self.personalWordList.append(lword) self._save() for listener in self.listeners: listener.onPersonalDictionaryWordAdded(word) # end addWord() def addWords(self, words): for word in words: lword = string.lower(word) if not lword in self.personalWordList: self.personalWordList.append(lword) for listener in self.listeners: listener.onPersonalDictionaryWordAdded(word) self._save() # end addWords() def removeWord(self, word): lword = string.lower(word) if not lword in self.personalWordList: del self.personalWordList[lword] self._save() for listener in self.listeners: listener.onPersonalDictionaryWordRemoved(word) # end removeWord() def getWords(self): return self.personalWordList # end getWords() def clearPersonalDictionary(self): self.personalWordList = [] self._save() for listener in self.listeners: listener.onPersonalDictionaryCleared() # end clearPersonalDictionary() def _save(self): serializer = ZSpellCheckerSerializer() serializer.serialize(self, self.directoryPath) # end _save() def _isCapitalized(self, word): return word == string.capitalize(word)
class ZTemplateService(IZTemplateService): def __init__(self): self.templateDir = None self.templates = None self.listeners = ZListenerSet() # end __init__() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService( IZAppServiceIDs.LOGGER_SERVICE_ID) self.applicationModel = applicationModel userProfile = self.applicationModel.getUserProfile() self.templateDir = userProfile.getDirectory(u"templates") #$NON-NLS-1$ self.templates = self._loadTemplates() self.logger.debug(u"Template Service started [%d templates loaded]" % len(self.templates)) #$NON-NLS-1$ # end start() def stop(self): self.templateDir = None self.templates = None # end stop() def getTemplates(self): return self.templates # end getTemplates() def createTemplate(self): guid = generate() templateDir = self._getDirForNewTemplate(guid) template = ZTemplate(templateDir, guid) template.setCreationTime(ZSchemaDateTime()) template.setLastModifiedTime(ZSchemaDateTime()) return template # end createTemplate() def getTemplate(self, templateId): for template in self.templates: if template.getId() == templateId: return template return None # end getTemplate() def getTemplateByName(self, templateName): for template in self.templates: if template.getName() == templateName: return template return None # end getTemplateByName() def deleteTemplate(self, templateId): template = self.getTemplate(templateId) if template is not None: self.templates.remove(template) deleteDirectory(template.getTemplateDirectory(), True) self._fireDeletedTemplateEvent(template) return True return False # end deleteTemplate() def saveTemplate(self, template): if not (template in self.templates): self.templates.append(template) self._fireNewTemplateEvent(template) else: self._fireModifiedTemplateEvent(template) saveTemplate(template) # end saveTemplate() def _getDirForNewTemplate(self, guid): path = os.path.join(self.templateDir, guid) return path # end _getDirForNewTemplate() def _loadTemplates(self): templateDirs = getDirectoryListing(self.templateDir, templateDirectoryFilter) templates = [] for template in map(self._loadTemplate, templateDirs): if template is not None: templates.append(template) return templates # end _loadTemplates() def _loadTemplate(self, templateDir): try: return loadTemplate(templateDir) except Exception, e: self.logger.exception(e) return None
class ZBackgroundTaskService(IZBackgroundTaskService, IZBackgroundTaskListener): def __init__(self): self.logger = None self.tasksDirectory = None self.tasks = [] self.listeners = ZListenerSet() # end __init__() def _getTasksDirectory(self, applicationModel): return applicationModel.getUserProfile().getDirectory( u"bgtasks") #$NON-NLS-1$ # end _getTasksDirectory() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService( IZAppServiceIDs.LOGGER_SERVICE_ID) self.tasksDirectory = self._getTasksDirectory(applicationModel) self.tasks = self._loadTasks() self.logger.debug( u"Background Task Service started [%d tasks loaded]." % len(self.tasks)) #$NON-NLS-1$ # end start() def stop(self): # First, stop all tasks. for task in self.tasks: if task.isRunning(): task.stop() self.tasks = [] # end stop() def getTasks(self): return self.tasks # end getTasks() def getTask(self, taskId): for task in self.tasks: if task.getId() == taskId: return task return None # end getTask() def addTask(self, task): task.setId(generate()) taskLogFilename = os.path.join(self.tasksDirectory, task.getId() + u".task.log") #$NON-NLS-1$ task.setLogLocation(taskLogFilename) self.tasks.append(task) self.listeners.doCallback(u"onTaskAdded", [task]) #$NON-NLS-1$ self._resumeTask(task) # Wait until the num work units has been set by the task (but only # wait for up to 30 seconds). numWaits = 0 while task.getNumWorkUnits() <= 0 and numWaits < 60: time.sleep(0.5) numWaits = numWaits + 1 if task.getNumWorkUnits() <= 0: raise ZAppFrameworkException( _extstr(u"backgroundtaskimpl.TaskFailedToStartError") % task.getName()) #$NON-NLS-1$ # end addTask() def cancelTask(self, taskId, removeFlag=False): task = self.getTask(taskId) if task is None: raise ZAppFrameworkException( _extstr(u"backgroundtaskimpl.FailedToCancelDoesNotExist") % taskId) #$NON-NLS-1$ task.cancel() task.detachListener(self) self.listeners.doCallback(u"onTaskCancelled", [task]) #$NON-NLS-1$ if removeFlag: self.removeTask(taskId) # end cancelTask() def removeTask(self, taskId): task = self.getTask(taskId) if task is None: raise ZAppFrameworkException( _extstr(u"backgroundtaskimpl.FailedToRemoveDoesNotExist") % taskId) #$NON-NLS-1$ if task.isRunning(): raise ZAppFrameworkException( _extstr(u"backgroundtaskimpl.FailedToRemoveStillRunning") % taskId) #$NON-NLS-1$ self.tasks.remove(task) self._removeTask(task) self.listeners.doCallback(u"onTaskRemoved", [task]) #$NON-NLS-1$ # end removeTask() def resumeTask(self, taskId, listener=None): task = self.getTask(taskId) if task is None: raise ZAppFrameworkException( _extstr(u"backgroundtaskimpl.FailedToResumeTaskNotFound") % taskId) #$NON-NLS-1$ if task.isRunning(): raise ZAppFrameworkException( _extstr(u"backgroundtaskimpl.FailedToResumeTaskAlreadyRunning") % taskId) #$NON-NLS-1$ if task.isComplete(): raise ZAppFrameworkException( _extstr(u"backgroundtaskimpl.FailedToResumeTaskComplete") % taskId) #$NON-NLS-1$ if not task.isResumable(): raise ZAppFrameworkException( _extstr(u"backgroundtaskimpl.FailedToResumeTaskNotResumable") % taskId) #$NON-NLS-1$ if listener is not None: task.attachListener(listener) self._resumeTask(task) self.listeners.doCallback(u"onTaskResumed", [task]) #$NON-NLS-1$ return task # end resumeTask() def _loadTasks(self): tasks = [] taskFiles = getDirectoryListing(self.tasksDirectory, TASK_FILE_FILTER) for taskFile in taskFiles: try: task = self._loadTask(taskFile) # Restart any resumable (but not cancelled) tasks. if task.isResumable() and not task.isCancelled( ) and not task.isComplete() and not task.hasError(): self._resumeTask(task) tasks.append(task) except Exception, e: self.logger.exception(e) return tasks
class ZBackgroundTask(IZBackgroundTask): def __init__(self): self.id = None self.name = None self.startTime = ZSchemaDateTime() self.endTime = None self.error = None self.numWorkUnits = 0 self.numCompletedWorkUnits = 0 self.logLocation = None self.logFile = None self.running = False self.stopped = True self.cancelled = False self.lastMessage = None self.listeners = ZListenerSet() self.logger = getLoggerService() # end __init__() def getId(self): return self.id # end getId() def setId(self, id): self.id = id # end setId() def getName(self): return self.name # end getName() def setName(self, name): self.name = name # end setName() def getStartTime(self): return self.startTime # end getStartTime() def setStartTime(self, startTime): self.startTime = startTime # end setStartTime() def getEndTime(self): return self.endTime # end getEndTime() def setEndTime(self, endTime): self.endTime = endTime # end setEndTime() def getNumWorkUnits(self): return self.numWorkUnits # end getNumWorkUnits() def setNumWorkUnits(self, numWorkUnits): self.numWorkUnits = numWorkUnits # end setNumWorkUnits() def getNumCompletedWorkUnits(self): return self.numCompletedWorkUnits # end getNumCompletedWorkUnits() def setNumCompletedWorkUnits(self, numCompletedWorkUnits): self.numCompletedWorkUnits = numCompletedWorkUnits # end setNumCompletedWorkUnits() def getLogLocation(self): return self.logLocation # end getLog() def setLogLocation(self, logLocation): self.logLocation = logLocation # end setLog() def getLogFile(self): if self.logFile is None and self.logLocation is not None: self.logFile = codecs.open(self.logLocation, u"aa", u"utf-8") #$NON-NLS-2$ #$NON-NLS-1$ return self.logFile # end getLogFile() def getLastLogMessage(self): return self.lastMessage # end getLastLogMessage() def getCustomAttributes(self): raise ZAppFrameworkException( u"Subclass should implement this!") #$NON-NLS-1$ # end getCustomAttributes() def setCustomAttributes(self, attributeMap): raise ZAppFrameworkException( u"Subclass should implement this!") #$NON-NLS-1$ # end setCustomAttributes() def isRunning(self): return self.running # end isRunning() def isCancelled(self): return self.cancelled # end isCancelled() def setCancelled(self, cancelled=True): self.cancelled = cancelled # end setCancelled() def isComplete(self): return self.numCompletedWorkUnits == self.numWorkUnits # end isComplete() def isResumable(self): raise ZAppFrameworkException( u"Subclass should implement this!") #$NON-NLS-1$ # end isResumable() def getError(self): return self.error # end getError() def setError(self, errorMessage, errorDetails): self.error = (errorMessage, errorDetails) # end setError() def hasError(self): return self.error is not None # end hasError() def stop(self): self.logger.debug(u"[bgtask.%s] Stopping task." % (self.getName())) #$NON-NLS-1$ self.stopped = True # This should really be a wait/notify while self.running: time.sleep(0.25) # end stop() def _doCancel(self): u"Subclasses can override in order to provide additional cancel logic." #$NON-NLS-1$ # end _doCancel() def cancel(self): self.logger.debug(u"[bgtask.%s] Cancelling task." % (self.getName())) #$NON-NLS-1$ self.stopped = True self.cancelled = True self._doCancel() # This should really be a wait/notify while self.running: time.sleep(0.25) # Notify the listeners. self.listeners.doCallback(u"onCancel", [self]) #$NON-NLS-1$ # end cancel() def cancelAsync(self): thread = ZThread(ZMethodRunnable(self.cancel), u"CancelTask", True) #$NON-NLS-1$ thread.start() # end cancelAsync() def attachListener(self, listener): self.listeners._acquireMutex() try: self.listeners.append(listener) listener.onAttached(self, self.numCompletedWorkUnits) finally: self.listeners._releaseMutex() # end attachListener() def detachListener(self, listener): self.listeners.remove(listener) # end detachListener() # Convenience method to indicate that work has been done. # # message: the message to send to the listeners (and optionally log) # amount: amount of work that was done # logMessage: flag indicating whether this message should be logged (useful for tasks that do a LOT # of work but only want to log certain vital messages) def _incrementWork(self, message, amount=1, logMessage=True): if self.isCancelled(): return self.lastMessage = message self.numCompletedWorkUnits = self.numCompletedWorkUnits + amount self.listeners.doCallback(u"onWorkDone", [self, amount, message]) #$NON-NLS-1$ if logMessage: self._writeToLog(message) if self.numCompletedWorkUnits == self.numWorkUnits: self.stopped = True self.endTime = ZSchemaDateTime() self.listeners.doCallback(u"onComplete", [self]) #$NON-NLS-1$ # end _incrementWork() # Convenience method to raise an error message. This will notify the listeners of the # error, cancel the task, and log the error message. def _raiseError(self, errorMessage, errorDetails): self.logger.error(errorMessage) self.error = (errorMessage, errorDetails) self.listeners.doCallback( u"onError", [self, errorMessage, errorDetails]) #$NON-NLS-1$ self._writeToLog( _extstr(u"backgroundtaskimpl.ErrorInTask") % errorMessage) #$NON-NLS-1$ self._writeToLog(errorDetails) self.endTime = ZSchemaDateTime() self.stopped = True self.cancelled = True # end _raiseError() # Reports an exception (when the _run() method throws). def _reportException(self, exception): if not isinstance(exception, ZException): exception = ZException( _extstr(u"backgroundtaskimpl.UnexpectedBGTaskError") % self.getName(), exception) #$NON-NLS-1$ self.logger.exception(exception) self._raiseError(exception.getMessage(), exception.getStackTrace()) # end _reportException() def _writeToLog(self, message): self.logger.debug(u"[bgtask.%s] %s" % (self.getName(), message)) #$NON-NLS-1$ if message is not None and self.getLogFile() is not None: self.getLogFile().write(message) self.getLogFile().write(u"\n") #$NON-NLS-1$ self.getLogFile().flush() # end _writeToLog() def run(self): self._writeToLog( u"[bgtask.%s] Task started: %s" % (self.getName(), unicode(ZSchemaDateTime()))) #$NON-NLS-1$ # Send the 'onStarted' event. self._fireStartEvent() # Run the actual task logic here. try: self._run() except ZException, ze: self._reportException(ze) except Exception, e: self._reportException( ZException( _extstr(u"backgroundtaskimpl.ErrorExecingTask") % self.getName(), e)) #$NON-NLS-1$
class ZBackgroundTask(IZBackgroundTask): def __init__(self): self.id = None self.name = None self.startTime = ZSchemaDateTime() self.endTime = None self.error = None self.numWorkUnits = 0 self.numCompletedWorkUnits = 0 self.logLocation = None self.logFile = None self.running = False self.stopped = True self.cancelled = False self.lastMessage = None self.listeners = ZListenerSet() self.logger = getLoggerService() # end __init__() def getId(self): return self.id # end getId() def setId(self, id): self.id = id # end setId() def getName(self): return self.name # end getName() def setName(self, name): self.name = name # end setName() def getStartTime(self): return self.startTime # end getStartTime() def setStartTime(self, startTime): self.startTime = startTime # end setStartTime() def getEndTime(self): return self.endTime # end getEndTime() def setEndTime(self, endTime): self.endTime = endTime # end setEndTime() def getNumWorkUnits(self): return self.numWorkUnits # end getNumWorkUnits() def setNumWorkUnits(self, numWorkUnits): self.numWorkUnits = numWorkUnits # end setNumWorkUnits() def getNumCompletedWorkUnits(self): return self.numCompletedWorkUnits # end getNumCompletedWorkUnits() def setNumCompletedWorkUnits(self, numCompletedWorkUnits): self.numCompletedWorkUnits = numCompletedWorkUnits # end setNumCompletedWorkUnits() def getLogLocation(self): return self.logLocation # end getLog() def setLogLocation(self, logLocation): self.logLocation = logLocation # end setLog() def getLogFile(self): if self.logFile is None and self.logLocation is not None: self.logFile = codecs.open(self.logLocation, u"aa", u"utf-8") #$NON-NLS-2$ #$NON-NLS-1$ return self.logFile # end getLogFile() def getLastLogMessage(self): return self.lastMessage # end getLastLogMessage() def getCustomAttributes(self): raise ZAppFrameworkException(u"Subclass should implement this!") #$NON-NLS-1$ # end getCustomAttributes() def setCustomAttributes(self, attributeMap): raise ZAppFrameworkException(u"Subclass should implement this!") #$NON-NLS-1$ # end setCustomAttributes() def isRunning(self): return self.running # end isRunning() def isCancelled(self): return self.cancelled # end isCancelled() def setCancelled(self, cancelled = True): self.cancelled = cancelled # end setCancelled() def isComplete(self): return self.numCompletedWorkUnits == self.numWorkUnits # end isComplete() def isResumable(self): raise ZAppFrameworkException(u"Subclass should implement this!") #$NON-NLS-1$ # end isResumable() def getError(self): return self.error # end getError() def setError(self, errorMessage, errorDetails): self.error = (errorMessage, errorDetails) # end setError() def hasError(self): return self.error is not None # end hasError() def stop(self): self.logger.debug(u"[bgtask.%s] Stopping task." % (self.getName())) #$NON-NLS-1$ self.stopped = True # This should really be a wait/notify while self.running: time.sleep(0.25) # end stop() def _doCancel(self): u"Subclasses can override in order to provide additional cancel logic." #$NON-NLS-1$ # end _doCancel() def cancel(self): self.logger.debug(u"[bgtask.%s] Cancelling task." % (self.getName())) #$NON-NLS-1$ self.stopped = True self.cancelled = True self._doCancel() # This should really be a wait/notify while self.running: time.sleep(0.25) # Notify the listeners. self.listeners.doCallback(u"onCancel", [self]) #$NON-NLS-1$ # end cancel() def cancelAsync(self): thread = ZThread(ZMethodRunnable(self.cancel), u"CancelTask", True) #$NON-NLS-1$ thread.start() # end cancelAsync() def attachListener(self, listener): self.listeners._acquireMutex() try: self.listeners.append(listener) listener.onAttached(self, self.numCompletedWorkUnits) finally: self.listeners._releaseMutex() # end attachListener() def detachListener(self, listener): self.listeners.remove(listener) # end detachListener() # Convenience method to indicate that work has been done. # # message: the message to send to the listeners (and optionally log) # amount: amount of work that was done # logMessage: flag indicating whether this message should be logged (useful for tasks that do a LOT # of work but only want to log certain vital messages) def _incrementWork(self, message, amount = 1, logMessage = True): if self.isCancelled(): return self.lastMessage = message self.numCompletedWorkUnits = self.numCompletedWorkUnits + amount self.listeners.doCallback(u"onWorkDone", [self, amount, message]) #$NON-NLS-1$ if logMessage: self._writeToLog(message) if self.numCompletedWorkUnits == self.numWorkUnits: self.stopped = True self.endTime = ZSchemaDateTime() self.listeners.doCallback(u"onComplete", [self]) #$NON-NLS-1$ # end _incrementWork() # Convenience method to raise an error message. This will notify the listeners of the # error, cancel the task, and log the error message. def _raiseError(self, errorMessage, errorDetails): self.logger.error(errorMessage) self.error = (errorMessage, errorDetails) self.listeners.doCallback(u"onError", [self, errorMessage, errorDetails]) #$NON-NLS-1$ self._writeToLog(_extstr(u"backgroundtaskimpl.ErrorInTask") % errorMessage) #$NON-NLS-1$ self._writeToLog(errorDetails) self.endTime = ZSchemaDateTime() self.stopped = True self.cancelled = True # end _raiseError() # Reports an exception (when the _run() method throws). def _reportException(self, exception): if not isinstance(exception, ZException): exception = ZException(_extstr(u"backgroundtaskimpl.UnexpectedBGTaskError") % self.getName(), exception) #$NON-NLS-1$ self.logger.exception(exception) self._raiseError(exception.getMessage(), exception.getStackTrace()) # end _reportException() def _writeToLog(self, message): self.logger.debug(u"[bgtask.%s] %s" % (self.getName(), message)) #$NON-NLS-1$ if message is not None and self.getLogFile() is not None: self.getLogFile().write(message) self.getLogFile().write(u"\n") #$NON-NLS-1$ self.getLogFile().flush() # end _writeToLog() def run(self): self._writeToLog(u"[bgtask.%s] Task started: %s" % (self.getName(), unicode(ZSchemaDateTime()))) #$NON-NLS-1$ # Send the 'onStarted' event. self._fireStartEvent() # Run the actual task logic here. try: self._run() except ZException, ze: self._reportException(ze) except Exception, e: self._reportException(ZException(_extstr(u"backgroundtaskimpl.ErrorExecingTask") % self.getName(), e)) #$NON-NLS-1$
class ZBackgroundTaskService(IZBackgroundTaskService, IZBackgroundTaskListener): def __init__(self): self.logger = None self.tasksDirectory = None self.tasks = [] self.listeners = ZListenerSet() # end __init__() def _getTasksDirectory(self, applicationModel): return applicationModel.getUserProfile().getDirectory(u"bgtasks") #$NON-NLS-1$ # end _getTasksDirectory() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService(IZAppServiceIDs.LOGGER_SERVICE_ID) self.tasksDirectory = self._getTasksDirectory(applicationModel) self.tasks = self._loadTasks() self.logger.debug(u"Background Task Service started [%d tasks loaded]." % len(self.tasks)) #$NON-NLS-1$ # end start() def stop(self): # First, stop all tasks. for task in self.tasks: if task.isRunning(): task.stop() self.tasks = [] # end stop() def getTasks(self): return self.tasks # end getTasks() def getTask(self, taskId): for task in self.tasks: if task.getId() == taskId: return task return None # end getTask() def addTask(self, task): task.setId(generate()) taskLogFilename = os.path.join(self.tasksDirectory, task.getId() + u".task.log") #$NON-NLS-1$ task.setLogLocation(taskLogFilename) self.tasks.append(task) self.listeners.doCallback(u"onTaskAdded", [task]) #$NON-NLS-1$ self._resumeTask(task) # Wait until the num work units has been set by the task (but only # wait for up to 30 seconds). numWaits = 0 while task.getNumWorkUnits() <= 0 and numWaits < 60: time.sleep(0.5) numWaits = numWaits + 1 if task.getNumWorkUnits() <= 0: raise ZAppFrameworkException(_extstr(u"backgroundtaskimpl.TaskFailedToStartError") % task.getName()) #$NON-NLS-1$ # end addTask() def cancelTask(self, taskId, removeFlag = False): task = self.getTask(taskId) if task is None: raise ZAppFrameworkException(_extstr(u"backgroundtaskimpl.FailedToCancelDoesNotExist") % taskId) #$NON-NLS-1$ task.cancel() task.detachListener(self) self.listeners.doCallback(u"onTaskCancelled", [task]) #$NON-NLS-1$ if removeFlag: self.removeTask(taskId) # end cancelTask() def removeTask(self, taskId): task = self.getTask(taskId) if task is None: raise ZAppFrameworkException(_extstr(u"backgroundtaskimpl.FailedToRemoveDoesNotExist") % taskId) #$NON-NLS-1$ if task.isRunning(): raise ZAppFrameworkException(_extstr(u"backgroundtaskimpl.FailedToRemoveStillRunning") % taskId) #$NON-NLS-1$ self.tasks.remove(task) self._removeTask(task) self.listeners.doCallback(u"onTaskRemoved", [task]) #$NON-NLS-1$ # end removeTask() def resumeTask(self, taskId, listener = None): task = self.getTask(taskId) if task is None: raise ZAppFrameworkException(_extstr(u"backgroundtaskimpl.FailedToResumeTaskNotFound") % taskId) #$NON-NLS-1$ if task.isRunning(): raise ZAppFrameworkException(_extstr(u"backgroundtaskimpl.FailedToResumeTaskAlreadyRunning") % taskId) #$NON-NLS-1$ if task.isComplete(): raise ZAppFrameworkException(_extstr(u"backgroundtaskimpl.FailedToResumeTaskComplete") % taskId) #$NON-NLS-1$ if not task.isResumable(): raise ZAppFrameworkException(_extstr(u"backgroundtaskimpl.FailedToResumeTaskNotResumable") % taskId) #$NON-NLS-1$ if listener is not None: task.attachListener(listener) self._resumeTask(task) self.listeners.doCallback(u"onTaskResumed", [task]) #$NON-NLS-1$ return task # end resumeTask() def _loadTasks(self): tasks = [] taskFiles = getDirectoryListing(self.tasksDirectory, TASK_FILE_FILTER) for taskFile in taskFiles: try: task = self._loadTask(taskFile) # Restart any resumable (but not cancelled) tasks. if task.isResumable() and not task.isCancelled() and not task.isComplete() and not task.hasError(): self._resumeTask(task) tasks.append(task) except Exception, e: self.logger.exception(e) return tasks
class ZMediaStorageService(IZMediaStorageService): def __init__(self): self.mediaStoreTypes = [] self.mediaSites = [] self.mediaStores = [] self.mediaStoresDirectory = None self.listeners = ZListenerSet() # end __init__() def _getMediaStoragesDirectory(self): return self.applicationModel.getUserProfile().getDirectory(u"mediastorages") #$NON-NLS-1$ # end _getMediaStoragesDirectory() def start(self, applicationModel): self.applicationModel = applicationModel self.logger = applicationModel.getEngine().getService(IZAppServiceIDs.LOGGER_SERVICE_ID) self.mediaStoresDirectory = self._getMediaStoragesDirectory() self.mediaStoreTypes = self._loadMediaStorageTypes() self.mediaSites = self._loadMediaSites() self.mediaStores = self._loadMediaStorages() for site in self.mediaSites: mediaStoreTypeId = site.getMediaStorageTypeId() mediaStoreType = self._getMediaStorageType(mediaStoreTypeId) if mediaStoreType is None: raise ZBlogAppException(_extstr(u"mediastoragesrvc.StoreTypeNotFoundError") % (site.getId(), mediaStoreTypeId)) #$NON-NLS-1$ site.setMediaStorageType(mediaStoreType) self.logger.debug(u"Media Storage Service started [%d types, %d sites, %d storages loaded]." % (len(self.mediaStoreTypes), len(self.mediaSites), len(self.mediaStores))) #$NON-NLS-1$ # end start() def stop(self): self.mediaStoreTypes = [] self.mediaSites = [] self.mediaStores = [] # end stop() def addListener(self, listener): self.listeners.append(listener) self.logger.debug(u"Added Media Storage Service Listener: '%s'" % unicode(listener.__class__)) #$NON-NLS-1$ # end addListener() def removeListener(self, listener): self.listeners.remove(listener) self.logger.debug(u"Removed Media Storage Service Listener: '%s'" % unicode(listener.__class__)) #$NON-NLS-1$ # end removeListener() def getMediaSite(self, mediaSiteId): for site in self.mediaSites: if site.getId() == mediaSiteId: return site return None # end getMediaSite() def getMediaSites(self): rval = [] for site in self.mediaSites: if not site.isInternal(): rval.append(site) return rval # end getMediaSites() def getMediaStorageById(self, mediaStoreId): for uploader in self.mediaStores: if uploader.getId() == mediaStoreId: return uploader return None # end getMediaStorageById() def getMediaStorageByName(self, name): for uploader in self.mediaStores: if uploader.getName() == name: return uploader return None # end getMediaStorageByName() def getMediaStorages(self): return self.mediaStores # end getMediaStorages() def hasMediaStorage(self, name): return self.getMediaStorageByName(name) is not None # end hasMediaStorage() def createStorageName(self, name): if not self.hasMediaStorage(name): return name count = 1 while count < 1000: newname = u"%s (%03d)" % (name, count) #$NON-NLS-1$ if not self.hasMediaStorage(newname): return newname count = count + 1 newname = u"%s (%d)" % (name, int(time.time())) #$NON-NLS-1$ return newname # end createStorageName() def createMediaStorage(self, name, mediaSiteId, properties, persist = True): if self.hasMediaStorage(name): raise ZBlogAppException(_extstr(u"mediastoragesrvc.FailedToAddMediaStorageError") % name) #$NON-NLS-1$ storage = self._createMediaStorage(name, mediaSiteId, properties) if persist: self.mediaStores.append(storage) self.saveMediaStorage(storage) self.logger.debug(u"Created a media storage named '%s' using site '%s'." % (name, mediaSiteId)) #$NON-NLS-1$ for listener in self.listeners: listener.onMediaStorageAdded(storage) return storage # end createMediaStorage() def _createMediaStorage(self, name, mediaSiteId, properties): site = self.getMediaSite(mediaSiteId) if site is None: raise ZBlogAppException(_extstr(u"mediastoragesrvc.NoMediaSiteFound") % mediaSiteId) #$NON-NLS-1$ id = generate() storageTypeId = site.getMediaStorageTypeId() storageType = self._getMediaStorageType(storageTypeId) storage = ZMediaStorage(id, name, mediaSiteId, properties) registryFile = os.path.join(self.mediaStoresDirectory, id + u".store.registry") #$NON-NLS-1$ storage.init(site, storageType, registryFile) return storage # end _createMediaStorage() def saveMediaStorage(self, mediaStore): path = os.path.join(self.mediaStoresDirectory, mediaStore.getId() + u".store") #$NON-NLS-1$ saveMediaStorage(mediaStore, path) self.logger.debug(u"Saved Media Storage: '%s'" % unicode(mediaStore.getName())) #$NON-NLS-1$ # end saveMediaStorage() def deleteMediaStorageById(self, mediaStoreId): storage = self.getMediaStorageById(mediaStoreId) if storage is not None: self.deleteMediaStorage(storage) # end deleteMediaStorageById() def deleteMediaStorageByName(self, name): storage = self.getMediaStorageByName(name) if storage is not None: self.deleteMediaStorage(storage) # end deleteMediaStorageByName() def deleteMediaStorage(self, mediaStore): self.mediaStores.remove(mediaStore) path = os.path.join(self.mediaStoresDirectory, mediaStore.getId() + u".store") #$NON-NLS-1$ deleteFile(path) registryPath = path + u".registry" #$NON-NLS-1$ deleteFile(registryPath) self.logger.debug(u"Deleted a media storage named '%s'." % mediaStore.getName()) #$NON-NLS-1$ for listener in self.listeners: listener.onMediaStorageRemoved(mediaStore) # end deleteMediaStorage() def _loadMediaStorageTypes(self): pluginRegistry = self.applicationModel.getPluginRegistry() extensions = pluginRegistry.getExtensions(IZBlogAppExtensionPoints.ZEP_ZOUNDRY_MEDIASTORE_TYPE) mediaTypeDefs = map(ZMediaStorageTypeDef, extensions) return map(ZMediaStorageType, mediaTypeDefs) # end _loadMediaStorageTypes() def _loadMediaSites(self): pluginRegistry = self.applicationModel.getPluginRegistry() extensions = pluginRegistry.getExtensions(IZBlogAppExtensionPoints.ZEP_ZOUNDRY_MEDIASTORE_SITE) mediaSiteDefs = map(ZMediaSiteDef, extensions) return map(ZMediaSite, mediaSiteDefs) # end _loadMediaSites() def _loadMediaStorages(self): storages = [] storageFiles = getDirectoryListing(self.mediaStoresDirectory, STORE_FILE_FILTER) for storageFile in storageFiles: registryFile = storageFile + u".registry" #$NON-NLS-1$ storage = self._loadMediaStorage(storageFile) mediaSiteId = storage.getMediaSiteId() site = self.getMediaSite(mediaSiteId) if site is None: raise ZBlogAppException(_extstr(u"mediastoragesrvc.NoMediaSiteFound") % mediaSiteId) #$NON-NLS-1$ storageTypeId = site.getMediaStorageTypeId() storageType = self._getMediaStorageType(storageTypeId) storage.init(site, storageType, registryFile) storages.append(storage) return storages # end _loadMediaStorages() def _loadMediaStorage(self, storageFile): return loadMediaStorage(storageFile) # end _loadMediaStorage() def _getMediaStorageType(self, mediaStoreTypeId): for msType in self.mediaStoreTypes: if msType.getId() == mediaStoreTypeId: return msType return None
class ZAbstractProfileImporter(IZRunnableProgress): def __init__(self, pathToSourceProfile, pathToRavenProfile, systemProfile): self.stopped = True self.pathToSourceProfile = pathToSourceProfile self.pathToRavenProfile = pathToRavenProfile self.systemProfile = systemProfile self.listeners = ZListenerSet() # end __init__() def addListener(self, listener): if not isinstance(listener, IZRunnableProgressListener): raise ZBlogAppException( _extstr(u"importer.IncorrectListenerType")) #$NON-NLS-1$ self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def _getRavenAccountDir(self): return os.path.join(self.pathToRavenProfile, u"accounts") #$NON-NLS-1$ # end _getRavenAccountDir() def _notifyWorkDone(self, workunits, progressText): for listener in self.listeners: listener.onWorkDone(workunits, progressText) # end _notifyWorkDone def _notifyCancel(self): for listener in self.listeners: listener.onCancel() # end _notifyCancel def stop(self): self.stopped = True # end stop() def run(self): self.stopped = False if self._getWorkAmount() < 1: return for listener in self.listeners: listener.onStarted(self._getWorkAmount()) # do the import self._runImport() # notify done for listener in self.listeners: listener.onComplete() # end run() def _runImport(self): raise ZAbstractMethodCalledException(self.__class__, u"_runImport") #$NON-NLS-1$ # end _runImport() def _getWorkAmount(self): raise ZAbstractMethodCalledException(self.__class__, u"_getWorkAmount") #$NON-NLS-1$
class ZDocumentIndex(IZService, IZDocumentIndex, IZDataStoreListener): def __init__(self): self.logger = None self.listeners = ZListenerSet() self.provider = None # end __init__() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService( IZAppServiceIDs.LOGGER_SERVICE_ID) self.dataStore = applicationModel.getEngine().getService( IZBlogAppServiceIDs.DATA_STORE_SERVICE_ID) self.bgTaskService = applicationModel.getEngine().getService( IZBlogAppServiceIDs.BACKGROUND_TASK_SERVICE_ID) self.provider = PROVIDER_FACTORY.createIndexProvider() self.provider.create(applicationModel) needsReindex = False if self.provider.requiresReindex(): self.logger.warning( u"Re-indexing documents because the provider requires it." ) #$NON-NLS-1$ needsReindex = True elif self.dataStore.getNumDocuments() != self.provider.getNumDocuments( ): self.logger.warning( u"Re-indexing documents because the number of documents in the data store does not match the number of documents in the provider." ) #$NON-NLS-1$ needsReindex = True # If a reindex is needed, then go ahead and create the reindex # background task and start it. (dependency on the bg task service) if needsReindex: self.provider.clear() task = ZReindexTask() task.initializeTaskParams(self.dataStore, self) self.bgTaskService.addTask(task) else: self.provider.optimize() # Register as a listener of the data store self.dataStore.addListener(self) self.logger.debug(u"Document Index started.") #$NON-NLS-1$ # end start() def stop(self): # Unregister as a listener of the data store self.dataStore.removeListener(self) self.provider.destroy() self.dataStore = None self.provider = None # end stop() def onReindexComplete(self): self.provider.optimize() # end onReindexComplete() def findDocuments(self, filter): return self.provider.findDocuments(filter) # end findDocuments() def findTags(self, filter): return self.provider.findTags(filter) # end findTags() def findLinks(self, filter): return self.provider.findLinks(filter) # end findLinks() def findImages(self, filter): return self.provider.findImages(filter) # end findImages() def getDocumentCount(self, filter): return self.provider.getDocumentCount(filter) # end getDocumentCount() def getTagCount(self, filter): return self.provider.getTagCount(filter) # end getTagCount() def getLinkCount(self, filter): return self.provider.getLinkCount(filter) # end getLinkCount() def getImageCount(self, filter): return self.provider.getImageCount(filter) # end getImageCount() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def onDocumentAdded(self, document): self.provider.addDocument(document, self.listeners) # end onDocumentAdded() def onDocumentChanged(self, document, metaDataOnly): #@UnusedVariable self.provider.updateDocument(document, self.listeners) # end onDocumentChange() def onDocumentDeleted(self, document): self.provider.removeDocument(document.getId(), self.listeners)
class ZDataStore(IZDataStore): def __init__(self): self.listeners = ZListenerSet() # end __init__() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService(IZAppServiceIDs.LOGGER_SERVICE_ID) self.dataStoreDirectory = applicationModel.getUserProfile().getDirectory(u"datastore") #$NON-NLS-1$ self.logger.debug(u"Data Store started.") #$NON-NLS-1$ # end start() def stop(self): pass # end stop() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def addDocument(self, document): if document.getId(): self.saveDocument(document) return document.setId(guid.generate()) if document.getCreationTime() is None: document.setCreationTime(ZSchemaDateTime()) if document.getLastModifiedTime() is None: document.setLastModifiedTime(ZSchemaDateTime()) documentXmlPath = self._getDocumentPath( document.getId() ) saveDocument(document, documentXmlPath) self._fireDocumentAddedEvent(document) # end addDocument() def getDocument(self, docId): documentXmlPath = self._getDocumentPath( docId ) return loadDocument(documentXmlPath) # end getDocument() def exists(self, docId): documentXmlPath = self._getDocumentPath( docId ) return os.path.exists(documentXmlPath) # end exists() def getDocumentIDs(self): docXmlFilePaths = getDirectoryListing(self.dataStoreDirectory, documentXmlFilter) return map(self._getDocumentIDFromPath, docXmlFilePaths) # end getDocumentIDs() def saveDocument(self, document, metaDataOnly = False): if not document.getId(): self.addDocument(document) return if not metaDataOnly: document.setLastModifiedTime(ZSchemaDateTime()) documentXmlPath = self._getDocumentPath( document.getId() ) saveDocument(document, documentXmlPath) self.logger.debug(u"Saved document id=%s" % document.getId()) #$NON-NLS-1$ self._fireDocumentChangedEvent(document, metaDataOnly) # end saveDocument() def removeDocument(self, docId): documentXmlPath = self._getDocumentPath( docId ) document = loadDocument(documentXmlPath) os.remove(documentXmlPath) self._fireDocumentDeletedEvent(document) # end removeDocument def getNumDocuments(self): return len(getDirectoryListing(self.dataStoreDirectory, documentXmlFilter)) # end getNumDocuments() # Given a path to the document xml file, returns the ID of the document. def _getDocumentIDFromPath(self, path): return os.path.basename(path).split(u".")[0] #$NON-NLS-1$ # end _getDocumentIDFromPath() def _getDocumentPath(self, docId): u"""_getDocumentPath(string) -> string Returns file path given document id.""" #$NON-NLS-1$ documentXmlPath = os.path.join(self.dataStoreDirectory, docId + u".rbe.xml") #$NON-NLS-1$ return documentXmlPath # end _getDocumentPath def _fireDocumentAddedEvent(self, document): for listener in self.listeners: try: self.logger.debug(u"Firing doc added event to handler: %s" % unicode(listener)) #$NON-NLS-1$ listener.onDocumentAdded(document) except Exception, e: self.logger.exception(e) self.logger.debug(u"Done firing doc added event.") #$NON-NLS-1$
class ZDocumentIndex(IZService, IZDocumentIndex, IZDataStoreListener): def __init__(self): self.logger = None self.listeners = ZListenerSet() self.provider = None # end __init__() def start(self, applicationModel): self.logger = applicationModel.getEngine().getService(IZAppServiceIDs.LOGGER_SERVICE_ID) self.dataStore = applicationModel.getEngine().getService(IZBlogAppServiceIDs.DATA_STORE_SERVICE_ID) self.bgTaskService = applicationModel.getEngine().getService(IZBlogAppServiceIDs.BACKGROUND_TASK_SERVICE_ID) self.provider = PROVIDER_FACTORY.createIndexProvider() self.provider.create(applicationModel) needsReindex = False if self.provider.requiresReindex(): self.logger.warning(u"Re-indexing documents because the provider requires it.") #$NON-NLS-1$ needsReindex = True elif self.dataStore.getNumDocuments() != self.provider.getNumDocuments(): self.logger.warning(u"Re-indexing documents because the number of documents in the data store does not match the number of documents in the provider.") #$NON-NLS-1$ needsReindex = True # If a reindex is needed, then go ahead and create the reindex # background task and start it. (dependency on the bg task service) if needsReindex: self.provider.clear() task = ZReindexTask() task.initializeTaskParams(self.dataStore, self) self.bgTaskService.addTask(task) else: self.provider.optimize() # Register as a listener of the data store self.dataStore.addListener(self) self.logger.debug(u"Document Index started.") #$NON-NLS-1$ # end start() def stop(self): # Unregister as a listener of the data store self.dataStore.removeListener(self) self.provider.destroy() self.dataStore = None self.provider = None # end stop() def onReindexComplete(self): self.provider.optimize() # end onReindexComplete() def findDocuments(self, filter): return self.provider.findDocuments(filter) # end findDocuments() def findTags(self, filter): return self.provider.findTags(filter) # end findTags() def findLinks(self, filter): return self.provider.findLinks(filter) # end findLinks() def findImages(self, filter): return self.provider.findImages(filter) # end findImages() def getDocumentCount(self, filter): return self.provider.getDocumentCount(filter) # end getDocumentCount() def getTagCount(self, filter): return self.provider.getTagCount(filter) # end getTagCount() def getLinkCount(self, filter): return self.provider.getLinkCount(filter) # end getLinkCount() def getImageCount(self, filter): return self.provider.getImageCount(filter) # end getImageCount() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener() def onDocumentAdded(self, document): self.provider.addDocument(document, self.listeners) # end onDocumentAdded() def onDocumentChanged(self, document, metaDataOnly): #@UnusedVariable self.provider.updateDocument(document, self.listeners) # end onDocumentChange() def onDocumentDeleted(self, document): self.provider.removeDocument(document.getId(), self.listeners)
class ZSystemProperties: u"""Use this class to get and set System Properties.""" #$NON-NLS-1$ def __init__(self, sysPropsFileName): # create a lock for thread synchronization self.lock = ZMutex(u"ZSystemProperties") #$NON-NLS-1$ self.listeners = ZListenerSet() self.sysPropsFileName = sysPropsFileName self.sysPropsDoc = ZDom() self.reloadProperties() # end __init__() def addListener(self, listener): self.listeners.append(listener) # end addListener() def removeListener(self, listener): self.listeners.remove(listener) # end removeListener def _fireEvent(self, key, value): for listener in self.listeners: listener.onSystemPropertyChange(key, value) # end _fireEvent() def reloadProperties(self): self.lock.acquire() try: # Open and parse the system properties file self.sysPropsDoc.load(self.sysPropsFileName) finally: self.lock.release() # end reloadProperties() # Public method - call this to save the system properties. def save(self): u"Public method - call this to save the system properties." #$NON-NLS-1$ self.lock.acquire() self.saveProperties() self.lock.release() self._fireEvent(None, None) # end save() # Note that locking is required prior to calling saveProperties() def saveProperties(self): try: tempSysPropsFileName = self.sysPropsFileName + u".t" #$NON-NLS-1$ self.sysPropsDoc.save(tempSysPropsFileName, True) deleteFile(self.sysPropsFileName) renameFile(tempSysPropsFileName, self.sysPropsFileName) except Exception, e: raise ZException( _extstr(u"sysprops.ErrorSavingPropsFile") % self.sysPropsFileName, e) #$NON-NLS-1$