Python qgis.core.Qgis.Critical() Examples

The following are 30 code examples of qgis.core.Qgis.Critical(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module qgis.core.Qgis , or try the search function .
Example #1
Source File: logger.py    From orstools-qgis-plugin with MIT License 6 votes vote down vote up
def log(message, level_in=0):
    """
    Writes to QGIS inbuilt logger accessible through panel.

    :param message: logging message to write, error or URL.
    :type message: str

    :param level_in: integer representation of logging level.
    :type level_in: int
    """
    if level_in == 0:
        level = Qgis.Info
    elif level_in == 1:
        level = Qgis.Warning
    elif level_in == 2:
        level = Qgis.Critical
    else:
        level = Qgis.Info

    QgsMessageLog.logMessage(message, PLUGIN_NAME.strip(), level) 
Example #2
Source File: manageServerUsers.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def on_removeUserButton_clicked(self):
        selectedUsers = self.serverUserTable.selectedItems()
        if not self.abstractDb:
            QMessageBox.critical(self, self.tr('Critical!'), self.tr('First select a database!'))
            return
        if len(selectedUsers) == 0:
            QMessageBox.critical(self, self.tr('Critical!'), self.tr('First select a user to remove!'))
            return
        selectedUserNames = [i.text(0) for i in selectedUsers]
        if QMessageBox.question(self, self.tr('Question'), self.tr('Do you really want to remove users: ')+', '.join(selectedUserNames), QMessageBox.Ok|QMessageBox.Cancel) == QMessageBox.Cancel:
            return
        exceptionDict = dict()
        successList = []
        for user in selectedUserNames:
            try:
                self.abstractDb.reassignAndDropUser(user)
                successList.append(user)
            except Exception as e:
                exceptionDict[user] =  ':'.join(e.args)
        header = self.tr('Drop user(s) operation complete!\n')
        self.outputMessage(header, successList, exceptionDict)
        self.populateUsers() 
Example #3
Source File: datasourceConversion.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def validate(self):
        """
        Verifies contents displayed on mapping table in order to infer its validity
        as datasource conversion map.
        :return: (bool) map validity status.
        """
        # validate map
        msg = self.invalidatedReason()
        if msg:
            # if an invalidation reason was given, warn user and nothing else.
            msgBar = QgsMessageBar(self)
            # if window is resized, msgBar stays, not ideal, but works for now
            # maybe we should connect to some parent resizing signal or something...
            msgBar.resize(QSize(self.geometry().size().width(), msgBar.geometry().height()))
            msgBar.pushMessage(self.tr('Warning!'), msg, level=Qgis.Warning, duration=5)
            QgsMessageLog.logMessage(msg, 'DSGTools Plugin', Qgis.Critical)
        return msg == '' 
Example #4
Source File: newDatabaseLineEdit.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def loadDatabase(self, currentText):
        """
        Loads the selected database.
        currentText: (str) text as shown on datasource combo box.
        """
        try:
            if not self.currentDb():
                # in case no datasource was selected
                return
            self.setAbstractDb()
            msg = self.validate()
            self.dbChanged.emit(self.abstractDb)
            self.connectionChanged.emit()
            # if msg:
            #     raise Exception(msg)
        except Exception as e:
            self.problemOccurred.emit(self.tr('A problem occurred! Check log for details.'))
            QgsMessageLog.logMessage(':'.join(e.args), "DSGTools Plugin", Qgis.Critical) 
Example #5
Source File: newConnectionLineEdit.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def loadDatabase(self, currentText):
        """
        Loads the selected database
        """
        try:
            if not self.currentDb():
                # in case no datasource was selected
                return
            self.setAbstractDb()
            msg = self.validate()
            self.dbChanged.emit(self.abstractDb)
            self.connectionChanged.emit()
            # if msg:
            #     raise Exception(msg)
        except Exception as e:
            self.problemOccurred.emit(self.tr('A problem occurred! Check log for details.'))
            QgsMessageLog.logMessage(':'.join(e.args), "DSGTools Plugin", Qgis.Critical) 
Example #6
Source File: connectionComboBox.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def loadDatabase(self, idx):
        """
        Loads the selected database
        """
        try:
            if self.abstractDb is not None:
                self.closeDatabase()
            if self.serverAbstractDb is not None and idx > 0:
                if not self.instantiateAbstractDb:
                    self.abstractDb = self.abstractDbFactory.createDbFactory(DsgEnums.DriverPostGIS)
                    (host, port, user, password) = self.serverAbstractDb.getDatabaseParameters()
                    dbName = self.connectionSelectorComboBox.itemText(idx).split(' (')[0]
                    self.abstractDb.connectDatabaseWithParameters(host, port, dbName, user, password)
                    self.abstractDb.checkAndOpenDb()
                    self.dbChanged.emit(self.abstractDb)
                    self.connectionChanged.emit()
        except Exception as e:
            self.closeDatabase()
            self.problemOccurred.emit(self.tr('A problem occurred! Check log for details.'))
            QgsMessageLog.logMessage(':'.join(e.args), "DSGTools Plugin", Qgis.Critical) 
Example #7
Source File: connectionComboBox.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def setServerDb(self, serverAbstractDb):
        self.serverAbstractDb = serverAbstractDb
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            if self.serverAbstractDb:
                dbList = self.serverAbstractDb.getEDGVDbsFromServer(parentWidget = self.parent, getDatabaseVersions = False)
                dbList.sort()
                self.clear()
                self.connectionSelectorComboBox.addItem(self.tr('Select Database'))
                self.addItems(dbList)
            else:
                self.clear()
                self.abstractDb = None
                QApplication.restoreOverrideCursor()
                return
        except Exception as e:
            QApplication.restoreOverrideCursor()
            QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))
        QApplication.restoreOverrideCursor() 
Example #8
Source File: databaseFileLineEdit.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def loadDatabase(self, currentText):
        """
        Loads the selected database
        """
        try:
            if not self.currentDb():
                # in case no datasource was selected
                self.closeDatabase()
            elif not self.instantiateAbstractDb:
                self.abstractDb = self.abstractDbFactory.createDbFactory(self.driver)
                self.abstractDb.connectDatabase(conn=currentText)
                self.abstractDb.checkAndOpenDb()
                self.dbChanged.emit(self.abstractDb)
                self.connectionChanged.emit()
        except Exception as e:
            self.closeDatabase()
            self.problemOccurred.emit(self.tr('A problem occurred! Check log for details.'))
            QgsMessageLog.logMessage(':'.join(e.args), "DSGTools Plugin", Qgis.Critical) 
Example #9
Source File: exploreServerWidget.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def getDbsFromServer(self, name):
        """
        Gets server databases
        name: server name
        """
        gen = self.factory.createSqlGenerator(driver=DsgEnums.DriverPostGIS)
        
        (host, port, user, password) = self.getServerConfiguration(name)
        database = 'postgres'
        postgisDb = self.dbFactory.createDbFactory(DsgEnums.DriverPostGIS)
        postgisDb.connectDatabaseWithParameters(host, port, database, user, password)
        if not postgisDb.db.open():
            QgsMessageLog.logMessage(db.lastError().text(), "DSGTools Plugin", Qgis.Critical)
            QMessageBox.critical(self.iface.mainWindow(), self.tr('Critical'), self.tr('A problem occurred! Check log for details.'))
        
        query = QSqlQuery(gen.getDatabasesFromServer(), postgisDb.db)
        if not query.isActive():
            QMessageBox.critical(self.iface.mainWindow(), self.tr('Critical'), self.tr("Problem executing query: ")+query.lastError().text())
            
        dbList = []
        while query.next():
            dbList.append(query.value(0))
        postgisDb.closeDatabase()
        return self.browseServer(dbList, host, port, user, password) 
Example #10
Source File: flipLineTool.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def flipSelectedLines(self):
        """
        Method for flipping all selected lines. Used for button callback.
        """        
        # get all selected features and remove all features that are not lines
        selectedFeatures = self.getAllSelectedLines()
        pop = 0
        for idx, item in enumerate(selectedFeatures):
            if item[2] != 1:
                selectedFeatures.pop(idx-pop)
                pop += 1
        if not selectedFeatures:
            logMsg = self.getLogMessage(None, None)
            self.iface.messageBar().pushMessage(self.tr('Error'), logMsg, level=Qgis.Critical, duration=3)
            # QMessageBox.critical(self, self.tr('Critical!'), logMsg)
            QgsMessageLog.logMessage(logMsg, "DSGTools Plugin", Qgis.Critical)
            return
        # call the method for flipping features from geometry module
        flippedLines, failedLines = self.DsgGeometryHandler.flipFeatureList(featureList=selectedFeatures, debugging=True)
        logMsg = self.getLogMessage(flippedLines, failedLines)
        self.iface.messageBar().pushMessage(self.tr('Success'), logMsg, level=Qgis.Info, duration=3)
        QgsMessageLog.logMessage(logMsg, "DSGTools Plugin", Qgis.Info) 
Example #11
Source File: connectionWidget.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def getDatabasesFromServer(self):
        """
        Gets databases from server
        """  
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            if self.serverWidget.abstractDb:
                dbList = self.serverWidget.abstractDb.getEDGVDbsFromServer(parentWidget = self)
                dbList.sort()
                self.comboBoxPostgis.clear()
                self.comboBoxPostgis.addItem(self.tr('Select Database'))
                for db, version in dbList:
                    self.comboBoxPostgis.addItem(db)
                
            else:
                self.setInitialState()
                QApplication.restoreOverrideCursor()
                return
        except Exception as e:
            QApplication.restoreOverrideCursor()
            QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))
            self.setInitialState()
        QApplication.restoreOverrideCursor() 
Example #12
Source File: viewServers.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def testServer(self, name):
        '''
        Tests if the server is online
        '''
        abstractDb = self.abstractDbFactory.createDbFactory(DsgEnums.DriverPostGIS)
        if not abstractDb:
            QMessageBox.critical(self, self.tr('Critical!'), self.tr('A problem occurred! Check log for details.'))
            return False
        (host, port, user, password) = abstractDb.getServerConfiguration(name)
        abstractDb.connectDatabaseWithParameters(host, port, 'postgres', user, password)
        try:
            abstractDb.checkAndOpenDb()
            abstractDb.closeDatabase()
            return True
        except Exception as e:
            QMessageBox.critical(self, self.tr('Critical!'), self.tr('A problem occurred! Check log for details.'))
            QgsMessageLog.logMessage(':'.join(e.args), 'DSGTools Plugin', Qgis.Critical)
            abstractDb.closeDatabase()
            return False 
Example #13
Source File: exceptions.py    From qfieldsync with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, message, exception=None, long_message=None, tag="QFieldSync"):
        """
        an Exception that automatically logs the error to the QgsMessageLog
        :param exception:
        :param message: a short message to be logged and used by str()
        :param long_message: a longer message only shown in the log
        """

        # Call the base class constructor with the parameters it needs
        super(QFieldSyncError, self).__init__(message)

        self.message = message
        self.exception = exception
        self.long_message = long_message

        log_message = self.message

        if self.long_message is not None:
            log_message = "\nDetails:\n %s" % self.long_message

        if self.exception is not None:
            log_message = "\nException:\n %s" % self.long_message

        QgsMessageLog.logMessage(log_message, tag, Qgis.Critical) 
Example #14
Source File: spatialiteLayerLoader.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, iface, abstractDb, loadCentroids):
        """Constructor."""
        super(SpatialiteLayerLoader, self).__init__(iface, abstractDb, loadCentroids)
        
        self.provider = 'spatialite'
        
        try:
            dbVersion = abstractDb.getDatabaseVersion()
        except Exception as e:
            QgsMessageLog.logMessage(':'.join(e.args), 'DSGTools Plugin', Qgis.Critical)
            return

        self.buildUri() 
Example #15
Source File: spatialiteLayerLoader.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def loadLayer(self, inputParam, parentNode, uniqueLoad, stylePath, domLayerDict):
        """
        Loads a layer
        :param lyrName: Layer nmae
        :param idSubgrupo: sub group id
        :param uniqueLoad: boolean to mark if the layer should only be loaded once
        :param stylePath: path to the styles used
        :param domLayerDict: domain dictionary
        :return:
        """
        lyrName, schema, geomColumn, tableName, srid = self.getParams(inputParam)
        lyr = self.checkLoaded(tableName)
        if uniqueLoad and lyr:
            return lyr
        self.setDataSource('', '_'.join([schema,tableName]), geomColumn, '')

        vlayer = QgsVectorLayer(self.uri.uri(), tableName, self.provider)
        QgsProject.instance().addMapLayer(vlayer, addToLegend = False)
        crs = QgsCoordinateReferenceSystem(int(srid), QgsCoordinateReferenceSystem.EpsgCrsId)
        vlayer.setCrs(crs)
        vlayer = self.setDomainsAndRestrictionsWithQml(vlayer)
        vlayer = self.setMulti(vlayer,domLayerDict)
        if stylePath:
            fullPath = self.getStyle(stylePath, tableName)
            if fullPath:
                vlayer.loadNamedStyle(fullPath, True)
        parentNode.addLayer(vlayer) 
        if not vlayer.isValid():
            QgsMessageLog.logMessage(vlayer.error().summary(), "DSGTools Plugin", Qgis.Critical)
        vlayer = self.createMeasureColumn(vlayer)
        return vlayer 
Example #16
Source File: shapefileLayerLoader.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, iface, abstractDb):
        """
        Class constructor.
        :param iface: (QgsInterface) QGIS interface to be used to get runtime access to layers/features.
        :param abstractDb: (AbstractDb) database object as designed in DSGTools plugin. Check driver concordance.
        """
        # no reason for centroids to be used, so it'll be set to False always (parent requirement to init)
        super(ShapefileLayerLoader, self).__init__(iface, abstractDb, False)
        self.provider = 'shapefile'
        try:
            dbVersion = abstractDb.getDatabaseVersion()
        except Exception as e:
            QgsMessageLog.logMessage(':'.join(e.args), 'DSGTools Plugin', Qgis.Critical)
            return
        self.buildUri() 
Example #17
Source File: geopackageLayerLoader.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, iface, abstractDb, loadCentroids):
        """Constructor."""
        super(GeopackageLayerLoader, self).__init__(iface, abstractDb, loadCentroids)
        
        self.provider = 'geopackage'
        
        try:
            dbVersion = abstractDb.getDatabaseVersion()
        except Exception as e:
            QgsMessageLog.logMessage(':'.join(e.args), 'DSGTools Plugin', Qgis.Critical)
            return

        self.buildUri() 
Example #18
Source File: geopackageLayerLoader.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def loadLayer(self, inputParam, parentNode, uniqueLoad, stylePath, domLayerDict):
        """
        Loads a layer
        :param lyrName: Layer nmae
        :param idSubgrupo: sub group id
        :param uniqueLoad: boolean to mark if the layer should only be loaded once
        :param stylePath: path to the styles used
        :param domLayerDict: domain dictionary
        :return:
        """
        lyrName, schema, geomColumn, tableName, srid = self.getParams(inputParam)
        lyr = self.checkLoaded(tableName)
        if uniqueLoad and lyr:
            return lyr
        vlayer = self.getLayerByName("{0}_{1}".format(schema, tableName))
        if not vlayer.isValid():
            QgsMessageLog.logMessage(vlayer.error().summary(), "DSGTools Plugin", Qgis.Critical)
        QgsProject.instance().addMapLayer(vlayer, addToLegend = False)
        crs = QgsCoordinateReferenceSystem(int(srid), QgsCoordinateReferenceSystem.EpsgCrsId)
        vlayer.setCrs(crs)
        vlayer = self.setDomainsAndRestrictionsWithQml(vlayer)
        vlayer = self.setMulti(vlayer,domLayerDict)
        if stylePath:
            fullPath = self.getStyle(stylePath, tableName)
            if fullPath:
                vlayer.loadNamedStyle(fullPath, True)
        parentNode.addLayer(vlayer)
        vlayer = self.createMeasureColumn(vlayer)
        return vlayer 
Example #19
Source File: dbCreatorFactory.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def createDbCreatorFactory(self, driverName, createParam, parentWidget = None):
        #TODO Treat none return
        if not ('QPSQL' in QSqlDatabase.drivers()): #Driver wasn't loaded
            QgsMessageLog.logMessage('QT PSQL driver not installed!', 'DSGTools Plugin', Qgis.Critical)
            return None
        if not ('QSQLITE' in QSqlDatabase.drivers()): #Driver wasn't loaded
            QgsMessageLog.logMessage('QT QSQLITE driver not installed!', 'DSGTools Plugin', Qgis.Critical)
            return None        
        creators = {
            "QSQLITE" : SpatialiteDbCreator,
            "QPSQL" : PostgisDbCreator,
            "GPKG" : GeopackageDbCreator
        }
        return creators[driverName](createParam, parentWidget) if driverName in creators else None 
Example #20
Source File: log.py    From raster-vision-qgis with GNU General Public License v3.0 5 votes vote down vote up
def log_error(cls, msg):
        QgsMessageLog.logMessage(msg, tag="Raster Vision", level=Qgis.Critical) 
Example #21
Source File: workflowSetupDialog.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def import_(self):
        """
        Request a file for Workflow importation and sets it to GUI.
        :return: (bool) operation status.
        """
        fd = QFileDialog()
        filename = fd.getOpenFileName(
            caption=self.tr('Select a Workflow file'),
            filter=self.tr('DSGTools Workflow (*.workflow *.json)')
        )
        filename = filename[0] if isinstance(filename, tuple) else ""
        if not filename:
            return False
        try:
            self.importWorkflow(filename)
        except Exception as e:
            self.messageBar.pushMessage(
                self.tr('Invalid workflow'),
                self.tr("Unable to export workflow to '{fp}' ({error}).").format(
                    fp=filename, error=str(e)
                ),
                level=Qgis.Critical,
                duration=5
            )
            return False
        self.messageBar.pushMessage(
            self.tr('Success'),
            self.tr("Workflow '{fp}' imported!").format(
                fp=filename
            ),
            level=Qgis.Info,
            duration=5
        )
        return True 
Example #22
Source File: field_toolbox.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def defineFactory(self, abstractDb):
        """
        Defines the layer loader by its type
        :param abstractDb:
        :return:
        """
        if abstractDb.db.databaseName() == "":
            return
        self.layerLoader = LayerLoaderFactory().makeLoader(self.iface, abstractDb)
        try:
            self.populateConfigFromDb()
        except Exception as e:
            QgsMessageLog.logMessage(self.tr('Error getting stored configuration.\n')+':'.join(e.args), "DSGTools Plugin", Qgis.Critical) 
Example #23
Source File: calc_contour.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def updateLayer(self, geom):
        """
        Updates the layer
        """
        if self.layerCombo.currentIndex() == 0:
            self.iface.messageBar().pushMessage(self.tr('Information'), self.tr('A layer must be selected!'), level=Qgis.Info, duration=3)
            return

        if self.attributeCombo.currentIndex() == 0:
            self.iface.messageBar().pushMessage(self.tr('Information'), self.tr('A field must be selected!'), level=Qgis.Info, duration=3)
            return

        #canvas crs to be used in case a reprojection is needed
        canvasCrs = self.iface.mapCanvas().mapSettings().destinationCrs()
        if self.ascendingRadioButton.isChecked():
            signal = 1
        else:
            signal = -1
        ret = self.contourTool.assignValues(self.attributeCombo.currentText(), signal*self.spinBox.value(), geom, canvasCrs)
        self.iface.mapCanvas().refresh()
        if ret == 1:
            self.iface.messageBar().pushMessage(self.tr('Information!'), self.tr('Layer successfully updated!'), level=Qgis.Info, duration=3)
        elif ret == 0:
            self.iface.messageBar().pushMessage(self.tr('Critical!'), self.tr('Could not update features!'), level=Qgis.Critical, duration=3)
        elif ret == -1:
            self.iface.messageBar().pushMessage(self.tr('Critical!'), self.tr('Problem ordering the features!'), level=Qgis.Critical, duration=3)
        elif ret == -2:
            self.iface.messageBar().pushMessage(self.tr('Critical!'), self.tr('The line created does not cross any features in the selected layer!'), level=Qgis.Critical, duration=3)
        elif ret == -3:
            self.iface.messageBar().pushMessage(self.tr('Critical!'), self.tr('Assign a value for the selected attribute of the first crossed feature!'), level=Qgis.Critical, duration=3) 
Example #24
Source File: profileUserManager.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def logInternalError(self, exceptionDict):
        msg = ''
        errorDbList = list(exceptionDict.keys())
        if len(errorDbList)> 0:
            msg += self.tr('\nUsers with error:')
            msg+= ', '.join(errorDbList)
            msg+= self.tr('\nError messages for each user were output in qgis log.')
            for errorDb in errorDbList:
                QgsMessageLog.logMessage(self.tr('Error for user ')+ errorDb + ': ' +exceptionDict[errorDb], "DSGTools Plugin", Qgis.Critical)
        return msg 
Example #25
Source File: mainPlugin.py    From PyRAT with Mozilla Public License 2.0 5 votes vote down vote up
def finished(self, result):
        """
        This function is threadsafe for GUI-Actions and
        called after run terminates.
        """
        if self.guionly:
            self.pyratTool.guirun(iface.mainWindow())

        if result and not self.failed:
            iface.messageBar().pushMessage(self.pyratTool.name + " finished.",
                                           level=Qgis.Success)

            for layer in [newlayer for newlayer in pyrat.data.getLayerIDs()
                          if newlayer not in self.existinglayers]:
                # Show the generated Layer(s) in QGIS
                anno = pyrat.data.getAnnotation(layer=layer)
                if 'info' not in anno:
                    anno['info'] = "Pyrat-Layer " + layer
                pyrat.data.setAnnotation({'info': anno['info'] + "-" +
                                          self.pyratTool.name},
                                         layer=layer)
                ViewerToQGISInterface.display[layer] = {'scaling': 'min->max',
                                                        'bwlayer': layer,
                                                        'colour': False}
                PyRATBridge.pyratToLayer(self.layer)
            PyRATBridge.layerTreeWidget.redraw()
        else:
            iface.messageBar().pushMessage(self.pyratTool.name +
                                           " failed. Look in the (system)" +
                                           " console for more information.",
                                           level=Qgis.Critical)
        del self.plugin 
Example #26
Source File: dbProfileManager.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def logInternalError(self, exceptionDict):
        msg = ''
        errorDbList = list(exceptionDict.keys())
        if len(errorDbList)> 0:
            msg += self.tr('\Profiles with error:')
            msg+= ', '.join(errorDbList)
            msg+= self.tr('\nError messages for each profile were output in qgis log.')
            for errorDb in errorDbList:
                QgsMessageLog.logMessage(self.tr('Error for profile ')+ errorDb + ': ' +exceptionDict[errorDb], "DSGTools Plugin", Qgis.Critical)
        return msg 
Example #27
Source File: alter_user_password.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def alterDatabasePassword(self, user, newpassword):
        """
        Alters the password of a specific user
        """
        try:
            self.abstractDb.alterUserPass(self.user, newpassword)
        except Exception as e:
            QMessageBox.critical(self, self.tr('Critical!'), e.args[0])
            return
        QMessageBox.warning(self, self.tr('Success!'), self.tr('User ') +self.user+self.tr(' password successfully updated on database ')+self.abstractDb.getDatabaseName()+'!') 
Example #28
Source File: exploreServerWidget.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def browseServer(self, dbList, host, port, user, password):
        """
        Browses server for EDGV databases
        dbList: databases list
        host: server host ip address
        port: server port
        user: user name
        password: password
        """
        canLoad = True
        if self.superNeeded:
            canLoad = False
            try:
                if self.serverWidget.abstractDb.checkSuperUser():
                    canLoad = True
                else:
                    QMessageBox.warning(self, self.tr('Info!'), self.tr('Connection refused. Connect with a super user to inspect server.'))
                    return []
            except Exception as e:
                QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))
        if canLoad:
            progress = ProgressWidget(1,len(dbList),self.tr('Loading databases from server... '), parent = self)
            progress.initBar()
            gen = self.factory.createSqlGenerator(driver=DsgEnums.DriverPostGIS)
            edvgDbList = []
            for database in dbList:
                postgisDb = self.dbFactory.createDbFactory(DsgEnums.DriverPostGIS)
                postgisDb.connectDatabaseWithParameters(host, port, database, user, password)
                if not postgisDb.db.open():
                    qgis.utils.iface.messageBar().pushMessage('DB :'+database+'| msg: '+postgisDb.db.lastError().databaseText(), level=Qgis.Critical)
    
                query = QSqlQuery(postgisDb.db)
                if query.exec_(gen.getEDGVVersion()):
                    while query.next():
                        version = query.value(0)
                        if version:
                            edvgDbList.append((database, version))
                progress.step()
            return edvgDbList 
Example #29
Source File: __init__.py    From qgis-geoserver-plugin with GNU General Public License v2.0 5 votes vote down vote up
def setError(msg, trace=None):
    iface.messageBar().pushMessage("Geoserver", msg, level=Qgis.Warning, duration=10)
    if trace is not None:
        QgsMessageLog.logMessage("{}:{}".format(msg, trace), level=Qgis.Critical) 
Example #30
Source File: batchDbManager.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def populateListWithDatabasesFromServer(self):
        try:
            dbList = self.serverWidget.abstractDb.getEDGVDbsFromServer(parentWidget = self)
        except Exception as e:
            QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))

        dbList.sort()
        for (dbname, dbversion) in dbList:
            if dbversion not in list(self.dbDict.keys()):
                dbversion = 'Non_EDGV'
            if dbname not in self.dbDict[dbversion]:
                self.dbDict[dbversion].append(dbname)