class DatabaseConfig(object): ''' Reads and writes database settings in the registry ''' def __init__(self): self.dbHost = "Host" self.dbPort = "Port" self.dbName = "Database" self.regConfig = RegistryConfig() def read(self): ''' Get the database connection properties ''' dbProps = self.regConfig.read([self.dbHost, self.dbPort, self.dbName]) if len(dbProps) < 3: return None else: return DatabaseConnection(dbProps[self.dbHost], dbProps[self.dbPort], dbProps[self.dbName]) def write(self, dbconnection): ''' Writes the database connection settings to the registry ''' dbSettings = {} dbSettings[self.dbHost] = dbconnection.Host dbSettings[self.dbPort] = dbconnection.Port dbSettings[self.dbName] = dbconnection.Database #Write dictionary to registry self.regConfig.write(dbSettings)
class DatabaseConfig(object): ''' Reads and writes database settings in the registry ''' def __init__(self): self.dbHost = "Host" self.dbPort = "Port" self.dbName = "Database" self.regConfig = RegistryConfig() def read(self): ''' Get the database connection properties ''' dbProps = self.regConfig.read([self.dbHost,self.dbPort,self.dbName]) if len(dbProps) < 3: return None else: return DatabaseConnection(dbProps[self.dbHost], dbProps[self.dbPort], dbProps[self.dbName]) def write(self,dbconnection): ''' Writes the database connection settings to the registry ''' dbSettings = {} dbSettings[self.dbHost] = dbconnection.Host dbSettings[self.dbPort] = dbconnection.Port dbSettings[self.dbName] = dbconnection.Database #Write dictionary to registry self.regConfig.write(dbSettings)
def fontCachePath(): regConfig = RegistryConfig() try: lookupReg = regConfig.read(['Config']) cachePath=lookupReg['Config'] return cachePath+"/font.cache" except: return None
def settingsDialog(self): ''' Incase the user clicks reset button to change the settings ''' connSettings = ['Host', 'Database', 'Port'] setting = RegistryConfig() dbDlg = dbconnDlg(self) settingData = setting.read(connSettings) dbDlg.txtDatabase.setText(str(settingData['Database'])) dbDlg.txtHost.setText(str(settingData['Host'])) dbDlg.txtPort.setText(str(settingData['Port'])) dbDlg.exec_()
def documentTemplates(): """ Return a dictionary of document names and their corresponding absolute file paths. """ docTemplates = OrderedDict() regConfig = RegistryConfig() keyName = "ComposerTemplates" pathConfig = regConfig.read([keyName]) if len(pathConfig) > 0: templateDir = pathConfig[keyName] pathDir = QDir(templateDir) pathDir.setNameFilters(["*.sdt"]) docFileInfos = pathDir.entryInfoList(QDir.Files,QDir.Name) for df in docFileInfos: docTemplates[df.completeBaseName()] = df.absoluteFilePath() return docTemplates
def networkResource(self): ''' Get the network resource location from the registry. ''' regConfig = RegistryConfig() networkResReg = regConfig.read([NETWORK_DOC_RESOURCE]) if len(networkResReg) == 0: networkLocation = "C:/" else: networkLocation = networkResReg[NETWORK_DOC_RESOURCE] return networkLocation
def _composerTemplatesPath(self): """ Reads the path of composer templates in the registry. """ regConfig = RegistryConfig() keyName = "ComposerTemplates" valueCollection = regConfig.read([keyName]) if len(valueCollection) == 0: return None else: return valueCollection[keyName]
def _composerOutputPath(self): """ Returns the directory name of the composer output directory. """ regConfig = RegistryConfig() keyName = "ComposerOutputs" valueCollection = regConfig.read([keyName]) if len(valueCollection) == 0: return None else: return valueCollection[keyName]
def initLookups(): ''' Loads the initial lookup values into the STDM database. First check if there is a flag in the registry for asserting whether the lookup values have been initialized. If False or the key does not exist then initialize then set key to True ''' regConfig = RegistryConfig() lookupReg = regConfig.read([DATABASE_LOOKUP]) if len(lookupReg) == 0 : loadLookups() else: lookupState = lookupReg[DATABASE_LOOKUP].lower() if lookupState == "false":loadLookups()
def __init__(self, path=None): self._file = PLUGIN_DIR self.baseDir = None self._html = '' self._sql = '' self.userPath = None self.cachePath = None self.config = RegistryConfig() self.checkPreviousSetting()
def loadLookups(): for k,v in stdm_lookups.iteritems(): modelName = k Values = v model = globals()[modelName] modelInstance = model() queryObj = modelInstance.queryObject() #Ensure item does not exist before being inserted for lk in v: #Convert QString to Python string lk = unicode(lk) lkObj = queryObj.filter(model.name == lk).first() if lkObj == None: lkInst = model() lkInst.name = lk lkInst.save() #Update registry regConfig = RegistryConfig() regConfig.write({DATABASE_LOOKUP:str(True)})
def documentTemplates(): """ Return a dictionary of document names and their corresponding absolute file paths. """ docTemplates = OrderedDict() regConfig = RegistryConfig() keyName = "ComposerTemplates" pathConfig = regConfig.read([keyName]) if len(pathConfig) > 0: templateDir = pathConfig[keyName] pathDir = QDir(templateDir) pathDir.setNameFilters(["*.sdt"]) docFileInfos = pathDir.entryInfoList(QDir.Files, QDir.Name) for df in docFileInfos: docTemplates[df.completeBaseName()] = df.absoluteFilePath() return docTemplates
class FilePaths(object): def __init__(self, path=None): self._file=PLUGIN_DIR self.baseDir=None self._html='' self._sql='' self.userPath=None self.cachePath=None self.config = RegistryConfig() #try: self.checkPreviousSetting() #except: #pass def checkPreviousSetting(self): self.defaultConfigPath() try: pathSettings=self.config.read([CONFIG]) if pathSettings: self.setUserConfigPath(pathSettings[CONFIG]) else: self.setUserConfigPath() except Exception as ex: pass def XMLFile(self): #this function returns the default xml file with configuration #self.setConfigPath() return self._file def cacheFile(self): #To implemented a backup file for comparing edits everytime the user makes changes path=self.userPath+'/temp/%s'%FILE return path def cacheDir(self): return self.cachePath def setCacheDir(self,path=None): if path: self.cachePath = self.userPath+"/%s"%path else: self.cachePath = self.userPath+"/temp" self.createDir(self.cachePath) def STDMSettingsPath(self): #To be implemented to write new file with user edits return self.userPath def HtmlFile(self): #Read the html representation of the schema self._html = self.userPath+'/%s'%HTML return self._html def SQLFile(self): #Read the html representation of the schema self._sql = self.userPath+'/%s'%SQL return self._sql def baseSQLPath(self): path= self.baseDir+'/%s'%FILE #path=self.userPath+'/temp/%s'%FILE return path def HelpContents(self): return self._file+'/%s'%HELP def defaultConfigPath(self): '''returns the path with configuration file''' self.baseDir = self._file+"/template/" def setUserConfigPath(self,path=None): ''' set new path with user configuration''' self.userPath = self.localPath() self.createDir(self.userPath) self.cachePath = self.userPath+'/temp' self.createDir(self.cachePath) self.userConfigPath() def userConfigPath(self,path=None): #Copy template files to the user directory try: for fileN in [FILE,HTML,SQL]: if not os.path.isfile(self.userPath+'/%s'%fileN): baseFile = self.baseDir +'/%s'%fileN shutil.copy(baseFile,self.userPath) if not os.path.isfile(self.cacheFile()): shutil.copy(self.setUserXMLFile(), self.cacheDir()) except IOError as ex: raise ex def setUserXMLFile(self): '''default path to the config file''' xml=self.userPath+'/%s'%FILE return xml def localPath(self): '''look for users path based on platform, need to implement for unix systems''' profPath=None if platform.system() == "Windows": userPath = os.environ["USERPROFILE"] profPath = userPath + "/.stdm" return str(profPath).replace("\\", "/") def setLocalPath(self,path=None): if path: self.userPath = path if not path: self.userPath = self.localPath() def createDir(self,dirPath): if os.access(dirPath, os.F_OK) == False: os.makedirs(dirPath) return dirPath def STDMLicenseDoc(self): '''load STDM license file for viewing''' return self._file+'/%s'%LICENSE def createBackup(self): '''incase the user want to keep track of the old file when current file changes''' if os.path.isfile(self.cacheFile()): os.remove(self.cacheFile()) #QMessageBox.information(None,'test',self.cachePath) shutil.copy(self.setUserXMLFile(), self.cacheDir())
def __init__(self,parent=None, args=None): self._doc='' self.args=args self.fileHandler=FilePaths() self.config = RegistryConfig()
class ConfigTableReader(object): def __init__(self,parent=None, args=None): self._doc='' self.args=args self.fileHandler=FilePaths() self.config = RegistryConfig() def tableListModel(self,profile): '''pass the table list to a listview model''' tData=self.tableNames(profile) if tData!= None: model=listEntityViewer(tData) return model else: return None def tableNames(self,profile): tData=XMLTableElement(profile) if tData is not None: # if "social_tenure" in tData: # tData.remove('social_tenure') return tData def fulltableList(self): tbList=tableLookUpCollection() if tbList is not None: return tbList def STDMProfiles(self): pfList=profiles() return pfList def lookupTableModel(self): model=listEntityViewer(self.lookupTable()) return model def lookupTable(self): return lookupTable() def lookupColumns(self,lookupName): columnModel=None tableAttrib=lookupColumn(lookupName) if len(tableAttrib)>0: colHeaders=tableAttrib[0].keys() colVals=[] for item in tableAttrib: colVals.append(item.values()) columnModel=EntityColumnModel(colHeaders,colVals) return columnModel else: return None def columns(self,profile,tableName): '''Functions to read columns details from the config for the given table''' columnModel = None tableAttrib = tableColumns(profile,tableName) if len(tableAttrib) > 0: colHeaders = tableAttrib[0].keys() colVals = [] for item in tableAttrib: colVals.append(item.values()) columnModel = EntityColumnModel(colHeaders, colVals) return columnModel else: return None def tableRelation(self,tableName): '''Method to read all defined table relationship in the config file''' relationModel = None tableAttrib = tableRelations(tableName,"relations") if tableAttrib is None: return tableAttrib if len(tableAttrib)>0: colHeaders = tableAttrib[0].keys() colVals = [] for item in tableAttrib: colVals.append(item.values()) relationModel = EntityColumnModel(colHeaders,colVals) return relationModel def geometryData(self,tableName): '''Method to read all defined table relationship in the config file''' geometryModel = None tableAttrib = geometryColumns(tableName, 'constraints') if tableAttrib == None: return tableAttrib if len(tableAttrib) > 0: colHeaders = tableAttrib[0].keys() colVals = [] for item in tableAttrib: colVals.append(item.values()) geometryModel = EntityColumnModel(colHeaders, colVals) return geometryModel def sqlTableDefinition(self): '''load the table definition info in html file''' docfile = self.fileHandler.SQLFile() return docfile def htmlTableDefinition(self): '''load the table definition info in html file''' docfile = self.fileHandler.HtmlFile() return docfile def userProfileDir(self): return self.fileHandler.STDMSettingsPath() def saveXMLchanges(self): writeSQLFile() writeHTML() def upDateSQLSchema(self): #To be implemented to allow updating of schema updateSQL() def setProfileSettings(self,profileData): '''write the current profile in Qsettings''' self.config.write(profileData) def settingsKeys(self): ''' Keys used to store directory paths in the database ''' return PATHKEYS def pathSettings(self): pathKeys = self.settingsKeys() pathSetting = self.config.read(pathKeys) return pathKeys, pathSetting def createDir(self, paths): if paths != None: for fPath in paths: self.fileHandler.createDir(fPath) def addLookupValue(self,table,valueText): setLookupValue(table,valueText) def readLookupList(self,table): lookupList=[] try: lookupList=lookupData(table) except: pass return lookupList def setDocumentationPath(self): '''get the help contents available to user''' helpFile=self.fileHandler.HelpContents() return helpFile def trackXMLChanges(self): self.fileHandler.createBackup()
def __init__(self): self.dbHost = "Host" self.dbPort = "Port" self.dbName = "Database" self.regConfig = RegistryConfig()
class ConfigTableReader(object): def __init__(self, parent=None, args=None): self._doc = '' self.args = args self.fileHandler = FilePaths() self.config = RegistryConfig() def tableListModel(self, profile): '''pass the table list to a listview model''' tData = self.tableNames(profile) if not tData is None: model = listEntityViewer(tData) return model else: return None def profile_tables(self, profile): table_desc = tableFullDescription(profile) if table_desc: headers = table_desc[0].keys() rowData = [row.values() for row in table_desc] table_desc_model = EntityColumnModel(headers, rowData) return table_desc_model def tableNames(self, profile): tbl_data = XMLTableElement(profile) if tbl_data is not None: # if "social_tenure" in tData: # tData.remove('social_tenure') return tbl_data def current_profile_tables(self): """ :return: Returns a list containing table names in the current profile. :rtype: list """ try: curr_profile = activeProfile() return self.tableNames(curr_profile) except ProfileException: raise def table_columns(self, table): """ :param table: Name of the table. :type table: str :return: Returns a list of the columns of the specified in order in which they were created. :rtype: list """ return tableCols(table) def fulltableList(self): tbList = tableLookUpCollection() if not tbList is None: return tbList def on_main_table_selection(self): """ Method required by the wizard for loading all the table in a model to a combo box :return: """ tbl_list= self.fulltableList() tbl_model = listEntityViewer(tbl_list) return tbl_model def STDMProfiles(self): pfList=profiles() return pfList def lookupTableModel(self): model=listEntityViewer(self.lookupTable()) return model def lookupTable(self): return lookupTable() def lookupColumns(self,lookupName): columnModel = None tableAttrib = lookupColumn(lookupName) if len(tableAttrib)>0: colHeaders = tableAttrib[0].keys() colVals= [] # [item.values for item in tableAttrib] for item in tableAttrib: colVals.append(item.values()) columnModel=EntityColumnModel(colHeaders,colVals) return columnModel else: return None def columns(self,profile,tableName): '''Functions to read columns details from the config for the given table''' columnModel = None tableAttrib = tableColumns(profile,tableName) if len(tableAttrib) > 0: colHeaders = tableAttrib[0].keys() colVals = [item.values() for item in tableAttrib] #for item in tableAttrib: # colVals.append(item.values()) columnModel = EntityColumnModel(colHeaders, colVals) return columnModel else: return None def column_labels(self,col_list): """ Method to read and return the defined column labels for the table as a model :param list: :return:Listmodel """ return listEntityViewer(col_list, icon=dataIcon) def table_searchable_columns(self, table): """ Method to read all searchable field from the config for the table :param table: :return:cols: List """ return table_searchable_cols(table) def social_tenure_tables(self): """ Method to read all tables participating in STR :return:tables: List """ if not social_tenure_tables(activeProfile()): return [] else: return social_tenure_tables(activeProfile()) def tableRelation(self,tableName): '''Method to read all defined table relationship in the config file''' relationModel = None tableAttrib = tableRelations(tableName,"relations") if tableAttrib is None: return tableAttrib if len(tableAttrib)>0: colHeaders = tableAttrib[0].keys() colVals = [] for item in tableAttrib: colVals.append(item.values()) relationModel = EntityColumnModel(colHeaders,colVals) return relationModel def geometry_collection(self,tableName): '''Method to read all defined table relationship in the config file''' geometryModel = None geomAttrib = geometryColumns(tableName, 'geometryz') if geomAttrib == None: return geomAttrib if len(geomAttrib) > 0: colHeaders = geomAttrib[0].keys() colVals = [] for item in geomAttrib: colVals.append(item.values()) geometryModel = EntityColumnModel(colHeaders, colVals) return geometryModel def sqlTableDefinition(self): '''load the table definition info in html file''' docfile = self.fileHandler.SQLFile() return docfile def htmlTableDefinition(self): '''load the table definition info in html file''' docfile = self.fileHandler.HtmlFile() return docfile def userProfileDir(self): return self.fileHandler.STDMSettingsPath() def updateDir(self, path): return self.fileHandler.userConfigPath(path) def saveXMLchanges(self): writeSQLFile() writeHTML() def upDateSQLSchema(self): #To be implemented to allow updating of schema updateSQL() def setProfileSettings(self,profileData): '''write the current profile in Qsettings''' self.config.write(profileData) def settingsKeys(self): ''' Keys used to store directory paths in the database ''' return PATHKEYS def pathSettings(self): pathKeys = self.settingsKeys() pathSetting = self.config.read(pathKeys) return pathKeys, pathSetting def createDir(self, paths): if paths != None: for fPath in paths: self.fileHandler.createDir(fPath) def addLookupValue(self,table,valueText): setLookupValue(table,valueText) def readLookupList(self,table): lookupList=[] try: lookupList=lookupData(table) except: pass lookupModel = listEntityViewer(lookupList, icon=dataIcon) return lookupModel def setDocumentationPath(self): '''get the help contents available to user''' helpFile=self.fileHandler.HelpContents() return helpFile def trackXMLChanges(self): self.fileHandler.createBackup() def check_config_version(self, path): self.fileHandler.compare_config_version(path) def active_profile(self): return activeProfile() def selected_table_columns(self, table): """ Method to return the selected table colums as alist :param table name STR: :return: List """ return tableCols(table) def update_str_tables(self, table,level): set_str_tables(activeProfile(),table,level) def set_str_type_collection(self,table, optiontype): """ Method to update the config to show the str type of individual str table :param table: :return: """ str_type_tables(activeProfile(), table, optiontype) def set_table_str_columns(self, table, collist): """ Method to set all the tables column participating in STR :param table: :return: """ str_col_collection(activeProfile(),table,collist) def social_tenure_col(self,table): """ Method to read str columns from config :param table: :return: """ return read_social_relation_cols(table) def social_tenure_table_types(self): """ Method to read and return the party and spatial unit str tables respectively :return:String """ return social_tenure_tables_type(activeProfile()) def read_config_version(self): """ Method to read and return the config version to avoid obsolete method returning none :return: """ return config_version() def update_config_file(self): """ Try and update the config file if old one is detected :return: """ self.fileHandler.change_config() def chect_table_exist(self, table): """ If the table is already defined in config :return: """ if current_table_exist(table): return True else: return False
class FilePaths(object): def __init__(self, path=None): self._file = PLUGIN_DIR self.baseDir = None self._html = '' self._sql = '' self.userPath = None self.cachePath = None self.config = RegistryConfig() self.checkPreviousSetting() def checkPreviousSetting(self): self.defaultConfigPath() try: pathSettings = self.config.read([CONFIG]) if pathSettings: self.setUserConfigPath(pathSettings[CONFIG]) else: self.setUserConfigPath() except Exception as ex: raise ex def XMLFile(self): #this function returns the default xml file with configuration #self.setConfigPath() return self._file def cacheFile(self): #To implemented a backup file for comparing edits everytime the user makes changes path = self.userPath+'/temp/%s'%DEFAULT_CONFIG return path def cacheDir(self): return self.cachePath def setCacheDir(self,path=None): if path: self.cachePath = self.userPath+"/%s"%path else: self.cachePath = self.userPath+"/temp" self.createDir(self.cachePath) def STDMSettingsPath(self): #To be implemented to write new file with user edits return self.userPath def HtmlFile(self): #Read the html representation of the schema self._html = self.userPath+'/%s'%HTML return self._html def SQLFile(self): #Read the html representation of the schema self._sql = self.userPath+'/%s'%BASIC_SQL return self._sql def baseSQLPath(self): path= self.baseDir+'/%s'%DEFAULT_CONFIG #path=self.userPath+'/temp/%s'%FILE return path def HelpContents(self): """Method to load help contents file""" return self._file+'/%s'%HELP def defaultConfigPath(self): """ returns the path with base configuration file """ self.baseDir = self._file+"/template/" def setUserConfigPath(self,path=None): ''' set new path with user configuration''' if path is not None: self.userPath= path else: self.userPath = self.localPath() self.createDir(self.userPath) self.cachePath = self.userPath+'/temp' self.createDir(self.cachePath) self.userConfigPath(self.userPath) def userConfigPath(self,path=None): #Copy template files to the user directory try: #self.compare_config_version(FILE) for fileN in [DEFAULT_CONFIG, BASIC_SQL]: if not os.path.isfile(path+'/%s'%fileN): baseFile = self.baseDir +'/%s'%fileN shutil.copy(baseFile,self.userPath) if not os.path.isfile(self.cacheFile()): self.createBackup() self.localFontPath(path) except IOError as io: raise io def compare_config_version(self, path = None): """ Method to check the version of the two files being copied and return the latest one :param newfile: QFile :return: QFile """ if not path: path = self.userPath else: path = path base_file = self.baseSQLPath() user_file = path +'/%s'%DEFAULT_CONFIG if os.path.isfile(user_file): if QMessageBox.warning(None, QApplication.translate("FilePaths","Previous user configuration found"), QApplication.translate("FilePaths", "Wizard detected previous configuration exists in the current directory." "\nDo you want to overwrite the existing config?"), QMessageBox.Yes| QMessageBox.No) == QMessageBox.Yes: if filecmp.cmp(base_file, user_file, shallow=False): pass else: try: os.remove(user_file) shutil.copy(base_file, self.userPath) except: pass else: QMessageBox.information(None, QApplication.translate("FilePaths","Configuration Exist"), QApplication.translate("FilePaths","Previous configuration retained")) else: shutil.copy(base_file, user_file) self.createBackup() def localFontPath(self, path): """ Create a path where fonts will be stored""" if path == None: if platform.system() == "Windows": path = os.environ["USERPROFILE"] else: path = os.getenv("HOME") fontPath = path + "/.stdm/font.cache" else: fontPath = str(path).replace("\\", "/")+"/font.cache" SysFonts.register(fontPath) def setUserXMLFile(self): """ Default path to the config file """ xml = self.userPath +'/%s'%DEFAULT_CONFIG return xml def localPath(self): """ Look for users path based on platform, need to implement for unix systems :return: """ profPath = None if platform.system() == "Windows": userPath = os.environ["USERPROFILE"] profPath = userPath + "/.stdm" else: profPath = str(os.getenv('HOME'))+"/.stdm" return str(profPath).replace("\\", "/") def setLocalPath(self, path=None): if path: self.userPath = path if not path: self.userPath = self.localPath() def createDir(self, dirPath): if not os.access(dirPath, os.F_OK): os.makedirs(dirPath) else: return dirPath def STDMLicenseDoc(self): """ load STDM license file for viewing """ return self._file+'/%s'%LICENSE def createBackup(self): """ Incase the user want to keep track of the old file when current file changes :return: """ if os.path.isfile(self.cacheFile()): os.remove(self.cacheFile()) shutil.copy(self.setUserXMLFile(), self.cacheDir()) def change_config(self): """ Method to update the config file the detected one is old :return: """ base_file = self.baseSQLPath() cur_file = self.setUserXMLFile() try: if os.path.isfile(cur_file): os.remove(cur_file) shutil.copy(base_file, self.userPath) except: pass
def reg_setting(self): connSettings = ['Host', 'Database', 'Port'] set_conn = RegistryConfig() settings = set_conn.read(connSettings) return settings