def read_form(self):
        """Extracts all inputs from the dialog form and provides run_task when succesful.
        
        The selected_layer object is used to find the connection info to the Oracle
        database. If the database connection is there but either the username or
        password is missing get_credentials() will be called until valid credentials
        are entered or the task is canceled.
        """
        filter_on_height = self.dlg.cb_filterOnHeight.isChecked()
        filter_on_volumetric_weight = self.dlg.cb_filterOnVolumetricWeight.isChecked(
        )
        selected_layer = self.dlg.cmb_layers.currentLayer()
        trx_bool = self.dlg.cb_TriaxiaalProeven.isChecked()
        sdp_bool = self.dlg.cb_SamendrukkingProeven.isChecked()
        output_location = self.dlg.fileWidget.filePath()
        output_name = self.dlg.le_outputName.text()
        args = {
            'selected_layer': selected_layer,
            'output_location': output_location,
            'output_name': output_name,
            'trx_bool': trx_bool,
            'sdp_bool': sdp_bool
        }

        # General Asserts
        assert isinstance(
            selected_layer, QgsVectorLayer
        ), 'De geselecteerde laag \'{}\' is geen vector laag.'.format(
            selected_layer.name())
        assert output_name, 'Het veld \'uitvoernaam\' mag niet leeg zijn.'
        assert output_location, 'Het veld \'uitvoermap\' mag niet leeg zijn.'

        if trx_bool:
            # TRX Asserts
            assert any([
                self.dlg.cb_CU.isChecked(),
                self.dlg.cb_CD.isChecked(),
                self.dlg.cb_UU.isChecked()
            ]), 'Een van de drie Proeftypes moet aangekruisd worden.'
            proef_types = []
            if self.dlg.cb_CU.isChecked():
                proef_types.append('CU')
            if self.dlg.cb_CD.isChecked():
                proef_types.append('CD')
            if self.dlg.cb_UU.isChecked():
                proef_types.append('UU')
            args['proef_types'] = proef_types
            args['ea'] = self.dlg.sb_strain.value()
            args['save_plot'] = self.dlg.cb_savePlot.isChecked()

            if self.dlg.le_vg_trx.text():
                volG_trx = self.dlg.le_vg_trx.text().strip('[').strip(
                    ']').split(',')
                volG_trx = [float(x) for x in volG_trx]
                volG_trx.sort()
                if len(volG_trx) < 2:
                    self.iface.messageBar().pushMessage(
                        "Warning",
                        'Maar 1 volumegewicht interval voor triaxiaalproeven is gegeven, het interval wordt automatisch gegenereerd.',
                        level=1,
                        duration=5)
                    volG_trx = None
            else:
                volG_trx = None
            args['volG_trx'] = volG_trx

        if sdp_bool:
            if self.dlg.le_vg_sdp.text():
                volG_sdp = self.dlg.le_vg_sdp.text().strip('[').strip(
                    ']').split(',')
                volG_sdp = [float(x) for x in volG_sdp]
                volG_sdp.sort()
                if len(volG_sdp) < 2:
                    self.iface.messageBar().pushMessage(
                        "Warning",
                        'Maar 1 volumegewicht interval voor samendrukkingsproeven is gegeven, het interval wordt automatisch gegenereerd.',
                        level=1,
                        duration=5)
                    volG_sdp = None
            else:
                volG_sdp = None
            args['volG_sdp'] = volG_sdp

        if filter_on_height:
            args['maxH'] = self.dlg.sb_maxHeight.value()
            args['minH'] = self.dlg.sb_minHeight.value()
            assert args['maxH'] > args[
                'minH'], 'Maximum hoogte moet hoger zijn dan minimum hoogte.'
        if filter_on_volumetric_weight:
            args['maxVg'] = self.dlg.sb_maxVolumetricWeight.value()
            args['minVg'] = self.dlg.sb_minVolumetricWeight.value()
            assert args['maxVg'] > args[
                'minVg'], 'Maximum volumegewicht moet hoger zijn dan het minimum volumegewicht.'

        source = selected_layer.source()
        uri = QgsDataSourceUri(source)

        savedUsername = uri.hasParam('username')
        savedPassword = uri.hasParam('password')

        host = uri.host()
        port = uri.port()
        database = uri.database()
        username = uri.username()
        password = uri.password()

        errorMessage = None
        if savedUsername is True and savedPassword is True:
            try:
                qb = qgis_backend.QgisBackend(host=host,
                                              port=port,
                                              database=database,
                                              username=username,
                                              password=password)
                qb.check_connection()
                args['qb'] = qb
                self.run_task(args)
            except cx_Oracle.DatabaseError as e:
                errorObj, = e.args
                errorMessage = errorObj.message
                suc = 'false'
                while suc == 'false':
                    suc, qb, errorMessage = self.get_credentials(
                        host,
                        port,
                        database,
                        username=username,
                        password=password,
                        message=errorMessage)
                if suc == 'exit':
                    pass
                elif suc == 'true':
                    args['qb'] = qb
                    self.run_task(args)
        else:
            suc, qb, errorMessage = self.get_credentials(host,
                                                         port,
                                                         database,
                                                         username=username,
                                                         password=password)
            while suc == 'false':
                suc, qb, message = self.get_credentials(host,
                                                        port,
                                                        database,
                                                        message=errorMessage)
            if suc == 'exit':
                pass
            elif suc == 'true':
                args['qb'] = qb
                self.run_task(args)
예제 #2
0
    def run(self):
        """Runs the logic behind the dialogs"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start:
            self.first_start = False
            # Start a dialog window
            self.dlg = PRW_Data_OpvragerDialog()
            self.dlg.OutputLocation.setStorageMode(1)
            self.dlg.OutputLocation.setFilePath(
                self.dlg.OutputLocation.defaultRoot())
            # Set a validator on the filename lineEdit so that no random signs can be put in.
            rx2 = QRegExp(r"^[\w\-. ]+$")
            filename_validator = QRegExpValidator(rx2)
            self.dlg.FileName.setValidator(filename_validator)

        # Show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Extracting values from the dialog form
            self.selected_layer = self.dlg.cmb_layer.currentLayer()
            self.dateMax = self.dlg.DateMax.date().toString('yyyy-MM-dd')
            self.dateMin = self.dlg.DateMin.date().toString('yyyy-MM-dd')
            self.shpExportBool = self.dlg.exportShapefile.isChecked()
            self.fileName = self.dlg.FileName.text()
            self.outputLocation = self.dlg.OutputLocation.filePath()

            source = self.selected_layer.source()
            uri = QgsDataSourceUri(source)
            try:
                # Check if a database is connected to the layer source
                assert uri.database(
                ), '"{layer}" heeft geen connectie met een database.'.format(
                    layer=self.selected_layer.name())
                assert self.selected_layer.selectedFeatureCount(
                ) != 0, 'Geen Objecten zijn geselecteerd in laag: "{layer}".'.format(
                    layer=self.selected_layer.name())
                assert self.fileName, 'Er is geen Excel uitvoernaam opgegeven.'
                assert self.outputLocation, 'Er is geen uitvoermap opgegeven.'
            except Exception as e:
                self.iface.messageBar().pushMessage("Error",
                                                    str(e),
                                                    level=2,
                                                    duration=5)
                raise e
                return

            savedUsername = uri.hasParam('username')
            savedPassword = uri.hasParam('password')

            host = uri.host()
            port = uri.port()
            database = uri.database()
            self.username = uri.username()
            self.password = uri.password()
            self.dsn = cora.makedsn(host=host,
                                    port=port,
                                    service_name=database)

            errorMessage = None
            # If we have a username and password try to connect, otherwise ask for credentials
            # If the connection fails store the error and show dialog screen for credentials input
            if savedUsername is True and savedPassword is True:
                try:
                    self.check_connection()
                    self.run_task()
                except cora.DatabaseError as e:
                    errorObj, = e.args
                    errorMessage = errorObj.message
                    success = 'false'
                    # Credentials loop
                    while success == 'false':
                        success, errorMessage = \
                            self.get_credentials(
                                host, port, self.database, message=errorMessage)
                    if success == 'exit':
                        pass
                    elif success == 'true':
                        self.run_task()
            else:
                success, errorMessage = \
                    self.get_credentials(
                        host, port, self.database, username=self.username, password=self.password)
                # Credentials loop
                while success == 'false':
                    success, errorMessage = \
                        self.get_credentials(
                            host, port, self.database, username=self.username, password=self.password, message=errorMessage)
                if success == 'exit':
                    pass
                elif success == 'true':
                    self.run_task()