def updateRequest(self, team_id, requestDict):
        '''
        Method to a update a request in missions_request table
        @param team_id: team_id code e.g index in DB table of the team... as returned by rest api
        @param requestDict: request dictiionary - keys have to be the same key of Db
        '''
        self.checkConnection()
        
        # preare dictionary to be used for DB
        requestOdered = self.prepareRequestDict(team_id, requestDict)

        # create query
        sqlquery = "UPDATE missions_request SET "
        for k,v in requestOdered.items():
            if k == "id":
                continue
            sqlquery += '%s=%s, ' % (k,adapt(v))
        sqlquery = sqlquery[0:-2] + " "
        sqlquery += "WHERE id=%s" % adapt(requestOdered["id"])
        
        QgsLogger.debug(self.tr("Aggiorna request con la query: %s" % sqlquery), 1 )
        try:
            
            self.cursor.execute(sqlquery)
            
        except Exception as ex:
            raise(ex)
 def loadRequests(self, indexes=None):
     '''
     Method to a load requests from missions_request table based on idexes
     @param indexes: list of index to retrieve. If empty then retrieve all
     @return requests: list of dict of the retrieved records
     '''
     self.checkConnection()
 
     # create query
     sqlquery = "SELECT * FROM missions_request "
     if (indexes != None) and (len(indexes) > 0):
         sqlquery += "WHERE "
         for index in indexes:
             sqlquery += "id='%s' OR " % adapt(index)
         sqlquery = sqlquery[0:-4] + " "
     sqlquery += "ORDER BY id;"
     
     QgsLogger.debug(self.tr("Recupera le request con la query: %s" % sqlquery), 1 )
     try:
         
         self.cursor.execute(sqlquery)
         columnNames = [descr[0] for descr in self.cursor.description]
         
         requests = []
         for values in self.cursor:
             requests.append( dict(zip(columnNames, values)) )
         
         return requests
         
     except Exception as ex:
         raise(ex)
    def updateTeam(self, teamDict):
        '''
        Method to a update a team in organization_team table
        @param teamDict: team dictiionary - keys have to be the same key of Db
        '''
        self.checkConnection()
        
        # preare dictionary to be used for DB
        teamOdered = self.prepareTeamDict(teamDict)

        # create query
        sqlquery = "UPDATE organization_team SET "
        for k,v in teamOdered.items():
            if k == "id":
                continue
            sqlquery += '%s=%s, ' % (k,adapt(v))
        sqlquery = sqlquery[0:-2] + " "
        sqlquery += "WHERE id=%s" % adapt(teamOdered["id"])
        
        QgsLogger.debug(self.tr("Aggiorna team con la query: %s" % sqlquery), 1 )
        try:
            
            self.cursor.execute(sqlquery)
            
        except Exception as ex:
            raise(ex)
    def fab_10kByPoint(self, point):
        '''
        Method to a load a record from fab_10k basing on geometry point
        @param point: where to find features
        @return fab_10k: list of dict of the retrieved records
        '''
        self.checkConnection()

        sqlquery = '''
            SELECT
                *
            FROM
                fab_10k 
            WHERE 
                ST_Contains(the_geom, ST_GeometryFromText('POINT(%s %s)', %s));
            ''' % ( point.x(), point.y(), gw.instance().GEODBDEFAULT_SRID )

        QgsLogger.debug(self.tr("Recupera fab_10k con la query: %s" % sqlquery), 1 )
        try:
            
            self.cursor.execute(sqlquery)
            columnNames = [descr[0] for descr in self.cursor.description]
            safeties = []
            for values in self.cursor:
                listValues = [v for v in values]
                safeties.append( dict(zip(columnNames, listValues)) )
            
            return safeties
            
        except Exception as ex:
            raise(ex)
Esempio n. 5
0
    def _displayRecords(self):
        ''' after a while show records... this give time that the bridge is available in JS
        '''
        if self._layer.selectedFeatureCount():
            # then prepare selected records in structure usefut for accordion visualization
            featuresDict = self._prepareFeatures_asAccordion()
            
            # prepare js command to execute in the page
            jsonString = json.dumps(featuresDict)
            
            JsCommand = "showRecords('%s', %s)" % (self._layer.id(), jsonString) # <<< jsonString is automatically converted in javascript obj during evaluate
            QgsLogger.debug(self.tr("display records with with JS command: %s" % JsCommand), 3)
            
            # show records
            self.webView.page().mainFrame().evaluateJavaScript(JsCommand)
        
        else:
            QgsLogger.debug(self.tr("No features selected to display for layer: %s" % self._layer.id()), 1)

        # then we can say that the load is completed
        self._ready = True
        
        # Check if we want to remove selection of this layer
        if self.removeSelection:
            self._layer.removeSelection()      
        
        # notify it is ready
        self.ready.emit(self._ready)
    def showRoadClassDistribution(self, currentRoadTypeItem, previousRoadTypeItem):
        ''' Set sunbust UI for each tab category
        '''
        # manage event in case of list clear
        if not currentRoadTypeItem:
            return
        
        # get classes from itemData (UserRole)
        vehicleClasses = currentRoadTypeItem.data(QtCore.Qt.UserRole)
        
        # then load config for each vehicle tab
        # for each tab get it's specific configuration to load in the webview tab
        for tabIndex in range(self.gui.fleetComposition_tabs.count()):
            # get tab name
            tabWidget = self.gui.fleetComposition_tabs.widget(tabIndex)
            vehicleClass = self.gui.fleetComposition_tabs.tabText(tabIndex)
            
            # get confguration for the current vechicle class
            vehicleClassConf = self.getChildrensByName(vehicleClasses, vehicleClass)
            if vehicleClassConf:
                # convert in json string
                jsonString = json.dumps(vehicleClassConf)
                
                # init webview basing on json configuration
                webView = tabWidget.findChildren(QtWebKit.QWebView)[0] # assume only a webview is present in the tab
                print webView.objectName()

                JsCommand = "showJson(%s)" % jsonString
                QgsLogger.debug(self.plugin.tr("Load config with with JS command: %s" % JsCommand), 3)
                
                webView.page().mainFrame().evaluateJavaScript(JsCommand)
Esempio n. 7
0
    def setValue(self, value, dynamicKeyPart: (list, str) = None):
        """
        Set settings value.
        :param value: the value to set for the setting.
        :param dynamicKeyPart: argument specifies the dynamic part of the settings key (a single one a string, or several as a list)
        """

        if self.__metaEnum is None or not self.__metaEnum.isValid():
            QgsLogger.debug(
                "Invalid metaenum. Enum/Flag probably misses Q_ENUM/Q_FLAG declaration. Settings key: '{0}'"
                .format(self.key()))
            return False

        if self.__metaEnum.isFlag():
            enumFlagKey = self.__metaEnum.valueToKeys(value)
        else:
            enumFlagKey = self.__metaEnum.valueToKey(value)
        if not enumFlagKey:
            QgsLogger.debug("Invalid enum/flag value '{0}'.".format(value))
            return False

        if type(dynamicKeyPart) == str:
            dynamicKeyPart = [dynamicKeyPart]
        elif dynamicKeyPart is None:
            dynamicKeyPart = []

        return super().setVariantValuePrivate(enumFlagKey, dynamicKeyPart)
 def setGuiProjectLoaded(self):
     ''' Set GUI if a project has loaded
     '''
     message = "QTraffic: setGuiProjectLoaded by sender {}".format(str(type(self.sender())))
     QgsLogger.debug(message, debuglevel=3)
     
     self.gui.saveAsProject_PButton.setEnabled(True)
Esempio n. 9
0
    def defaultValue(self):
        """
        Get settings default value.
        """

        if self.__metaEnum is None or not self.__metaEnum.isValid():
            QgsLogger.debug(
                "Invalid metaenum. Enum/Flag probably misses Q_ENUM/Q_FLAG declaration. Settings key: '{0}'"
                .format(self.key()))
            return -1

        defaultValueString = self.defaultValueAsVariant()
        if self.__metaEnum.isFlag():
            (defaultValue,
             ok) = self.__metaEnum.keysToValue(defaultValueString)
        else:
            (defaultValue, ok) = self.__metaEnum.keyToValue(defaultValueString)
        if not ok:
            QgsLogger.debug("Invalid enum/flag key/s '{0}'.".format(
                self.defaultValueAsVariant()))
            return -1

        # cast to the enum class
        defaultValue = self.__enumFlagClass(defaultValue)
        return defaultValue
Esempio n. 10
0
    def __init__(self,
                 key,
                 pluginName,
                 defaultValue,
                 description=str(),
                 options=Qgis.SettingsOptions()):
        """
        Constructor for PyQgsSettingsEntryEnumFlag.
        :param key: argument specifies the final part of the settings key.
        :param pluginName: argument is inserted in the key after the section.
        :param defaultValue: argument specifies the default value for the settings entry.
        :param description: argument specifies a description for the settings entry.
        """

        self.options = options
        defaultValueStr = str()
        self.__metaEnum = metaEnumFromValue(defaultValue)
        if self.__metaEnum is None or not self.__metaEnum.isValid():
            QgsLogger.debug(
                "Invalid metaenum. Enum/Flag probably misses Q_ENUM/Q_FLAG declaration. Settings key: '{0}'"
                .format(self.key()))
        else:
            if self.__metaEnum.isFlag():
                defaultValueStr = self.__metaEnum.valueToKeys(defaultValue)
            else:
                defaultValueStr = self.__metaEnum.valueToKey(defaultValue)
            self.__enumFlagClass = defaultValue.__class__

        super().__init__(key, 'plugins/{}'.format(pluginName), defaultValueStr,
                         description, options)
Esempio n. 11
0
    def _setSelectedRecord(self, layerId, featureId):
        ''' Set current selected Record and layer
        '''
        QgsLogger.debug("RecordsDisplayWidget._setSelectedRecord: Selected layerId = {} and record id {}".format(layerId, featureId), 3)

        self._selectedLayerId = layerId
        self._selectedFeatureId = int(featureId)
Esempio n. 12
0
    def uploadAttachment(self, safetyRemoteId, attachment):
        
        tempAttachment = attachment.copy()
        # modify attachment values to be as requested by server records
        tempAttachment["safety"] = self.safetyUrl + str(safetyRemoteId) + "/"
        tempAttachment["attached_file"] = os.path.basename(tempAttachment["attached_file"])
        tempAttachment.pop("id")
        tempAttachment.pop("attached_by_id")
        tempAttachment.pop("safety_id")
        
        QgsLogger.debug("uploadAttachment upload of %s" % json.dumps(tempAttachment),2 )

        boundary = "Boundary_.oOo._83uncb3yc7y83yb4ybi93u878278bx7b8789"
        datas = QByteArray()
        # add parameters
        datas += "--" + boundary + "\r\n"
        for name, value in tempAttachment.iteritems():
            if name == "attached_file":
                continue
            datas += 'Content-Disposition: form-data; name="%s"\r\n' % name;
            datas += 'Content-Type: text/plain; charset=utf-8\r\n';
            datas += "\r\n"
            datas += str(value).encode('utf-8')
            datas += "\r\n"
            datas += "--" + boundary + "\r\n"
        
        # add file
        fd = QFile(tempAttachment["attached_file"])
        fd.open(QIODevice.ReadOnly)
        datas += 'Content-Disposition: form-data; name="attached_file"; filename="%s"\r\n' % tempAttachment["attached_file"];
        datas += 'Content-Type: application/octet-stream\r\n';
        datas += "\r\n"
        datas += fd.readAll()
        datas += "\r\n"
        datas += "--" + boundary + "\r\n"
        fd.close()
        
        # build request
        request = QNetworkRequest()
        url = QUrl(self.baseApiUrl + self.attachmentUrl)
        request.setUrl(url)
        request.setRawHeader("Host", url.host())
        request.setRawHeader("Content-type", "multipart/form-data; boundary=%s" % boundary)
        request.setRawHeader("Content-Length", str(datas.size()))
        
        # register response manager
        try:
            self.manager.finished.disconnect()
        except:
            pass
        self.manager.finished.connect(self.replyUploadAttachmentFinished)

        # start upload
#         print "dump request-----------------------------------------------"
#         for headerKey in request.rawHeaderList():
#             print headerKey, request.rawHeader(headerKey)
#         print datas
        self.singleAttachmentUploadFinished = False
        self.manager.post(request, datas)
        QgsLogger.debug("uploadAttachment to url %s with datas %s" % (url.toString(), str(datas)) ,2 )
 def loadUnlikedSafeties(self):
     '''
     Method to a load safeties without linked Particella
     @return safeties: list of dict of the retrieved records
     '''
     self.checkConnection()
 
     # create query
     sqlquery = "SELECT *,ST_AsText(the_geom) FROM missions_safety WHERE gid_catasto == '' OR gid_catasto == 'None' OR gid_catasto IS NULL "
     sqlquery += "ORDER BY id;"
     
     QgsLogger.debug(self.tr("Recupera le safety non associate a particelle"), 1 )
     try:
         
         self.cursor.execute(sqlquery)
         columnNames = [descr[0] for descr in self.cursor.description]
         # get index of the_geom and ST_AsText(the_geom)
         geomIndex = columnNames.index("the_geom")
         textGeomIndex = columnNames.index("ST_AsText(the_geom)")
         
         # modify column to erase binary the_geom and substitude with renamed ST_AsText(st_geom)
         columnNames[textGeomIndex] = "the_geom" 
         columnNames.pop(geomIndex)
         
         safeties = []
         for values in self.cursor:
             listValues = [v for v in values]
             listValues.pop(geomIndex)
             safeties.append( dict(zip(columnNames, listValues)) )
         
         return safeties
         
     except Exception as ex:
         raise(ex)
Esempio n. 14
0
 def _highlightRecord(self, layerId, featureId):
     ''' Set current hilighted Record and layer
     '''
     QgsLogger.debug("RecordsDisplayWidget._highlightRecord: on mouse over layerId = {} and record id {}".format(layerId, featureId), 3)
     
     if layerId and featureId:
         self.highlightRecord.emit(layerId, featureId)
 def loadAttachments(self, safetyId=None):
     '''
     Method to a load attachments from missions_attachment table based on idexes
     @param safetyId: select only records related to the safetyId
     @return attachments: list of dict of the retrieved records
     '''
     self.checkConnection()
 
     # create query
     sqlquery = "SELECT * FROM missions_attachment "
     if safetyId != None:
         sqlquery += "WHERE safety_id = '%s' " % safetyId
     sqlquery += "ORDER BY id;"
     
     QgsLogger.debug(self.tr("Recupera gli attachments con la query: %s" % sqlquery), 1 )
     try:
         
         self.cursor.execute(sqlquery)
         columnNames = [descr[0] for descr in self.cursor.description]
         
         attachments = []
         for values in self.cursor:
             attachments.append( dict(zip(columnNames, values)) )
         
         return attachments
         
     except Exception as ex:
         raise(ex)
Esempio n. 16
0
    def __init__(self, key, pluginName, defaultValue, description=str()):
        """ Constructor for _PyQgsSettingsEntryEnumFlag.

            :param self: the QgsSettingsEntryEnum object
            :param key: argument specifies the final part of the settings key.
            :param pluginName: argument is inserted in the key after the section.
            :param defaultValue: argument specifies the default value for the settings entry.
            :param description: argument specifies a description for the settings entry.

            .. note::  This constructor should not be used. Use PyQgsSettingsEntryEnum
                       or PyQgsSettingsEntryFlag instead.
        """

        defaultValueStr = str()
        self.__metaEnum = metaEnumFromValue(defaultValue)
        if self.__metaEnum is None or not self.__metaEnum.isValid():
            QgsLogger.debug(
                "Invalid metaenum. Enum/Flag probably misses Q_ENUM/Q_FLAG declaration. Settings key: '{0}'"
                .format(self.key()))
        else:
            if self.settingsType() is self.SettingsType.Enum:
                defaultValueStr = self.__metaEnum.valueToKey(defaultValue)
            else:
                defaultValueStr = self.__metaEnum.valueToKeys(defaultValue)
            self.__enumFlagClass = defaultValue.__class__

        super().__init__(key, pluginName, defaultValueStr, description)
    def fab_10kByPoint(self, point):
        '''
        Method to a load a record from fab_10k basing on geometry point
        @param point: where to find features
        @return fab_10k: list of dict of the retrieved records
        '''
        self.checkConnection()

        sqlquery = '''
            SELECT
                *
            FROM
                fab_10k 
            WHERE 
                ST_Contains(the_geom, ST_GeometryFromText('POINT(%s %s)', %s));
            ''' % (point.x(), point.y(), gw.instance().GEODBDEFAULT_SRID)

        QgsLogger.debug(
            self.tr("Recupera fab_10k con la query: %s" % sqlquery), 1)
        try:

            self.cursor.execute(sqlquery)
            columnNames = [descr[0] for descr in self.cursor.description]
            safeties = []
            for values in self.cursor:
                listValues = [v for v in values]
                safeties.append(dict(zip(columnNames, listValues)))

            return safeties

        except Exception as ex:
            raise (ex)
Esempio n. 18
0
    def setGuiProjectLoaded(self):
        ''' Set GUI if a project has loaded
        '''
        message = "QTraffic: setGuiProjectLoaded by sender {}".format(
            str(type(self.sender())))
        QgsLogger.debug(message, debuglevel=3)

        self.gui.saveAsProject_PButton.setEnabled(True)
 def setHilightRecord(self, layerId=None, featureId=None):
     '''
     slot emitted by JS to communicate the current Layer/featureId have to be highlighted
     '''
     QgsLogger.debug("RecordsDisplayWidgetBridge.setHilightRecord: on mouse over layerId = {} and record id {}".format(layerId, featureId), 3)
     
     if layerId and featureId:
         self.highlightRecord.emit(layerId, featureId)
 def setSelctedRecord(self, layerId=None, featureId=None):
     '''
     slot emitted by JS to communicate the current Layer/featureId selected in the interface
     '''
     QgsLogger.debug("RecordsDisplayWidgetBridge.setSelctedRecord: Selected layerId = {} and record id {}".format(layerId, featureId), 3)
     
     if layerId and featureId:
         self.selectedRecord.emit(layerId, featureId)
 def notifyLinkClicked(self, layerId=None, featureId=None, link=None):
     '''
     slot emitted by JS to communicate that a hyperlink has been clicked.
     event return the Layer/featureId of the click and the web address clicked
     '''
     QgsLogger.debug("RecordsDisplayWidgetBridge.notifyClicked: Clicked hyperlnk = {} on layerId = {} and record id {}".format(link, layerId, featureId), 3)
     
     if layerId and featureId and link:
         self.linkClicked.emit(layerId, featureId, link)
 def __init__(self, serverIface):
     # Save reference to the QGIS server interface
     self.serverIface = serverIface
     QgsMessageLog.logMessage("SUCCESS - Cadastre init", 'plugin', QgsMessageLog.INFO)
     from filters.cadastreFilter import cadastreFilter
     try:
         serverIface.registerFilter( cadastreFilter(serverIface), 100 )
     except Exception, e:
         QgsLogger.debug("cadastreServer - Error loading filter cadastreServer : %s" % e )
         QgsMessageLog.logMessage("CADASTRE  - Error loading filter cadastreServer: %s" % e, 'plugin', QgsMessageLog.WARNING)
    def __init__(self, serverIface):
        # Save reference to the QGIS server interface
        self.serverIface = serverIface
        QgsMessageLog.logMessage("SUCCESS - DynamicLayersServer init", 'plugin', QgsMessageLog.INFO)

        from filters.DynamicLayersFilter import DynamicLayersFilter
        try:
            serverIface.registerFilter( DynamicLayersFilter(serverIface), 100 )
        except Exception, e:
            QgsLogger.debug("DynamicLayersServer - Error loading filter DynamicLayersServer : %s" % e )
    def __init__(self, serverIface):
        # Save reference to the QGIS server interface
        self.serverIface = serverIface
        QgsMessageLog.logMessage("SUCCESS - invalidatecache init plugin",
                                 Qgis.Info)

        from .invalidate_cache_filter import InvalidateCacheFilter
        try:
            serverIface.registerFilter(InvalidateCacheFilter(serverIface), 50)
        except Exception as e:
            QgsLogger.debug("invalidatecache - Error loading filter: %s" % e)
Esempio n. 25
0
    def __init__(self, msg):

        from qgis.utils import iface

        try:
            from qgis.core import QgsMessageLog, Qgis, QgsLogger
            iface.messageBar().pushMessage("Error", msg, level=Qgis.Critical)
            QgsMessageLog.logMessage(msg, 'CanFlood', level=Qgis.Critical)
            QgsLogger.debug('ERROR_%s' % msg)  #also send to file
        except:
            Error(msg)
 def notifyDocClicked(self, layerId=None, featureId=None, document=None):
     '''
     slot emitted by JS to communicate that a document has been clicked.
     event return the Layer/featureId of the click and the value of the document filename
     Does not care if document filename is relative or absolute... that's is managed by 
     listeners of this event
     '''
     QgsLogger.debug("RecordsDisplayWidgetBridge.notifyDocClicked: Clicked doc = {} on layerId = {} and record id {}".format(document, layerId, featureId), 3)
     
     if layerId and featureId and document:
         self.docClicked.emit(layerId, featureId, document)
    def __init__(self, serverIface):
        # Save reference to the QGIS server interface
        self.serverIface = serverIface
        QgsMessageLog.logMessage("SUCCESS - atlasprint init", 'plugin',
                                 QgsMessageLog.INFO)

        from filters.atlasprintFilter import atlasprintFilter
        try:
            serverIface.registerFilter(atlasprintFilter(serverIface), 50)
        except Exception, e:
            QgsLogger.debug(
                "atlasprint - Error loading filter atlasprint : %s" % e)
    def deleteSafety(self, safetyId):
        '''
        Method to delete safety from missions_safety
        @param safetyId
        '''
        self.checkConnection()

        # create query
        sqlquery = "DELETE FROM missions_safety WHERE local_id=%s;" % int(safetyId)
        
        QgsLogger.debug(self.tr("Cancella safety con la query: %s" % sqlquery), 1 )
        self.cursor.execute(sqlquery)
Esempio n. 29
0
 def replyFinished(self):
     error = self.reply.error()
     if error == QNetworkReply.NoError:
         response_text = self.reply.readAll().data()
         QgsLogger.debug('Response: {}'.format(response_text))
         data = json.loads(response_text)
         self.loadData(data)
     else:
         errorMessage = self.getErrorMessage(error)
         self.message.emit(errorMessage, QgsMessageBar.WARNING)
         self._finish()
     self.reply.deleteLater()
     self.reply = None
 def deleteAttachmentsBySasfety(self, safetyId):
     '''
     Method to a delete attachments from missions_attachment related to a specified safety
     @param indexes: indexes of attachments to delete
     '''
     self.checkConnection()
 
     # create query
     sqlquery = "DELETE FROM missions_attachment "
     sqlquery += "WHERE safety_id='%s';" % str(safetyId)
     
     QgsLogger.debug(self.tr("Rimozione attachments con la query: %s" % sqlquery), 1 )
     self.cursor.execute(sqlquery)
Esempio n. 31
0
 def replyFinished(self):
     error = self.reply.error()
     if error == QNetworkReply.NoError:
         response_text = self.reply.readAll().data()
         QgsLogger.debug('Response: {}'.format(response_text))
         data = json.loads(response_text)
         self.loadData(data)
     else:
         errorMessage = self.getErrorMessage(error)
         self.message.emit(errorMessage, QgsMessageBar.WARNING)
         self._finish()
     self.reply.deleteLater()
     self.reply = None
Esempio n. 32
0
 def testLogger(self):
     (myFileHandle, myFilename) = tempfile.mkstemp()
     try:
         myFile = os.fdopen(myFileHandle, "w")
         myFile.write("QGIS Logger Unit Test\n")
         myFile.close()
         os.environ['QGIS_DEBUG'] = '2'
         os.environ['QGIS_LOG_FILE'] = myFilename
         myLogger = QgsLogger()
         myLogger.debug('This is a debug')
         myLogger.warning('This is a warning')
         myLogger.critical('This is critical')
         #myLogger.fatal('Aaaargh...fatal');  #kills QGIS not testable
         myFile = open(myFilename, 'rt')
         myText = myFile.readlines()
         myFile.close()
         myExpectedText = [
             'QGIS Logger Unit Test\n', 'This is a debug\n',
             'This is a warning\n', 'This is critical\n'
         ]
         myMessage = ('Expected:\n---\n%s\n---\nGot:\n---\n%s\n---\n' %
                      (myExpectedText, myText))
         self.assertEquals(myText, myExpectedText, myMessage)
     finally:
         pass
         os.remove(myFilename)
Esempio n. 33
0
    def showRoadClassDistribution(self, currentRoadTypeItem,
                                  previousRoadTypeItem):
        ''' Set sunburst UI for each tab category
        '''
        # manage event in case of list clear
        if not currentRoadTypeItem:
            return

        # get current road type
        roadType = currentRoadTypeItem.text()

        # get classes from itemData (UserRole)
        vehicleClasses = currentRoadTypeItem.data(QtCore.Qt.UserRole)

        # create json string to create uniform legend am9ong tabs
        jsonString = json.dumps(vehicleClasses)
        setLegendJsCommand = "setColorLegend(%s)" % (jsonString)

        # then load config for each vehicle tab
        # for each tab get it's specific configuration to load in the webview tab
        for tabIndex in range(self.gui.fleetComposition_tabs.count()):
            # get tab name
            tabWidget = self.gui.fleetComposition_tabs.widget(tabIndex)
            vehicleClass = self.gui.fleetComposition_tabs.tabText(tabIndex)

            # get confguration for the current vechicle class
            vehicleClassConf = self.getChildrensByName(vehicleClasses,
                                                       vehicleClass)
            if vehicleClassConf:
                # init webview basing on json configuration
                webView = tabWidget.findChildren(QtWebKit.QWebView)[
                    0]  # assume only a webview is present in the tab

                # init color legend uniform among sunburst tabs
                QgsLogger.debug(
                    self.tr("Create uniform color legend with JS command: %s" %
                            setLegendJsCommand), 3)
                webView.page().mainFrame().evaluateJavaScript(
                    setLegendJsCommand)

                # create sunburst
                jsonString = json.dumps(vehicleClassConf)

                JsCommand = "showJson('%s', '%s', %s)" % (
                    roadType, vehicleClass, jsonString)
                QgsLogger.debug(
                    self.tr("Load config with with JS command: %s" %
                            JsCommand), 3)

                webView.page().mainFrame().evaluateJavaScript(JsCommand)
 def get(self, api, jsonquery):
     QgsLogger.debug("api: " + api)
     QgsLogger.debug("jsonquery: " + jsonquery)
     # do query
     if (api == "provincia/"):
         return QueryProvincia(jsonquery).getJsonFile()
     elif (api == "comune/"):
         return QueryComune(jsonquery).getJsonFile()
     elif (api == "localita/"):
         return QueryLocalita(jsonquery).getJsonFile()
     #elif ( api == "catasto2010_1/" ):
     #return QueryCatasto2010_1(jsonquery).getJsonFile()
     elif (api == "catasto2010_2/"):
         return QueryCatasto2010_2(jsonquery).getJsonFile()
Esempio n. 35
0
    def replyDownloadSopralluoghiFinished(self, reply):
        # disconnect current reply callback
        self.manager.finished.disconnect(self.replyDownloadSopralluoghiFinished)
        
        # received error
        if reply.error():
            message = self.tr("Errore nella HTTP Request: %d - %s" % (reply.error(), reply.errorString()) )
            self.message.emit(message, QgsMessageLog.CRITICAL)
            self.done.emit(False)
            return
        
        # well authenticated :)
        gw.instance().autenthicated = True
        gw.instance().authenticationRetryCounter = 0

        from json import loads
        raw = reply.readAll()
        try:
            jsonRequest = loads(raw.data())
        except Exception as ex:
            try:
                traceback.print_exc()
            except:
                pass
            self.done.emit(False)
            self.message.emit(ex.message, QgsMessageLog.CRITICAL)
            return
        QgsLogger.debug("replyDownloadSopralluoghiFinished received request %s" % json.dumps(jsonRequest),2 )
        
        # check if return more than 20 elements (e.g. for the super user)
        if "objects" in jsonRequest:
            jsonSopralluoghi = jsonRequest["objects"] # get array of dicts
        else:
            jsonSopralluoghi = [jsonRequest]
        
        # get number of the archived safety
        if len(jsonSopralluoghi) == 0:
            message = self.tr("Errore nel record sopralluoghi appena scaricato: %s" % json.dumps(jsonSopralluoghi) )
            self.message.emit(message, QgsMessageLog.CRITICAL)
            self.done.emit(False)
            return
            
        self.saved_sopralluoghi = jsonSopralluoghi[0]

        message = self.tr("self.saved_sopralluoghi: %s" % json.dumps(self.saved_sopralluoghi) )
        self.message.emit(message, QgsMessageLog.INFO)
        
        # successfully end
        self.singleSopralluoghiDownloadDone.emit(True)
Esempio n. 36
0
    def updateSopralluoghi(self, sopralluoghi):
        request = QNetworkRequest()
        request.setRawHeader("Content-Type", "application/json");
        url = QUrl(self.baseApiUrl + self.sopralluoghiUrl + str(sopralluoghi["gid"]))
        
        request.setUrl(url)
        
        # register response manager
        self.manager.finished.connect(self.replyUpdateSopralluoghiFinished)

        # start update
        self.singleSopralluoghiUpdateFinished = False
        sopralluoghi.pop("gid")
        self.manager.put(request, json.dumps(sopralluoghi) )
        QgsLogger.debug("updateSopralluoghi to url %s with sopralluoghi %s" % (url.toString(), json.dumps(sopralluoghi)) ,2 )
Esempio n. 37
0
 def __init__(self, serverIface):
     # Save reference to the QGIS server interface
     self.serverIface = serverIface
     QgsMessageLog.logMessage("SUCCESS - Cadastre init", 'plugin',
                              QgsMessageLog.INFO)
     from filters.cadastreFilter import cadastreFilter
     try:
         serverIface.registerFilter(cadastreFilter(serverIface), 100)
     except Exception, e:
         QgsLogger.debug(
             "cadastreServer - Error loading filter cadastreServer : %s" %
             e)
         QgsMessageLog.logMessage(
             "CADASTRE  - Error loading filter cadastreServer: %s" % e,
             'plugin', QgsMessageLog.WARNING)
Esempio n. 38
0
 def reply_finished(self):
     error = self.reply.error()
     if error == QNetworkReply.NoError:
         response_text = self.reply.readAll().data().decode('utf-8')
         QgsLogger.debug('Response: {}'.format(response_text))
         try:
             data = json.loads(response_text)
             self.load_data(data)
         except ValueError:
             self.message.emit(self.tr('The service did not reply properly. Please check service definition.'), QgsMessageBar.WARNING)
     else:
         error_message = self.get_error_message(error)
         self.message.emit(error_message, QgsMessageBar.WARNING)
         self._finish()
     self.reply.deleteLater()
     self.reply = None
 def createNewAttachment(self, attachmentsDict):
     '''
     Method to a archive a attachments in missions_attachments table
     @param attachmentsDict: attachments dictionary - keys have to be the same key of Db
     '''
     self.checkConnection()
     
     # create query
     sqlquery = "INSERT INTO missions_attachment "
     sqlquery += "( "+",".join(attachmentsDict.keys()) + " ) VALUES ( "
     for v in attachmentsDict.values():
         sqlquery += "%s, " % adapt(v)
     sqlquery = sqlquery[0:-2] + " );"
     
     QgsLogger.debug(self.tr("Inserisce attachment con la query: %s" % sqlquery), 1 )
     self.cursor.execute(sqlquery)
 def modifiedStatistic(self, statistic=None):
     '''
     slot emitted by JS to communicate that a vehicle class statistic
     has changed 
     '''
     QgsLogger.debug("Statistic = %s" % statistic, 3)
     
     self.statistic = None
     if statistic:
         try:
             # parse JSON
             self.statistic =   json.loads(statistic, object_pairs_hook=collections.OrderedDict)
             # notify new statistic
             self.modified.emit(self.statistic)
         except:
             traceback.print_exc()                
 def setProjectSaved(self):
     ''' Set status of project GUI as saved = not modified
         This method is a slot called everytime a project is saved
     '''
     message = "QTraffic: setProjectSaved by sender {}".format(str(type(self.sender())))
     QgsLogger.debug(message, debuglevel=3)
     
     # do nothing if the project already marked as modified
     if not self.isModified():
         return
     
     # enable Save button
     self.gui.saveProject_PButton.setEnabled(False)
     
     # set tab text = tab text + '*' to show that project has been modified
     self.gui.tabWidget.setTabText(0, self.gui.tabWidget.tabText(0)[0:-1])
    def loadAllTeamIds(self):
        '''
        Method to retieve all available team_id in missions_request e missions_safety
        @return list of distinct team_id
        '''
        self.checkConnection()

        # create query
        sqlquery = "SELECT DISTINCT team_id FROM (SELECT team_id FROM missions_request UNION SELECT team_id FROM missions_safety);"
        
        QgsLogger.debug(self.tr("Recupera i team_id con la query: %s" % sqlquery), 1 )
        self.cursor.execute(sqlquery)
        
        result = []
        for team_id in self.cursor:
            result.append(team_id[0])
        return result
    def initSafetyValues(self):

        #self.currentSafety = {"safety": "{u'sdate': u'20/03/2013', u's1mapright': u'643334.2044114', u'number': 3, u's1com': u'San Marcello Pistoiese', u's1istatcom': u'019', u's0com': u'', u's1mapleft': u'643291.87110092', u's1viacorso': 1, u's1istatloc': u'10010', u's1name': u'Club Juventus', u's0sigla': u'', u's1mapbottom': u'4879570.583229', u's1aggn': u'019103576', u's1prov': u'PT', u's1istatcens': u'002', u's1civico': u'121', u's1catfoglio': u'55', u's1istatreg': u'009', u's1pos': 3, u's1loc': u'San Marcello Pistoiese', u's1catpart1': u'61', u's1istatprov': u'047', u's1maptop': u'4879597.6765478', u's1via': u'Marconi', u's1edn': u'3'}"}
        #self.currentSafety = '{"s1istatprov":"045","s1istatcom":"004","sdate":"22/10/2013","s1prov":"MS","s1istatreg":"009","s1com":"Casola in Lunigiana","s1loc":"Casola in Lunigiana","s1istatloc":"10003","s1istatcens":"001","s1catfoglio":"24","s1catpart1":"966","s2nfloors":"1","s2floorsfc":"8","s2uso1":true,"s2uson1":12,"s2percuse":"0","s2occupiers":3,"s3tA1":true,"s3tG1":true,"s3tH1":true,"s3reg1":"1","s3as2":true,"s3as1":true,"s3as3":true,"s4dA1":true,"s4dC1":true,"s4dF1":true,"s4pB1":true,"s4pC1":true,"s4pD1":true,"s4pE1":true,"s4pF1":true,"s5ensA1":true,"s5ensB1":true,"s6extA1":true,"s6extB1":true,"s6extC1":true,"s6extD1":true,"s6extE1":true,"s7morfo":"1","s8riskst":"0","s8agibilita":"0","s8accuracy":"0","s8prov1":"0","s8prov7":"0","s8prov8":"0","s8prov2":"0","s8prov3":"0","s8prov4":"0","s8prov5":"0","s8prov6":"0","s8prov9":"0","s8prov10":"0","s8prov11":"0","s8prov12":"0","s8prov11other":"111111111111111","s8prov12other":"12121212121212"}'

        if self.currentSafety is None:
            return

        self.setWindowTitle(
            self.tr("Squadra: %s - Scheda: %d" %
                    (self.teamName, self.currentSafety["number"])))

        safety = self.prepareSafetyToJs(self.currentSafety["safety"])
        JsCommand = "updateSafety(%s, %s)" % (adapt(self.teamName), safety)
        QgsLogger.debug(self.tr("Init Safety with JS command: %s" % JsCommand))

        self.webView.page().mainFrame().evaluateJavaScript(JsCommand)
    def loadSafetyNumbers(self):
        '''
        Method to retieve missions_safety numbers (useful to select the number of a new safety)
        @return list of numbers
        '''
        self.checkConnection()

        # create query
        sqlquery = "SELECT number FROM missions_safety ORDER BY number;"
        
        QgsLogger.debug(self.tr("Recupera la lista dei numeri di scheda con la query: %s" % sqlquery), 1 )
        self.cursor.execute(sqlquery)
        
        result = []
        for number in self.cursor:
            result.append(number[0])
        return result
Esempio n. 45
0
    def setProjectSaved(self):
        ''' Set status of project GUI as saved = not modified
            This method is a slot called everytime a project is saved
        '''
        message = "QTraffic: setProjectSaved by sender {}".format(
            str(type(self.sender())))
        QgsLogger.debug(message, debuglevel=3)

        # do nothing if the project already marked as modified
        if not self.isModified():
            return

        # enable Save button
        self.gui.saveProject_PButton.setEnabled(False)

        # set tab text = tab text + '*' to show that project has been modified
        self.gui.tabWidget.setTabText(0, self.gui.tabWidget.tabText(0)[0:-1])
Esempio n. 46
0
    def modifiedStatistic(self, statistic=None):
        '''
        slot emitted by JS to communicate that a vehicle class statistic
        has changed 
        '''
        QgsLogger.debug("Statistic = %s" % statistic, 3)

        self.statistic = None
        if statistic:
            try:
                # parse JSON
                self.statistic = json.loads(
                    statistic, object_pairs_hook=collections.OrderedDict)
                # notify new statistic
                self.modified.emit(self.statistic)
            except:
                traceback.print_exc()
    def loadRequestNumbers(self):
        '''
        Method to retieve missions_request numbers
        @return list of numbers
        '''
        self.checkConnection()

        # create query
        sqlquery = "SELECT number, id FROM missions_request ORDER BY number;"
        
        QgsLogger.debug(self.tr("Recupera la lista dei numeri di sopralluoghi con la query: %s" % sqlquery), 1 )
        self.cursor.execute(sqlquery)
        
        result = []
        for number, request_id in self.cursor:
            result.append( (number, request_id) )
        return result