Example #1
0
    def collect_legend_entries_by_bbox(self, session, bbox):
        """
        Extracts all legend entries in the topic which have spatial relation with the passed bounding box of
        visible extent.

        Args:
            session (sqlalchemy.orm.Session): The requested clean session instance ready for use
            bbox (shapely.geometry.base.BaseGeometry): The bbox to search the records.

        Returns:
            list: The result of the related geometries unique by the public law restriction id
        """
        distinct_legend_entry_ids = []
        geometries = session.query(self._model_).filter(
            or_(
                self._model_.point.ST_Intersects(
                    from_shape(bbox, srid=Config.get('srid'))),
                self._model_.line.ST_Intersects(
                    from_shape(bbox, srid=Config.get('srid'))),
                self._model_.surface.ST_Intersects(
                    from_shape(bbox, srid=Config.get('srid'))))).distinct(
                        self._model_.public_law_restriction_id).all()

        for geometry in geometries:
            if geometry.public_law_restriction.legend_entry_id not in distinct_legend_entry_ids:
                distinct_legend_entry_ids.append(
                    geometry.public_law_restriction.legend_entry_id)

        return session.query(self.legend_entry_model).filter(
            self.legend_entry_model.t_id.in_(
                (distinct_legend_entry_ids))).all()
Example #2
0
    def get_egrid_coord(self):
        """
        Returns a list with the matched EGRIDs for the given coordinates.

        Returns:
            pyramid.response.Response: The `getegrid` response.
        """
        params = Parameter('json' if self._is_json() else 'xml')
        xy = self._params.get('XY')
        gnss = self._params.get('GNSS')
        try:
            if xy or gnss:
                geom_wkt = 'SRID={0};{1}'
                if xy:
                    geom_wkt = geom_wkt.format(
                        Config.get('srid'),
                        self.__parse_xy__(xy, buffer_dist=1.0).wkt)
                elif gnss:
                    geom_wkt = geom_wkt.format(Config.get('srid'),
                                               self.__parse_gnss__(gnss).wkt)
                records = self._real_estate_reader.read(
                    params, **{'geometry': geom_wkt})
                response = self.__get_egrid_response__(records)
            else:
                raise HTTPBadRequest('XY or GNSS must be defined.')
        except HTTPNoContent as err:
            response = HTTPNoContent('{}'.format(err))
        except HTTPBadRequest as err:
            response = HTTPBadRequest('{}'.format(err))
        response.extras = OerebStats(service='GetEgridCoord',
                                     params={
                                         'xy': xy,
                                         'gnss': gnss
                                     })
        return response
Example #3
0
    def _get_egrid_coord(self, params):
        """
        Returns a list with the matched EGRIDs for the given coordinates.

        Args:
            params (pyramid_oereb.views.webservice.Parameter): The parameter object.

        Returns:
            list of pyramid_oereb.core.records.real_estate.RealEstateRecord:
                The list of all found records filtered by the passed criteria.
        """
        en = self._params.get('EN')
        gnss = self._params.get('GNSS')
        if en or gnss:
            geom_wkt = 'SRID={0};{1}'
            if en:
                geom_wkt = geom_wkt.format(
                    Config.get('srid'),
                    self.__parse_en__(en, buffer_dist=1.0).wkt)
            elif gnss:
                geom_wkt = geom_wkt.format(Config.get('srid'),
                                           self.__parse_gnss__(gnss).wkt)
            processor = create_processor()
            return processor.real_estate_reader.read(params,
                                                     **{'geometry': geom_wkt})
        else:
            raise HTTPBadRequest('EN or GNSS must be defined.')
def create_dummy_extract():
    date = datetime.datetime.now()
    real_estate = RealEstateRecord(
        u'test', u'BL', u'Laufen', 2770, 1000, MultiPolygon(),
        ViewServiceRecord('test_link', 1, 1.0, {'de': 'test_legend'}))
    plr_office = OfficeRecord({u'en': u'PLR Authority'})
    resolver = DottedNameResolver()
    date_method_string = Config.get('extract').get('base_data').get(
        'methods').get('date')
    date_method = resolver.resolve(date_method_string)
    av_update_date = date_method(real_estate)
    base_data = Config.get_base_data(av_update_date)

    av_provider_method_string = Config.get('extract').get('base_data').get(
        'methods').get('provider')
    av_provider_method = resolver.resolve(av_provider_method_string)
    cadaster_state = date
    theme = ThemeRecord(u'TEST', {u'de': u'TEST TEXT'})
    datasources = [DatasourceRecord(theme, date, plr_office)]
    plr_cadastre_authority = Config.get_plr_cadastre_authority()
    embeddable = EmbeddableRecord(cadaster_state, plr_cadastre_authority,
                                  av_provider_method(real_estate),
                                  av_update_date, datasources)
    record = ExtractRecord(real_estate, ImageRecord('100'.encode('utf-8')),
                           ImageRecord('100'.encode('utf-8')),
                           ImageRecord('100'.encode('utf-8')),
                           ImageRecord('100'.encode('utf-8')), plr_office,
                           base_data, embeddable)
    return record
Example #5
0
def get_test_extract():
    date = datetime.datetime.now()
    with pyramid_oereb_test_config():
        view_service = ViewServiceRecord(u'http://geowms.bl.ch',
                                         1,
                                         1.0,
                                         u'http://geowms.bl.ch',
                                         None)
        real_estate = RealEstateRecord(u'RealEstate', u'BL', u'Liestal', 2829, 11395,
                                       MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)])]),
                                       u'http://www.geocat.ch', u'1000', u'BL0200002829', u'CH775979211712')
        real_estate.set_view_service(view_service)
        real_estate.set_main_page_view_service(view_service)
        office_record = OfficeRecord({'de': u'AGI'})
        resolver = DottedNameResolver()
        date_method_string = Config.get('extract').get('base_data').get('methods').get('date')
        date_method = resolver.resolve(date_method_string)
        av_update_date = date_method(real_estate)
        base_data = Config.get_base_data(av_update_date)

        av_provider_method_string = Config.get('extract').get('base_data').get('methods').get('provider')
        av_provider_method = resolver.resolve(av_provider_method_string)
        cadaster_state = date
        theme = ThemeRecord(u'TEST', {'de': u'TEST TEXT'})
        datasources = [DatasourceRecord(theme, date, office_record)]
        plr_cadastre_authority = Config.get_plr_cadastre_authority()
        embeddable = EmbeddableRecord(
            cadaster_state,
            plr_cadastre_authority,
            av_provider_method(real_estate),
            av_update_date,
            datasources
        )
        extract = ExtractRecord(
            real_estate,
            ImageRecord('1'.encode('utf-8')),
            ImageRecord('2'.encode('utf-8')),
            ImageRecord('3'.encode('utf-8')),
            ImageRecord('4'.encode('utf-8')),
            office_record,
            base_data,
            embeddable,
            exclusions_of_liability=[
                ExclusionOfLiabilityRecord({'de': u'Haftungsausschluss'}, {'de': u'Test'})
            ],
            glossaries=[GlossaryRecord({'de': u'Glossar'}, {'de': u'Test'})],
            general_information={'de': u'Allgemeine Informationen'},
            certification={'de': u'certification'},
            certification_at_web={'de': u'certification_at_web'},
        )
        # extract.qr_code = 'VGhpcyBpcyBub3QgYSBRUiBjb2Rl'.encode('utf-8') TODO:
        #    qr_code Must be an image ('base64Binary'), but even with images xml validation
        #    fails on it.
        # extract.electronic_signature = 'Signature'  # TODO: fix signature rendering first
        return extract
Example #6
0
 def from_db_to_view_service_record(self, view_service_from_db,
                                    legend_entry_records):
     view_service_record = self._view_service_record_class(
         view_service_from_db.reference_wms,
         view_service_from_db.layer_index,
         view_service_from_db.layer_opacity,
         Config.get('default_language'),
         Config.get('srid'),
         Config.get('proxies'),
         legends=legend_entry_records)
     return view_service_record
Example #7
0
def test_embeddable(params):
    renderer = Renderer(DummyRenderInfo())
    renderer._language = u'de'
    renderer._params = params
    date = datetime.datetime.now()
    view_service = ViewServiceRecord(u'http://geowms.bl.ch',
                                     1,
                                     1.0,
                                     {'de': u'http://geowms.bl.ch'},
                                     None)
    real_estate = RealEstateRecord(
        u'RealEstate',
        u'BL',
        u'Liestal',
        2829,
        11395,
        MultiPolygon([Polygon([(0, 0), (1, 1), (1, 0)])]),
        u'http://www.geocat.ch', u'1000', u'BL0200002829', u'CH775979211712'
    )
    real_estate.plan_for_land_register = view_service
    resolver = DottedNameResolver()
    date_method_string = Config.get('extract').get('base_data').get('methods').get('date')
    date_method = resolver.resolve(date_method_string)
    av_update_date = date_method(real_estate)

    av_provider_method_string = Config.get('extract').get('base_data').get('methods').get('provider')
    av_provider_method = resolver.resolve(av_provider_method_string)
    cadaster_state = date
    theme = ThemeRecord(u'TEST', {u'de': u'TEST TEXT'})
    datasources = [DatasourceRecord(theme, date, OfficeRecord({u'de': u'Test Office'}))]
    plr_cadastre_authority = Config.get_plr_cadastre_authority()
    embeddable = EmbeddableRecord(
        cadaster_state,
        plr_cadastre_authority,
        av_provider_method(real_estate),
        av_update_date,
        datasources
    )
    result = renderer.format_embeddable(embeddable)
    assert result == {
        'cadasterOrganisationName': plr_cadastre_authority.name.get('de'),
        'datasource': [{
            'topic': {
                'Text': {'Text': u'TEST TEXT', 'Language': 'de'},
                'Code': 'TEST'
            },
            'dataownerName': u'Test Office',
            'transferFromSource': date.strftime('%d-%m-%YT%H:%M:%S')
        }],
        'cadasterState': cadaster_state.strftime('%d-%m-%YT%H:%M:%S'),
        'dataOwnerNameCadastralSurveying': u'This is only a dummy',
        'transferFromSourceCadastralSurveying': av_update_date.strftime('%d-%m-%YT%H:%M:%S')
    }
Example #8
0
def test_init():
    date = datetime.datetime.now()
    real_estate = RealEstateRecord(u'test', u'BL', u'Laufen', 2770, 1000, MultiPolygon(), ViewServiceRecord(
        'test_link',
        'test_legend'
    ))
    plr_office = OfficeRecord({u'en': u'PLR Authority'})
    resolver = DottedNameResolver()
    date_method_string = Config.get('extract').get('base_data').get('methods').get('date')
    date_method = resolver.resolve(date_method_string)
    av_update_date = date_method(real_estate)
    base_data = Config.get_base_data(av_update_date)

    av_provider_method_string = Config.get('extract').get('base_data').get('methods').get('provider')
    av_provider_method = resolver.resolve(av_provider_method_string)
    cadaster_state = date
    theme = ThemeRecord(u'TEST', {u'de': u'TEST TEXT'})
    datasources = [DatasourceRecord(theme, date, plr_office)]
    plr_cadastre_authority = Config.get_plr_cadastre_authority()
    embeddable = EmbeddableRecord(
        cadaster_state,
        plr_cadastre_authority,
        av_provider_method(real_estate),
        av_update_date,
        datasources
    )
    record = ExtractRecord(
        real_estate,
        ImageRecord('100'.encode('utf-8')),
        ImageRecord('100'.encode('utf-8')),
        ImageRecord('100'.encode('utf-8')),
        ImageRecord('100'.encode('utf-8')),
        plr_office,
        base_data,
        embeddable
    )
    assert isinstance(record.extract_identifier, str)
    assert isinstance(record.real_estate, RealEstateRecord)
    assert isinstance(record.not_concerned_theme, list)
    assert isinstance(record.concerned_theme, list)
    assert isinstance(record.theme_without_data, list)
    assert isinstance(record.creation_date, datetime.date)
    assert isinstance(record.logo_plr_cadastre, ImageRecord)
    assert isinstance(record.federal_logo, ImageRecord)
    assert isinstance(record.cantonal_logo, ImageRecord)
    assert isinstance(record.municipality_logo, ImageRecord)
    assert isinstance(record.exclusions_of_liability, list)
    assert isinstance(record.glossaries, list)
    assert isinstance(record.plr_cadastre_authority, OfficeRecord)
    assert isinstance(record.base_data, dict)
    assert isinstance(record.embeddable, EmbeddableRecord)
Example #9
0
 def from_db_to_view_service_record(self, view_service_from_db,
                                    legend_entry_records, theme):
     multilingual_uri = from_multilingual_uri_to_dict(
         view_service_from_db.multilingual_uri)
     layer_index, layer_opacity = Config.get_index_and_opacity_of_view_service(
         multilingual_uri)
     view_service_record = self._view_service_record_class(
         multilingual_uri,
         layer_index,
         layer_opacity,
         Config.get('default_language'),
         Config.get('srid'),
         Config.get('proxies'),
         legends=legend_entry_records)
     return view_service_record
Example #10
0
    def _get_egrid_address(self, params):
        """
        Returns a list with the matched EGRIDs for the given postal address.

        Args:
            params (pyramid_oereb.views.webservice.Parameter): The parameter object.

        Returns:
            list of pyramid_oereb.core.records.real_estate.RealEstateRecord:
                The list of all found records filtered by the passed criteria.
        """
        postalcode = self._params.get('POSTALCODE')
        localisation = self._params.get('LOCALISATION')
        number = self._params.get('NUMBER')
        if postalcode and localisation and number:
            reader = AddressReader(
                Config.get_address_config().get('source').get('class'),
                **Config.get_address_config().get('source').get('params'))
            addresses = reader.read(params, localisation, int(postalcode),
                                    number)
            if len(addresses) == 0:
                raise HTTPNoContent()
            geometry = 'SRID={srid};{wkt}'.format(srid=Config.get('srid'),
                                                  wkt=addresses[0].geom.wkt)
            processor = create_processor()
            return processor.real_estate_reader.read(params,
                                                     **{'geometry': geometry})
        else:
            raise HTTPBadRequest(
                'POSTALCODE, LOCALISATION and NUMBER must be defined.')
Example #11
0
    def handle_collection(self, geometry_results, session, collection_types,
                          bbox):

        # Check for Geometry type, cause we can't handle geometry collections the same as specific geometries
        if self._plr_info.get('geometry_type') in [
                x.upper() for x in collection_types
        ]:

            # The PLR is defined as a collection type. We need to do a special handling
            db_bbox_intersection_results = session.query(self._model_).filter(
                self.extract_geometry_collection_db(
                    '{schema}.{table}.geom'.format(
                        schema=self._model_.__table__.schema,
                        table=self._model_.__table__.name), bbox))

            def handle_result(result):
                real_geometry_intersection_result = bbox.intersects(
                    to_shape(result.geom))
                if real_geometry_intersection_result:
                    geometry_results.append(result)

            for result in db_bbox_intersection_results:
                handle_result(result)

        else:

            # The PLR is not problematic at all cause we do not have a collection type here
            geometry_results.extend(
                session.query(self._model_).filter(
                    self._model_.geom.ST_Intersects(
                        from_shape(bbox, srid=Config.get('srid')))).all())
Example #12
0
    def __coord_transform__(self, coord, source_crs):
        """
        Transforms the specified coordinates from the specified CRS to the configured target
        CRS and creates a point geometry.

        Args:
            coord (tuple): The coordinates to transform (x, y).
            source_crs (intorstr): The source CRS

        Returns:
            shapely.geometry.Point or shapely.geometry.Polygon: The transformed coordinates as
            Point.
        """
        log.debug('----- Transforming Coordinates: -----')
        log.debug('----- X/Y Coordinates: {0} -----'.format(coord))
        epsg = 'epsg:{0}'
        srid = Config.get('srid')
        log.debug('----- srid from config (to_srs): {0} -----'.format(srid))
        log.debug(
            '----- srid from source (from_srs): {0} -----'.format(source_crs))
        rp = Reprojector()
        x, y = rp.transform(coord,
                            from_srs=epsg.format(source_crs),
                            to_srs=epsg.format(srid))
        log.debug(
            '----- X/Y coordinates after transformation: ({0}, {1}) -----'.
            format(x, y))
        return Point(x, y)
    def get_wms_url_params():
        """
        Returns the list of additionally configured wms_url_params.

        :return: The configured wms_url_params.
        :rtype: list
        """
        result = {}
        wms_url_params = Config.get('print', {}).get('wms_url_params', False)
        if wms_url_params:
            log.debug("get_wms_url_params() read configuration {}".format(
                wms_url_params))
            if isinstance(wms_url_params, dict):
                result = wms_url_params
            else:
                log.warning(
                    "get_wms_url_params() ignoring unaccepted configuration value {}"
                    .format(wms_url_params))
        else:
            log.info(
                "no wms_url_params configuration detected; using default value"
            )
            result = {'TRANSPARENT': 'true'}

        return result
Example #14
0
    def get_localized_text(self, values, not_null=True):
        """
        Returns the requested language of a multilingual text element.

        Args:
            values (str or dict): The multilingual values encoded as JSON.
            not_null (boolean): Throws an error if there is no value for this language.

        Returns:
            dict of str: Dictionary containing the localized representation.
        """
        default_language = Config.get('default_language')
        if isinstance(values, dict):
            if self._language in values:
                return {
                    'Language': self._language,
                    'Text': get_multilingual_element(values, self._language, not_null)
                }
            else:
                return {
                    'Language': default_language,
                    'Text': get_multilingual_element(values, default_language, not_null)
                }
        else:
            return {
                'Language': default_language,
                'Text': values
            }
Example #15
0
    def extract_geometry_collection_db(db_path, real_estate_geometry):
        """
        Decides the geometry collection cases of geometric filter operations when the database contains multi
        geometries but the passed geometry does not.
        The multi geometry will be extracted to it's sub parts for operation.

        Args:
            db_path (str): The point separated string of schema_name.table_name.column_name from
                which we can construct a correct SQL statement.
            real_estate_geometry (shapely.geometry.base.BaseGeometry): The shapely geometry
                representation which is used for comparison.

        Returns:
            sqlalchemy.sql.elements.BooleanClauseList: The clause element.

        Raises:
            HTTPBadRequest
        """
        srid = Config.get('srid')
        sql_text_point = 'ST_Intersects(ST_CollectionExtract({0}, 1), ST_GeomFromText(\'{1}\', {2}))'.format(
            db_path, real_estate_geometry.wkt, srid)
        sql_text_line = 'ST_Intersects(ST_CollectionExtract({0}, 2), ST_GeomFromText(\'{1}\', {2}))'.format(
            db_path, real_estate_geometry.wkt, srid)
        sql_text_polygon = 'ST_Intersects(ST_CollectionExtract({0}, 3), ' \
                           'ST_GeomFromText(\'{1}\', {2}))'.format(
                                db_path,
                                real_estate_geometry.wkt,
                                srid
                            )
        clause_blocks = [
            text(sql_text_point),
            text(sql_text_line),
            text(sql_text_polygon)
        ]
        return or_(*clause_blocks)
Example #16
0
    def get_custom_wms_params(self, params):
        """
        From a given dictionary filter out all the parameters that are specified in the config
        and return these.
        Only values which exist in the given params are added.
        If there is nothing configured or the config is not a list
        the configured wms_url_params are used as fallback.

        Args:
            params (dict): Parameters available in the URL

        Returns:
            custom_params (dict): dictionary of filtered params
        """
        wms_url_params = Config.get('print', {}).get('wms_url_keep_params',
                                                     False)
        if not isinstance(wms_url_params, list):
            # If no config exists or config is not as expected fall back to use standard wms_url_params
            return self.get_wms_url_params()

        custom_params = {
            wms_keys: self.string_check(wms_values)
            for wms_keys, wms_values in params.items()
            if wms_keys in wms_url_params
        }
        return custom_params
Example #17
0
    def format_geometry(self, geometry):
        """
        Formats a geometry record for rendering according to the federal specification.

        Args:
            geometry (pyramid_oereb.lib.records.geometry.GeometryRecord): The geometry record to
                be formatted.

        Returns:
            dict: The formatted dictionary for rendering.
        """
        geometry_types = Config.get('geometry_types')
        if geometry.geom.type in geometry_types.get('point').get('types'):
            geometry_type = 'Point'
        elif geometry.geom.type in geometry_types.get('line').get('types'):
            geometry_type = 'Line'
        elif geometry.geom.type in geometry_types.get('polygon').get('types'):
            geometry_type = 'Surface'
        else:
            raise TypeError('The geometry type {gtype} is not configured in "geometry_types"'.format(
                gtype=geometry.geom.type
            ))

        geometry_dict = {
            geometry_type: self.from_shapely(geometry.geom),
            'Lawstatus': self.format_law_status(geometry.law_status),
            'ResponsibleOffice': self.format_office(geometry.office)
        }

        if geometry.geo_metadata is not None:
            geometry_dict['MetadataOfGeographicalBaseData'] = geometry.geo_metadata

        return geometry_dict
Example #18
0
    def __init__(self, info):
        """
        Creates a new base renderer instance.

        Args:
            info (pyramid.interfaces.IRendererInfo): Info object.
        """
        self._info_ = info
        self._language = str(Config.get('default_language')).lower()
Example #19
0
    def get_egrid_coord(self):
        """
        Returns a list with the matched EGRIDs for the given coordinates.

        Returns:
            pyramid.response.Response: The `getegrid` response.
        """
        xy = self._request.params.get('XY')
        gnss = self._request.params.get('GNSS')
        if xy or gnss:
            geom_wkt = 'SRID={0};{1}'
            if xy:
                geom_wkt = geom_wkt.format(Config.get('srid'),
                                           self.__parse_xy__(xy, buffer_dist=1.0).wkt)
            elif gnss:
                geom_wkt = geom_wkt.format(Config.get('srid'), self.__parse_gnss__(gnss).wkt)
            records = self._real_estate_reader.read(**{'geometry': geom_wkt})
            return self.__get_egrid_response__(records)
        else:
            raise HTTPBadRequest('XY or GNSS must be defined.')
def get_symbol(request):
    """
    Returns the symbol for the requested theme and type code from database.

    Args:
        request (pyramid.request.Request): The request containing the codes as matchdict parameters.

    Returns:
        pyramid.response.Response: The generated response object.
    """

    theme_code = request.matchdict.get('theme_code')

    plr = None
    for p in Config.get('plrs'):
        if str(p.get('code')).lower() == str(theme_code).lower():
            plr = p
            break

    if plr is None:
        raise HTTPNotFound('No theme with code {}.'.format(theme_code))

    source_params = plr.get('source').get('params')
    session = database_adapter.get_session(source_params.get('db_connection'))

    type_code = request.params.get('CODE')
    legend_text = request.params.get('TEXT')

    if type_code is None:
        raise HTTPBadRequest('Missing parameter CODE.')
    if legend_text is None:
        raise HTTPBadRequest('Missing parameter TEXT.')

    try:
        model = DottedNameResolver().resolve('{module_}.{class_}'.format(
            module_=source_params.get('models'), class_='LegendEntry'))
        legend_entry = session.query(model).filter(
            cast(model.type_code, Text) == cast(type_code, Text),
            cast(model.legend_text, Text) == json.dumps(
                json.loads(
                    base64.b64decode(legend_text).decode(
                        'unicode-escape'))).decode('unicode-escape')).first()
        if legend_entry:
            symbol = getattr(legend_entry, 'symbol', None)
            if symbol:
                response = request.response
                response.status_int = 200
                response.content_type = 'image/*'
                response.body = base64.b64decode(symbol.encode('ascii'))
                return response
        raise HTTPNotFound()

    finally:
        session.close()
Example #21
0
    def handle_collection(self, session, geometry_to_check):
        geometry_types = Config.get('geometry_types')
        collection_types = geometry_types.get('collection').get('types')
        # Check for Geometry type, cause we can't handle geometry collections the same as specific geometries
        if self._plr_info.get('geometry_type') in [
                x.upper() for x in collection_types
        ]:

            # The PLR is defined as a collection type. We need to do a special handling
            query = session.query(self._model_).filter(
                self.extract_geometry_collection_db(
                    '{schema}.{table}.geom'.format(
                        schema=self._model_.__table__.schema,
                        table=self._model_.__table__.name), geometry_to_check))

        else:
            # The PLR is not problematic at all cause we do not have a collection type here
            query = session.query(self._model_).filter(
                self._model_.geom.ST_Intersects(
                    from_shape(geometry_to_check, srid=Config.get('srid'))))
        return query
Example #22
0
    def get_image(self):
        """
        Returns a response containing the binary image content using the configured "get_municipality_method".

        Returns:
            pyramid.response.Response: Response containing the binary image content.
        """
        method = Config.get('get_municipality_method')
        if method:
            return DottedNameResolver().resolve(method)(self._request_)
        log.error('"get_municipality_method" not found')
        raise HTTPNotFound()
Example #23
0
def get_symbol(request):
    """
    Returns the symbol for the requested theme and type code from database.

    Args:
        request (pyramid.request.Request): The request containing the codes as matchdict parameters.

    Returns:
        pyramid.response.Response: The generated response object.
    """

    theme_code = request.matchdict.get('theme_code')
    view_service_id = request.matchdict.get('view_service_id')
    type_code = request.matchdict.get('type_code')

    plr = None
    for p in Config.get('plrs'):
        if str(p.get('code')).lower() == str(theme_code).lower():
            plr = p
            break

    if plr is None:
        raise HTTPNotFound('No theme with code {}.'.format(theme_code))

    session = database_adapter.get_session(
        plr.get('source').get('params').get('db_connection'))

    try:
        config_parser = StandardThemeConfigParser(**plr)
        models = config_parser.get_models()
        model = models.LegendEntry
        legend_entry = session.query(model).filter(
            cast(model.type_code, Text) == cast(type_code, Text)).filter(
                model.view_service_id == view_service_id).first()
        if legend_entry:
            symbol = getattr(legend_entry, 'symbol', None)
            if symbol:
                response = request.response
                response.status_int = 200
                if isinstance(symbol, str):
                    response.body = b64.decode(symbol)
                if isinstance(symbol, bytes):
                    response.body = b64.decode(
                        binascii.b2a_base64(symbol).decode('ascii'))
                response.content_type = ImageRecord.get_mimetype(
                    bytearray(response.body))
                return response
        raise HTTPNotFound()

    finally:
        session.close()
Example #24
0
    def collect_related_geometries_by_real_estate(self, session, real_estate):
        """
        Extracts all geometries in the topic which have spatial relation with the passed real estate

        Args:
            session (sqlalchemy.orm.Session): The requested clean session instance ready for use
            real_estate (pyramid_oereb.lib.records.real_estate.RealEstateRecord): The real
                estate in its record representation.

        Returns:
            list: The result of the related geometries unique by the public law restriction id
        """

        return session.query(self._model_).filter(
            or_(
                self._model_.point.ST_Intersects(
                    from_shape(real_estate.limit, srid=Config.get('srid'))),
                self._model_.line.ST_Intersects(
                    from_shape(real_estate.limit, srid=Config.get('srid'))),
                self._model_.surface.ST_Intersects(
                    from_shape(
                        real_estate.limit,
                        srid=Config.get('srid'))))).distinct(
                            self._model_.public_law_restriction_id).all()
Example #25
0
    def read(self, real_estate, bbox):
        """
        The read point which creates a extract, depending on a passed real estate.

        Args:
            real_estate (pyramid_oereb.lib.records.real_estate.RealEstateRecord): The real
                estate in its record representation.
            bbox (shapely.geometry.base.BaseGeometry): The bbox to search the records.
        """
        geometry_types = Config.get('geometry_types')
        collection_types = geometry_types.get('collection').get('types')

        # Check if the plr is marked as available
        if self._is_available(real_estate):

            session = self._adapter_.get_session(self._key_)

            try:

                if session.query(self._model_).count() == 0:
                    # We can stop here already because there are no items in the database
                    self.records = [
                        EmptyPlrRecord(self._theme_record, has_data=True)
                    ]

                else:

                    geometry_results = []
                    self.handle_collection(geometry_results, session,
                                           collection_types, bbox)

                    if len(geometry_results) == 0:
                        self.records = [EmptyPlrRecord(self._theme_record)]
                    else:
                        self.records = []
                        for geometry_result in geometry_results:
                            self.records.append(
                                self.from_db_to_plr_record(
                                    geometry_result.public_law_restriction))

            finally:
                session.close()

        # Add empty record if topic is not available
        else:
            self.records = [EmptyPlrRecord(self._theme_record, has_data=False)]
Example #26
0
def get_symbol(request):
    """
    Returns the symbol for the requested theme and type code from database.

    Args:
        request (pyramid.request.Request): The request containing the codes as matchdict parameters.

    Returns:
        pyramid.response.Response: The generated response object.
    """

    theme_code = request.matchdict.get('theme_code')
    view_service_id = request.matchdict.get('view_service_id')
    type_code = request.matchdict.get('type_code')

    plr = None
    for p in Config.get('plrs'):
        if str(p.get('code')).lower() == str(theme_code).lower():
            plr = p
            break

    if plr is None:
        raise HTTPNotFound('No theme with code {}.'.format(theme_code))

    source_params = plr.get('source').get('params')
    session = database_adapter.get_session(source_params.get('db_connection'))

    try:
        model = DottedNameResolver().resolve('{module_}.{class_}'.format(
            module_=source_params.get('models'), class_='LegendEntry'))
        legend_entry = session.query(model).filter(
            cast(model.type_code, Text) == cast(type_code, Text)).filter(
                model.view_service_id == view_service_id).first()
        if legend_entry:
            symbol = getattr(legend_entry, 'symbol', None)
            if symbol:
                response = request.response
                response.status_int = 200
                response.body = b64.decode(symbol)
                response.content_type = ImageRecord.get_mimetype(
                    bytearray(response.body))
                return response
        raise HTTPNotFound()

    finally:
        session.close()
Example #27
0
    def from_shapely(geom):
        """
        Formats shapely geometry for rendering according to the federal specification.

        Args:
            geom (shapely.geometry.base.BaseGeometry): The geometry object to be formatted.

        Returns:
            dict: The formatted geometry.
        """
        geom_dict = {
            'coordinates': mapping(geom)['coordinates'],
            'crs': 'EPSG:{srid}'.format(srid=Config.get('srid'))
            # isosqlmmwkb only used for curved geometries (not supported by shapely)
            # 'isosqlmmwkb': b64.encode(geom.wkb)
        }
        return geom_dict
Example #28
0
    def get_image(self):
        """
        Returns a response containing the binary image content using the configured "get_symbol_method".

        Returns:
            pyramid.response.Response: Response containing the binary image content.
        """
        method = None
        dnr = DottedNameResolver()
        for plr in Config.get('plrs'):
            if str(plr.get('code')).lower() == str(self._request_.matchdict.get('theme_code')).lower():
                method = dnr.resolve(plr.get('hooks').get('get_symbol'))
                break
        if method:
            return method(self._request_)
        log.error('"get_symbol_method" not found')
        raise HTTPNotFound()
Example #29
0
    def read(self, street_name, zip_code, street_number):
        """
        Queries an address using the federal GeoAdmin API location search.

        Args:
            street_name (unicode): The name of the street for the desired address.
            zip_code (int): The postal zipcode for the desired address.
            street_number (unicode): The house or so called street number of the desired address.
        """
        headers = {
            'Referer':
            'http://bl.ch'  # TODO: Remove this header when referer is not needed anymore!
        }
        params = {
            'type':
            self._type,
            'origins':
            self._origins,
            'searchText':
            u'{0} {1} {2}'.format(zip_code, street_name, street_number)
        }
        response = requests.get(self._geoadmin_url,
                                params=params,
                                proxies=self._proxies,
                                headers=headers)
        if response.status_code == requests.codes.ok:
            rp = Reprojector()
            srid = Config.get('srid')
            self.records = list()
            data = response.json()
            if 'results' in data:
                for item in data.get('results'):
                    attrs = item.get('attrs')
                    if isinstance(attrs,
                                  dict) and attrs.get('origin') == 'address':
                        x, y = rp.transform(
                            (attrs.get('lon'), attrs.get('lat')), to_srs=srid)
                        self.records.append(
                            AddressRecord(street_name=street_name,
                                          zip_code=zip_code,
                                          street_number=street_number,
                                          geom='POINT({x} {y})'.format(x=x,
                                                                       y=y)))
        else:
            response.raise_for_status()
Example #30
0
    def __coord_transform__(self, coord, source_crs):
        """
        Transforms the specified coordinates from the specified CRS to the configured target CRS and creates a
        point geometry.

        Args:
            coord (tuple): The coordinates to transform (x, y).
            source_crs (intorstr): The source CRS

        Returns:
            shapely.geometry.Point or shapely.geometry.Polygon: The transformed coordinates as
            Point.
        """
        epsg = 'epsg:{0}'
        srid = Config.get('srid')
        rp = Reprojector()
        x, y = rp.transform(coord, from_srs=epsg.format(source_crs), to_srs=epsg.format(srid))
        return Point(x, y)