def saveMetadata(layer, mefFilename=None, apiUrl=None, wms=None, wfs=None, layerName=None):
    uuid = uuidForLayer(layer)
    _, safe_name = getLayerTitleAndName(layer)
    filename = tempFileInSubFolder(safe_name + ".qmd")
    layer.saveNamedMetadata(filename)
    thumbnail = _saveLayerThumbnail(layer)
    apiUrl = apiUrl or ""
    transformedFilename = _transformMetadata(filename, uuid, apiUrl, wms, wfs, layerName or safe_name)
    mefFilename = mefFilename or tempFileInSubFolder(uuid + ".mef")
    _createMef(uuid, transformedFilename, mefFilename, thumbnail)
    return mefFilename
 def publishStyle(self, layer):
     lyr_title, lyr_name = lyr_utils.getLayerTitleAndName(layer)
     export_layer = lyr_utils.getExportableLayer(layer, lyr_name)
     style_filename = tempFileInSubFolder(lyr_name + ".zip")
     warnings = saveLayerStyleAsZippedSld(export_layer, style_filename)
     for w in warnings:
         self.logWarning(w)
     self.logInfo(f"Style for layer '{layer.name()}' exported as ZIP file to '{style_filename}'")
     self._publishStyle(lyr_name, style_filename)
     self._published_layers.add(layer)
     return style_filename
Beispiel #3
0
def _transformMetadata(filename, uuid, api_url, wms, wfs, layer_name):
    def _ns(n):
        return f"{{http://www.isotc211.org/2005/gmd}}{n}"

    def _addServiceElement(root_element, md_layer, service_url, service_type):
        trans = ET.SubElement(root_element, _ns("transferOptions"))
        dtrans = ET.SubElement(trans, _ns("MD_DigitalTransferOptions"))
        online = ET.SubElement(dtrans, _ns("onLine"))
        cionline = ET.SubElement(online, _ns("CI_OnlineResource"))
        linkage = ET.SubElement(cionline, _ns("linkage"))
        url = ET.SubElement(linkage, _ns("URL"))
        url.text = service_url
        protocol = ET.SubElement(cionline, _ns("protocol"))
        cs = ET.SubElement(
            protocol, "{http://www.isotc211.org/2005/gco}CharacterString")
        cs.text = f"OGC:{service_type.upper()}"
        name = ET.SubElement(cionline, _ns("name"))
        csname = ET.SubElement(
            name, "{http://www.isotc211.org/2005/gco}CharacterString")
        csname.text = md_layer

    iso_filename = tempFileInSubFolder("metadata.xml")
    feedback.logInfo(f"Creating metadata export file {iso_filename}")
    out_dom = _transformDom(filename, QMD_TO_ISO19139_XSLT)

    for ident in out_dom.iter(_ns("fileIdentifier")):
        ident[0].text = uuid
    if wms is not None:
        for root in out_dom.iter(_ns("MD_Distribution")):
            _addServiceElement(root, layer_name, wms, "wms")
    if wfs is not None:
        for root in out_dom.iter(_ns("MD_Distribution")):
            _addServiceElement(root, layer_name, wfs, "wfs")
    for root in out_dom.iter(_ns("MD_DataIdentification")):
        overview = ET.SubElement(root, _ns("graphicOverview"))
        browse_graphic = ET.SubElement(overview, _ns("MD_BrowseGraphic"))
        file = ET.SubElement(browse_graphic, _ns("fileName"))
        cs = ET.SubElement(
            file, "{http://www.isotc211.org/2005/gco}CharacterString")
        thumbnail_url = f"{api_url}/records/{uuid}/attachments/thumbnail.png"
        cs.text = thumbnail_url

    _writeDom(out_dom, iso_filename)
    return iso_filename
def _saveLayerThumbnail(layer):
    filename = tempFileInSubFolder("thumbnail.png")
    img = QImage(QSize(800, 800), QImage.Format_A2BGR30_Premultiplied)
    color = QColor(255, 255, 255, 255)
    img.fill(color.rgba())
    p = QPainter()
    p.begin(img)
    p.setRenderHint(QPainter.Antialiasing)
    ms = QgsMapSettings()
    ms.setBackgroundColor(color)
    ms.setLayers([layer])
    ms.setExtent(layer.extent())
    ms.setOutputSize(img.size())
    render = QgsMapRendererCustomPainterJob(ms, p)
    render.start()
    render.waitForFinished()
    p.end()
    img.save(filename)
    return filename
Beispiel #5
0
def exportLayer(layer,
                fields=None,
                to_shapefile=False,
                path=None,
                force=False,
                logger=None):
    logger = logger or feedback
    filepath, _, ext = lyr_utils.getLayerSourceInfo(layer)
    lyr_name, safe_name = lyr_utils.getLayerTitleAndName(layer)
    fields = fields or []
    if layer.type() == layer.VectorLayer:
        if to_shapefile and (force or layer.fields().count() != len(fields)
                             or ext != EXT_SHAPEFILE):
            # Export with Shapefile extension
            ext = EXT_SHAPEFILE
        elif force or ext != EXT_GEOPACKAGE or layer.fields().count() != len(fields) \
                or not isSingleTableGpkg(filepath):
            # Export with GeoPackage extension
            ext = EXT_GEOPACKAGE
        else:
            # No need to export
            logger.logInfo(
                f"No need to export layer {lyr_name} stored at {filepath}")
            return filepath

        # Perform GeoPackage or Shapefile export
        attrs = [
            i for i, f in enumerate(layer.fields())
            if len(fields) == 0 or f.name() in fields
        ]
        output = path or tempFileInSubFolder(safe_name + ext)
        encoding = "UTF-8"
        driver = "ESRI Shapefile" if ext == EXT_SHAPEFILE else "GPKG"
        options = None
        if hasattr(QgsVectorFileWriter, 'SaveVectorOptions'):
            # QGIS v3.x has the SaveVectorOptions object
            options = QgsVectorFileWriter.SaveVectorOptions()
            options.fileEncoding = encoding
            options.attributes = attrs
            options.driverName = driver
        # Make sure that we are using the latest (non-deprecated) write method
        if hasattr(QgsVectorFileWriter, 'writeAsVectorFormatV3'):
            # Use writeAsVectorFormatV3 for QGIS versions >= 3.20 to avoid DeprecationWarnings
            result = QgsVectorFileWriter.writeAsVectorFormatV3(
                layer, output, QgsCoordinateTransformContext(),
                options)  # noqa
        elif hasattr(QgsVectorFileWriter, 'writeAsVectorFormatV2'):
            # Use writeAsVectorFormatV2 for QGIS versions >= 3.10.3 to avoid DeprecationWarnings
            result = QgsVectorFileWriter.writeAsVectorFormatV2(
                layer, output, QgsCoordinateTransformContext(),
                options)  # noqa
        else:
            # Use writeAsVectorFormat for QGIS versions < 3.10.3 for backwards compatibility
            result = QgsVectorFileWriter.writeAsVectorFormat(
                layer,
                output,
                fileEncoding=encoding,
                attributes=attrs,
                driverName=driver)  # noqa
        # Check if first item in result tuple is an error code
        if result[0] == QgsVectorFileWriter.NoError:
            logger.logInfo(f"Layer {lyr_name} exported to {output}")
        else:
            # Dump the result tuple as-is when there are errors (the tuple size depends on the QGIS version)
            logger.logError(
                f"Layer {lyr_name} failed to export.\n\tResult object: {str(result)}"
            )
        return output
    else:
        # Export raster
        if force or not filepath.lower().endswith("tif"):
            output = path or tempFileInSubFolder(safe_name + ".tif")
            writer = QgsRasterFileWriter(output)
            writer.setOutputFormat("GTiff")
            writer.writeRaster(layer.pipe(), layer.width(), layer.height(),
                               layer.extent(), layer.crs())
            del writer
            logger.logInfo(f"Layer {lyr_name} exported to {output}")
            return output
        else:
            logger.logInfo(
                f"No need to export layer {lyr_name} stored at {filepath}")
            return filepath
def _loadMetadataFromFgdcXml(layer, filename):
    iso_filename = tempFileInSubFolder("fromfgdc.xml")
    feedback.logInfo(f"Exporting FGDC metadata to {iso_filename}")
    _convertMetadata(filename, iso_filename, FGDC_TO_ISO19115)
    _loadMetadataFromEsriXml(layer, iso_filename)
def _loadMetadataFromWrappingEsriXml(layer, filename):
    iso_filename = tempFileInSubFolder("fromesri.xml")
    feedback.logInfo(f"Exporting Wrapping-ISO19115 metadata to {iso_filename}")
    _convertMetadata(filename, iso_filename, WRAPPING_ISO19115_TO_ISO19139_XSLT)
    _loadMetadataFromIsoXml(layer, iso_filename)
def _loadMetadataFromIsoXml(layer, filename):
    qmd_filename = tempFileInSubFolder("fromiso.qmd")
    feedback.logInfo(f"Exporting ISO19193 metadata to {qmd_filename}")
    _convertMetadata(filename, qmd_filename, ISO19139_TO_QMD_XSLT)
    layer.loadNamedMetadata(qmd_filename)