def applyScalarRenderSettings(self, layer, datasetGroupIndex, file, type, save_type='xml'): """ Applies scalar renderer settings to a datagroup based on a color ramp properties. :param layer: QgsMeshLayer :param datasetGroupIndex: int :param file: str :param type: str -> 'ramp' 'map' :return: bool -> True for successful, False for unsuccessful """ rs = layer.rendererSettings() rsScalar = rs.scalarSettings(datasetGroupIndex) if type == 'ramp': if rsScalar.colorRampShader().colorRampItemList(): minValue = rsScalar.colorRampShader().colorRampItemList()[0].value maxValue = rsScalar.colorRampShader().colorRampItemList()[-1].value shader = rsScalar.colorRampShader() doc = QDomDocument() xml = QFile(file) statusOK, errorStr, errorLine, errorColumn = doc.setContent(xml, True) if statusOK: element = doc.documentElement() shader.readXml(element) shader.setMinimumValue(minValue) shader.setMaximumValue(maxValue) shader.setColorRampType(0) shader.classifyColorRamp(5, -1, QgsRectangle(), None) rsScalar.setColorRampShader(shader) else: return False else: return False elif type == 'map': doc = QDomDocument() xml = QFile(file) if save_type == 'xml' else file statusOK, errorStr, errorLine, errorColumn = doc.setContent(xml, True) if statusOK: element = doc.documentElement() rsScalar.readXml(element) else: return False else: return False rs.setScalarSettings(datasetGroupIndex, rsScalar) layer.setRendererSettings(rs) return True
def createSimpleMemorial(self): tempDoc = QDomDocument() simple = QFile(self.simpleMemorial) simple.open(QIODevice.ReadOnly) loaded = tempDoc.setContent(simple) simple.close() element = tempDoc.documentElement() nodes = element.elementsByTagName("table") table = nodes.item(0).toElement() tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, u"MEMORIAL DESCRITIVO SINTÉTICO", 7, 0)) table.appendChild(tr) tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, u"VÉRTICE", 0, 2)) tr.appendChild(self.createCellElement(tempDoc, "COORDENADAS", 2, 0)) tr.appendChild(self.createCellElement(tempDoc, "LADO", 0, 2)) tr.appendChild(self.createCellElement(tempDoc, "AZIMUTES", 2, 0)) tr.appendChild(self.createCellElement(tempDoc, u"DISTÂNCIA", 0, 0)) table.appendChild(tr) tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, "E", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "N", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "PLANO", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "REAL", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "(m)", 0, 0)) table.appendChild(tr) convergence = float(self.convergenciaEdit.text()) rowCount = self.tableWidget.rowCount() for i in range(0,rowCount): lineElement = tempDoc.createElement("tr") lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,0).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,1).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,2).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,3).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,4).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,5).text(), 0, 0)) lineElement.appendChild(self.createCellElement(tempDoc, self.tableWidget.item(i,6).text(), 0, 0)) table.appendChild(lineElement) simple = open(self.simpleMemorial, "w", encoding='utf-8') simple.write(tempDoc.toString()) simple.close()
def download_features(self, output_path): wfs = self.wfs() typenames = self.selected_typenames() if len(typenames) == 0: return params = { "typename": typenames, } if self.limitChkBox.isChecked(): params["maxfeatures"] = self.featureLimitBox.value() if self.bbox_group.isChecked(): if self.bboxWidget.value() == "": QMessageBox.warning(self, self.windowTitle(), "Extent is empty") return if not self.bboxWidget.isValid(): QMessageBox.warning(self, self.windowTitle(), "Extent is invalid") return params["bbox"] = self._get_bbox(wfs) try: with qgis_proxy_settings(): print("params", params) response = wfs.getfeature(**params) except owslib.util.ServiceException as e: QMessageBox.critical(self, "ServiceException", str(e)) return xml = response.read() doc = QDomDocument() if not doc.setContent(xml): return root = doc.documentElement() exception = root.firstChildElement("ows:Exception") if not exception.isNull(): QMessageBox.critical(self, "ows:Exception", exception.text()) return # depending on WFS versions, we get either a str or bytes if isinstance(xml, str): xml = xml.encode("utf8") with open(output_path, "wb") as out: out.write(xml)
def on_load_style(self): fn, _ = QFileDialog.getOpenFileName(self, "Fichier style à charger", filter = "*.xml") if fn: doc = QDomDocument() doc.setContent(open(fn, "r").read()) self.__renderer = QgsFeatureRenderer.load(doc.documentElement(), QgsReadWriteContext()) for i, c in enumerate(self.__classes): _, cls, wcls = c if self.__renderer.__class__ == cls: new_widget = wcls.create(self.__layer, self.__styles[i], self.__renderer) idx = i break # replace old widget self.__sw.removeWidget(self.__sw.widget(idx)) self.__sw.insertWidget(idx, new_widget) self.__sw.setCurrentIndex(idx) self.__combo.setCurrentIndex(idx)
def __init__(self, width, height, column_mapping=None, style_file=None, symbology=None, parent_item=None): """ Parameters ---------- width: int Width in pixels height: int Height in pixels column_mapping: dict Layer column mapping with the following keys: - rock_code_column : name of the column which holds the rock code - formation_code_column : name of the column which holds the formation code - rock_description_column - formation_description_column style_file: str File name of the QGIS style file to load symbology: QDomDocument QGIS style, as XML document parent: QGraphicsItem Parent item """ LogItem.__init__(self, parent_item) self.__width = width self.__height = height self.__min_z = 0 self.__max_z = 100 self.__data = None self.__layer = None self.__column_mapping = column_mapping if column_mapping is not None else {} # change current directory, so that relative paths to SVG get correctly resolved os.chdir(os.path.dirname(__file__)) if style_file: doc = QDomDocument() doc.setContent(open(style_file, "r").read()) self.__renderer = QgsFeatureRenderer.load(doc.documentElement(), QgsReadWriteContext()) elif symbology: self.__renderer = QgsFeatureRenderer.load(symbology.documentElement(), QgsReadWriteContext()) else: self.__renderer = QgsFeatureRenderer.defaultRenderer(POLYGON_RENDERER)
def __init__(self, width, height, style_file=None, parent=None): LogItem.__init__(self, parent) self.__width = width self.__height = height self.__min_z = 0 self.__max_z = 100 self.__data = None self.__layer = None # change current directory, so that relative paths to SVG get correctly resolved os.chdir(os.path.dirname(__file__)) if style_file: doc = QDomDocument() doc.setContent(open(style_file, "r").read()) self.__renderer = QgsFeatureRendererV2._load(doc.documentElement()) else: self.__renderer = QgsFeatureRendererV2.defaultRenderer( POLYGON_RENDERER)
def create(document: QDomDocument): """ Create an instance of the ComposerDataSource object from a DOM document. Returns None if the domDocument is invalid. """ custom_properties = QgsObjectCustomProperties() custom_properties.readXml(document.documentElement()) data_source_name = custom_properties.value( LayoutUtils.DATA_SOURCE_PROPERTY) data_category = custom_properties.value( LayoutUtils.DATA_CATEGORY_PROPERTY) referenced_table_name = custom_properties.value( LayoutUtils.REFERENCED_TABLE_PROPERTY) if not data_source_name: return None data_source = ComposerDataSource(data_source_name, data_category, referenced_table_name) return data_source
def parse_xml(self): """Parse the xml file. Returns false if there is failure.""" xml_file = QFile(self._xml_path) if not xml_file.open(QIODevice.ReadOnly): return False document = QDomDocument() if not document.setContent(xml_file): return False xml_file.close() document_element = document.documentElement() if document_element.tagName() != 'qgis_style': return False # Get all the symbols self._symbols = [] symbols_element = document_element.firstChildElement('symbols') symbol_element = symbols_element.firstChildElement() context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) while not symbol_element.isNull(): if symbol_element.tagName() == 'symbol': symbol = QgsSymbolLayerUtils.loadSymbol( symbol_element, context) if symbol: self._symbols.append({ 'name': symbol_element.attribute('name'), 'symbol': symbol }) symbol_element = symbol_element.nextSiblingElement() return True
def test_getcapabilities(self): project = self._project_path assert os.path.exists(project), "Project file not found: " + project # without cache query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % ( urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) doc = QDomDocument("wms_getcapabilities_130.xml") doc.setContent(body) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.1.1&REQUEST=%s' % ( urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WFS&VERSION=1.1.0&REQUEST=%s' % ( urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WFS&VERSION=1.0.0&REQUEST=%s' % ( urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WCS&VERSION=1.0.0&REQUEST=%s' % ( urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WMTS&VERSION=1.0.0&REQUEST=%s' % ( urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) filelist = [ f for f in os.listdir(self._servercache._cache_dir) if f.endswith(".xml") ] self.assertEqual(len(filelist), 6, 'Not enough file in cache') cacheManager = self._server_iface.cacheManager() self.assertTrue(cacheManager.deleteCachedDocuments(None), 'deleteCachedDocuments does not return True') filelist = [ f for f in os.listdir(self._servercache._cache_dir) if f.endswith(".xml") ] self.assertEqual(len(filelist), 0, 'All files in cache are not deleted ') prj = QgsProject() prj.read(project) query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % ( urllib.parse.quote(project), 'GetCapabilities') request = QgsBufferServerRequest(query_string, QgsServerRequest.GetMethod, {}, None) accessControls = self._server_iface.accessControls() cDoc = QDomDocument("wms_getcapabilities_130.xml") self.assertFalse( cacheManager.getCachedDocument(cDoc, prj, request, accessControls), 'getCachedDocument is not None') self.assertTrue( cacheManager.setCachedDocument(doc, prj, request, accessControls), 'setCachedDocument false') self.assertTrue( cacheManager.getCachedDocument(cDoc, prj, request, accessControls), 'getCachedDocument is None') self.assertEqual(doc.documentElement().tagName(), cDoc.documentElement().tagName(), 'cachedDocument not equal to provide document') self.assertTrue(cacheManager.deleteCachedDocuments(None), 'deleteCachedDocuments does not return True')
def test_expressionFromOgcFilterWithString(self): """ Test expressionFromOgcFilter with String type field """ vl = QgsVectorLayer('Point', 'vl', 'memory') vl.dataProvider().addAttributes([QgsField('id', QVariant.String)]) vl.updateFields() # Literals are Integer 1 and 3 f = '''<?xml version="1.0" encoding="UTF-8"?> <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"> <ogc:And> <ogc:PropertyIsGreaterThan> <ogc:PropertyName>id</ogc:PropertyName> <ogc:Literal>1</ogc:Literal> </ogc:PropertyIsGreaterThan> <ogc:PropertyIsLessThan> <ogc:PropertyName>id</ogc:PropertyName> <ogc:Literal>3</ogc:Literal> </ogc:PropertyIsLessThan> </ogc:And> </ogc:Filter> ''' d = QDomDocument('filter') d.setContent(f, True) e = QgsOgcUtils.expressionFromOgcFilter(d.documentElement(), vl) self.assertEqual(e.expression(), 'id > \'1\' AND id < \'3\'') # Literals are Double 1.0 and 3.0 f = '''<?xml version="1.0" encoding="UTF-8"?> <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"> <ogc:And> <ogc:PropertyIsGreaterThan> <ogc:PropertyName>id</ogc:PropertyName> <ogc:Literal>1.0</ogc:Literal> </ogc:PropertyIsGreaterThan> <ogc:PropertyIsLessThan> <ogc:PropertyName>id</ogc:PropertyName> <ogc:Literal>3.0</ogc:Literal> </ogc:PropertyIsLessThan> </ogc:And> </ogc:Filter> ''' d = QDomDocument('filter') d.setContent(f, True) e = QgsOgcUtils.expressionFromOgcFilter(d.documentElement(), vl) self.assertEqual(e.expression(), 'id > \'1.0\' AND id < \'3.0\'') # Literals are Double 1.5 and 3.5 f = '''<?xml version="1.0" encoding="UTF-8"?> <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"> <ogc:And> <ogc:PropertyIsGreaterThan> <ogc:PropertyName>id</ogc:PropertyName> <ogc:Literal>1.5</ogc:Literal> </ogc:PropertyIsGreaterThan> <ogc:PropertyIsLessThan> <ogc:PropertyName>id</ogc:PropertyName> <ogc:Literal>3.5</ogc:Literal> </ogc:PropertyIsLessThan> </ogc:And> </ogc:Filter> ''' d = QDomDocument('filter') d.setContent(f, True) e = QgsOgcUtils.expressionFromOgcFilter(d.documentElement(), vl) self.assertEqual(e.expression(), 'id > \'1.5\' AND id < \'3.5\'') # Literals are Scientific notation 15e-01 and 35e-01 f = '''<?xml version="1.0" encoding="UTF-8"?> <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"> <ogc:And> <ogc:PropertyIsGreaterThan> <ogc:PropertyName>id</ogc:PropertyName> <ogc:Literal>15e-01</ogc:Literal> </ogc:PropertyIsGreaterThan> <ogc:PropertyIsLessThan> <ogc:PropertyName>id</ogc:PropertyName> <ogc:Literal>35e-01</ogc:Literal> </ogc:PropertyIsLessThan> </ogc:And> </ogc:Filter> ''' d = QDomDocument('filter') d.setContent(f, True) e = QgsOgcUtils.expressionFromOgcFilter(d.documentElement(), vl) self.assertEqual(e.expression(), 'id > \'15e-01\' AND id < \'35e-01\'')
def createSimpleMemorial(self): tempDoc = QDomDocument() simple = QFile(self.simpleMemorial) simple.open(QIODevice.ReadOnly) loaded = tempDoc.setContent(simple) simple.close() element = tempDoc.documentElement() nodes = element.elementsByTagName("table") table = nodes.item(0).toElement() tr = tempDoc.createElement("tr") tr.appendChild( self.createCellElement(tempDoc, u"MEMORIAL DESCRITIVO SINTÉTICO", 7, 0)) table.appendChild(tr) tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, u"VÉRTICE", 0, 2)) tr.appendChild(self.createCellElement(tempDoc, "COORDENADAS", 2, 0)) tr.appendChild(self.createCellElement(tempDoc, "LADO", 0, 2)) tr.appendChild(self.createCellElement(tempDoc, "AZIMUTES", 2, 0)) tr.appendChild(self.createCellElement(tempDoc, u"DISTÂNCIA", 0, 0)) table.appendChild(tr) tr = tempDoc.createElement("tr") tr.appendChild(self.createCellElement(tempDoc, "E", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "N", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "PLANO", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "REAL", 0, 0)) tr.appendChild(self.createCellElement(tempDoc, "(m)", 0, 0)) table.appendChild(tr) convergence = float(self.convergenciaEdit.text()) rowCount = self.tableWidget.rowCount() for i in range(0, rowCount): lineElement = tempDoc.createElement("tr") lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 0).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 1).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 2).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 3).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 4).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 5).text(), 0, 0)) lineElement.appendChild( self.createCellElement(tempDoc, self.tableWidget.item(i, 6).text(), 0, 0)) table.appendChild(lineElement) simple = open(self.simpleMemorial, "w", encoding='utf-8') simple.write(tempDoc.toString()) simple.close()
def loadTemplate(self, filePath): """ Loads a document template into the view and updates the necessary STDM-related composer items. """ if not QFile.exists(filePath): QMessageBox.critical( self.mainWindow(), QApplication.translate("OpenTemplateConfig", "Open Template Error"), QApplication.translate( "OpenTemplateConfig", "The specified template does not exist.")) return copy_file = filePath.replace('sdt', 'cpy') # remove existing copy file if QFile.exists(copy_file): copy_template = QFile(copy_file) copy_template.remove() orig_template_file = QFile(filePath) self.setDocumentFile(orig_template_file) # make a copy of the original result = orig_template_file.copy(copy_file) #templateFile = QFile(filePath) # work with copy templateFile = QFile(copy_file) self.copy_template_file = templateFile if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical( self.mainWindow(), QApplication.translate("ComposerWrapper", "Open Operation Error"), "{0}\n{1}".format( QApplication.translate("ComposerWrapper", "Cannot read template file."), templateFile.errorString())) return templateDoc = QDomDocument() if templateDoc.setContent(templateFile): table_config_collection = TableConfigurationCollection.create( templateDoc) ''' First load vector layers for the table definitions in the config collection before loading the composition from file. ''' load_table_layers(table_config_collection) self.clearWidgetMappings() #Load items into the composition and configure STDM data controls self.composition().loadFromTemplate(templateDoc) #Load data controls composerDS = ComposerDataSource.create(templateDoc) #Set title by appending template name title = QApplication.translate("STDMPlugin", "STDM Document Designer") composer_el = templateDoc.documentElement() if not composer_el is None: template_name = "" if composer_el.hasAttribute("title"): template_name = composer_el.attribute("title", "") elif composer_el.hasAttribute("_title"): template_name = composer_el.attribute("_title", "") if template_name: win_title = "{0} - {1}".format(title, template_name) self.mainWindow().setWindowTitle(template_name) self._configure_data_controls(composerDS) #Load symbol editors spatialFieldsConfig = SpatialFieldsConfiguration.create( templateDoc) self._configureSpatialSymbolEditor(spatialFieldsConfig) #Load photo editors photo_config_collection = PhotoConfigurationCollection.create( templateDoc) self._configure_photo_editors(photo_config_collection) # Load table editors self._configure_table_editors(table_config_collection) #Load chart property editors chart_config_collection = ChartConfigurationCollection.create( templateDoc) self._configure_chart_editors(chart_config_collection) # Load QR code property editors qrc_config_collection = QRCodeConfigurationCollection.create( templateDoc) self._configure_qr_code_editors(qrc_config_collection) self._sync_ids_with_uuids()
class QmlParser(object): def __init__(self, fileName): """ Constructor """ self.fileName = fileName self.qml = QDomDocument() self.qgisElement = None self.edittypesElement = None self.edittypeElementList = [] self.domainDict = dict() def loadFileContent(self): """ Loads QML data """ qml = open(self.fileName, 'r') data = qml.read() loaded = self.qml.setContent(data) qml.close() return loaded def readQGISElement(self): """ Reads the QML's parent node """ self.qgisElement = self.qml.documentElement() def readEdittypesElement(self): """ Read edittypes element """ self.edittypeElementList = [] elements = self.qgisElement.elementsByTagName("edittypes") self.edittypesElement = elements.item(0).toElement() elements = self.edittypesElement.elementsByTagName("edittype") for i in range(len(elements)): self.edittypeElementList.append(elements.item(i).toElement()) def readEdittypeElement(self, edittypeElement): """ Read a specific edittype tag """ type = edittypeElement.attribute("widgetv2type") if type == "ValueMap": name = edittypeElement.attribute("name") valueMapDict = dict() nodes = edittypeElement.elementsByTagName("widgetv2config") widgetv2configElement = nodes.item(0).toElement() values = widgetv2configElement.elementsByTagName("value") for i in range(len(values)): value = values.item(i).toElement() keyText = value.attribute("key") #print 'key: '+keyText valueText = value.attribute("value") #print 'value: '+valueText valueMapDict[keyText] = valueText self.domainDict[name] = valueMapDict elif type == "ValueRelation": name = edittypeElement.attribute("name") nodes = edittypeElement.elementsByTagName("widgetv2config") widgetv2configElement = nodes.item(0).toElement() filter = widgetv2configElement.attribute("FilterExpression") table = widgetv2configElement.attribute("Layer") filter_keys = filter.replace("code in (", "").replace(")", "").split(",") self.domainDict[name] = (table, filter_keys) def getDomainDict(self): """ Gets the domain dictionary (value relation and value map) """ self.domainDict.clear() if not self.loadFileContent(): QMessageBox.warning(self.iface.mainWindow(), self.tr("Warning!"), self.tr("QML file not loaded properly. Enum values won't be available.")) return self.readQGISElement() self.readEdittypesElement() for edittypeElement in self.edittypeElementList: self.readEdittypeElement(edittypeElement) return self.domainDict
def addToDefaultProject(maps, visibleMaps, authcfg=None): """Add basemaps to the existing default project""" layers = [] for m in maps: connstring = u'type=xyz&url={url}' if authcfg is not None: connstring = u'authcfg={authcfg}&' + connstring layer = QgsRasterLayer(connstring.format(url=urllib2.quote("{}?version={}".format(m['endpoint'], pluginSetting("apiVersion"))), authcfg=authcfg), m['name'], 'wms') # I've no idea why the following is required even if the crs is specified # in the layer definition layer.setCrs(QgsCoordinateReferenceSystem('EPSG:3857')) layers.append(layer) if os.path.isfile(defaultProjectPath()): backup = defaultProjectPath().replace( '.qgs', '-%s.qgs' % datetime.now().strftime('%Y-%m-%d-%H_%M_%S')) shutil.copy2(defaultProjectPath(), backup) # open default project with open(defaultProjectPath()) as f: content = f.read() doc = QDomDocument() setOk, errorString, errorLine, errorColumn = doc.setContent(content) if not setOk: return False root = doc.documentElement() for layer in layers: is_visible = layer.name() in visibleMaps xml = QgsMapLayer.asLayerDefinition([layer]) r = xml.documentElement() mapLayerElement = r.firstChildElement("maplayers").firstChildElement("maplayer") layerTreeLayerElement = doc.createElement("layer-tree-layer") layerTreeLayerElement.setAttribute("expanded", "1") layerTreeLayerElement.setAttribute("checked", "Qt::Checked" if is_visible else "Qt::Unchecked") layerTreeLayerElement.setAttribute("id", layer.id()) layerTreeLayerElement.setAttribute("name", layer.name()) customPropertiesElement = doc.createElement("customproperties") layerTreeLayerElement.appendChild(customPropertiesElement) legendLayerElement = doc.createElement("legendlayer") legendLayerElement.setAttribute("drawingOrder", "-1") legendLayerElement.setAttribute("open", "true") legendLayerElement.setAttribute("checked", "Qt::Checked" if is_visible else "Qt::Unchecked") legendLayerElement.setAttribute("name", layer.name()) legendLayerElement.setAttribute("showFeatureCount", "0") filegroupElement = doc.createElement("filegroup") filegroupElement.setAttribute("open", "true") filegroupElement.setAttribute("hidden", "false") legendlayerfileElement = doc.createElement("legendlayerfile") legendlayerfileElement.setAttribute("isInOverview", "0") legendlayerfileElement.setAttribute("layerid", layer.id()) legendlayerfileElement.setAttribute("visible", "1" if is_visible else "0") filegroupElement.appendChild(legendlayerfileElement) legendLayerElement.appendChild(filegroupElement) crsElement = doc.createElement("layer_coordinate_transform") crsElement.setAttribute("destAuthId", "EPSG:3857") crsElement.setAttribute("srcAuthId", "EPSG:3857") crsElement.setAttribute("srcDatumTransform", "-1") crsElement.setAttribute("destDatumTransform", "-1") crsElement.setAttribute("layerid", layer.id()) itemElement = doc.createElement("item") text = doc.createTextNode(layer.id()) itemElement.appendChild(text) e = root.firstChildElement("layer-tree-group") e.appendChild(layerTreeLayerElement) e = root.firstChildElement("mapcanvas").firstChildElement("layer_coordinate_transform_info") e.appendChild(crsElement) e = root.firstChildElement("layer-tree-canvas").firstChildElement("custom-order") e.appendChild(itemElement) e = root.firstChildElement("legend") e.appendChild(legendLayerElement) e = root.firstChildElement("projectlayers") e.appendChild(mapLayerElement) with open(defaultProjectPath(), "wb+") as f: f.write(doc.toString(2)) settings = QSettings() settings.setValue('/qgis/newProjectDefault', True) return True
def test_getcapabilities(self): project = self._project_path assert os.path.exists(project), "Project file not found: " + project # without cache query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % (urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) doc = QDomDocument("wms_getcapabilities_130.xml") doc.setContent(body) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.1.1&REQUEST=%s' % (urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WFS&VERSION=1.1.0&REQUEST=%s' % (urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WFS&VERSION=1.0.0&REQUEST=%s' % (urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WCS&VERSION=1.0.0&REQUEST=%s' % (urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) # without cache query_string = '?MAP=%s&SERVICE=WMTS&VERSION=1.0.0&REQUEST=%s' % (urllib.parse.quote(project), 'GetCapabilities') header, body = self._execute_request(query_string) # with cache header, body = self._execute_request(query_string) filelist = [f for f in os.listdir(self._servercache._cache_dir) if f.endswith(".xml")] self.assertEqual(len(filelist), 6, 'Not enough file in cache') cacheManager = self._server_iface.cacheManager() self.assertTrue(cacheManager.deleteCachedDocuments(None), 'deleteCachedDocuments does not return True') filelist = [f for f in os.listdir(self._servercache._cache_dir) if f.endswith(".xml")] self.assertEqual(len(filelist), 0, 'All files in cache are not deleted ') prj = QgsProject() prj.read(project) query_string = '?MAP=%s&SERVICE=WMS&VERSION=1.3.0&REQUEST=%s' % (urllib.parse.quote(project), 'GetCapabilities') request = QgsBufferServerRequest(query_string, QgsServerRequest.GetMethod, {}, None) accessControls = self._server_iface.accessControls() cDoc = QDomDocument("wms_getcapabilities_130.xml") self.assertFalse(cacheManager.getCachedDocument(cDoc, prj, request, accessControls), 'getCachedDocument is not None') self.assertTrue(cacheManager.setCachedDocument(doc, prj, request, accessControls), 'setCachedDocument false') self.assertTrue(cacheManager.getCachedDocument(cDoc, prj, request, accessControls), 'getCachedDocument is None') self.assertEqual(doc.documentElement().tagName(), cDoc.documentElement().tagName(), 'cachedDocument not equal to provide document') self.assertTrue(cacheManager.deleteCachedDocuments(None), 'deleteCachedDocuments does not return True')
class ConfigurationUtils(): PROFILE = 'Profile' SOCIAL_TENURE = 'SocialTenure' CONFIGURATION = 'Configuration' def __init__(self, document): """ A utility class for STDM configuration. :param document: The configuration :type document: QDomDocument """ self.file_handler = FilePaths() self.log_file_path = '{}/logs/migration.log'.format( self.file_handler.localPath() ) self.document = document def append_log(self, info): """ Append info to a single file :param info: update information to save to file :type info: str """ info_file = open(self.log_file_path, "a") time_stamp = datetime.datetime.now().strftime( '%d-%m-%Y %H:%M:%S' ) info_file.write('\n') info_file.write('{} - '.format(time_stamp)) info_file.write(info) info_file.write('\n') info_file.close() def check_config_file_exists(self, config_file): """ Checks if config file exists :returns True if folder exists else False :rtype bool """ if os.path.isfile(os.path.join( self.file_handler.localPath(), config_file) ): return True else: return False def read_stc(self, config_file_name): """ Reads provided config file :returns QDomDocument, QDomDocument.documentElement() :rtype tuple """ config_file_path = os.path.join( self.file_handler.localPath(), config_file_name ) config_file_path = QFile(config_file_path) config_file = os.path.basename(config_file_name) if self.check_config_file_exists(config_file): self.document = QDomDocument() status, msg, line, col = self.document.setContent(config_file_path) if not status: error_message = 'Configuration file cannot be loaded: {0}'. \ format(msg) self.append_log(str(error_message)) raise ConfigurationException(error_message) self.doc_element = self.document.documentElement() def find_node(self, name): """ Get nodes inside a document by a tag name. :param document: The xml document :type document: QDomDocument :param name: the tag name :type name: String :return: The nodes list :rtype: List """ node_list = self.document.elementsByTagName(name) nodes = [] for i in range(node_list.length()): node = node_list.item(i) nodes.append(node) return nodes def add_attribute_to_nodes(self, nodes, attr, value): """ Adds an attribute with value to node lists. :param nodes: List of nodes :type nodes: QNodeList :param attr: The attribute text :type attr: String :param value: The value of the attribute. :type value: String :return: :rtype: """ for node in nodes: element = node.toElement() element.setAttribute(attr, value) def add_attribute_by_node_name(self, node_name, attr, value): """ Add attribute with value to nodes by node name. :param node_name: The name of the node. :type node_name: Strong :param attr: The attribute text :type attr: String :param value: The value of the attribute. :type value: String :return: :rtype: """ nodes = self.find_node(node_name) self.add_attribute_to_nodes(nodes, attr, value) def profile_first_child(self, tag_name): """ Gets the first child of profile node with a specified tag name. :param tag_name: The tag name to be used to search the child. :type tag_name: String :return: Dictionary of parent (profile node) and the child element. :rtype: OrderedDict """ profile_nodes = self.find_node(self.PROFILE) first_child = OrderedDict() for profile_node in profile_nodes: profile_child = profile_node.firstChildElement( tag_name ) first_child[profile_node] = profile_child return first_child def social_tenure_elements(self): """ Get all social tenure element in a dom_document. :return: List of social tenure element :rtype: OrderedDict """ social_tenure_nodes = self.profile_first_child( self.SOCIAL_TENURE ) return social_tenure_nodes def run(self): nodes = self.find_node('Entity') self.add_attribute_to_nodes(nodes, 'Test', 'One')
def parse_xml(self): """Parse the xml file. Returns false if there is failure.""" xml_file = QFile(self._xml_path) if not xml_file.open(QIODevice.ReadOnly): return False document = QDomDocument() if not document.setContent(xml_file): return False xml_file.close() document_element = document.documentElement() if document_element.tagName() != "qgis_style": return False # Get all the symbols self._symbols = [] symbols_element = document_element.firstChildElement("symbols") symbol_element = symbols_element.firstChildElement() context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) while not symbol_element.isNull(): if symbol_element.tagName() == "symbol": symbol = QgsSymbolLayerUtils.loadSymbol( symbol_element, context) if symbol: self._symbols.append({ "name": symbol_element.attribute("name"), "symbol": symbol }) symbol_element = symbol_element.nextSiblingElement() # Get all the colorramps self._colorramps = [] ramps_element = document_element.firstChildElement("colorramps") ramp_element = ramps_element.firstChildElement() while not ramp_element.isNull(): if ramp_element.tagName() == "colorramp": colorramp = QgsSymbolLayerUtils.loadColorRamp(ramp_element) if colorramp: self._colorramps.append({ "name": ramp_element.attribute("name"), "colorramp": colorramp }) ramp_element = ramp_element.nextSiblingElement() # Get all the TextFormats - textformats - textformat self._textformats = [] textformats_element = document_element.firstChildElement("textformats") textformat_element = textformats_element.firstChildElement() while not textformat_element.isNull(): if textformat_element.tagName() == "textformat": textformat = QgsTextFormat() textformat.readXml(textformat_element, QgsReadWriteContext()) if textformat: self._textformats.append({ "name": textformat_element.attribute("name"), "textformat": textformat, }) textformat_element = textformat_element.nextSiblingElement() # Get all the LabelSettings - labelsettings - labelsetting - # QgsPalLayerSettings.readXML? self._labelsettings = [] labels_element = document_element.firstChildElement("labelsettings") label_element = labels_element.firstChildElement() while not label_element.isNull(): if label_element.tagName() == "labelsetting": labelsettings = QgsPalLayerSettings() labelsettings.readXml(label_element, QgsReadWriteContext()) if labelsettings: self._labelsettings.append({ "name": label_element.attribute("name"), "labelsettings": labelsettings, }) label_element = label_element.nextSiblingElement() return True