コード例 #1
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.')
コード例 #2
0
ファイル: plr.py プロジェクト: openoereb/pyramid_oereb
    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()
コード例 #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.')
コード例 #4
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
コード例 #5
0
    def get_image(self):
        """
        Returns a response containing the binary logo image content using the configured "get_logo_method".

        Returns:
            pyramid.response.Response: Response containing the binary image content.
        """
        logo_key = self._request.matchdict.get('logo')
        logo_language = self._request.matchdict.get('language')
        if (logo_key.upper() == 'CONFEDERATION'):
            logo = Config.get_conferderation_logo()
        elif (logo_key.upper() == 'OEREB'):
            logo = Config.get_oereb_logo()
        elif (logo_key.upper() == 'CANTON'):
            logo = Config.get_canton_logo()
        elif (logo_key.upper() == 'MUNICIPALITY'):
            fosnr = self._request.params['fosnr']
            logo = Config.get_municipality_logo(fosnr)
        else:
            raise HTTPNotFound('This logo does not exist.')
        response = self._request.response
        response.status_int = 200
        response.body = logo.image_dict[logo_language].content
        response.content_type = logo.image_dict[logo_language].mimetype
        return response
コード例 #6
0
ファイル: webservice.py プロジェクト: pfirpfel/pyramid_oereb
    def get_capabilities(self):
        """
        Returns the capabilities of this service.

        Returns:
            pyramid.response.Response: The `capabilities` response.
        """
        themes = list()
        for theme in Config.get_themes():
            text = list()
            for lang in theme.text:
                text.append({
                    'Language': lang,
                    'Text': theme.text[lang]
                })
            themes.append({
                'Code': theme.code,
                'Text': text
            })
        capabilities = {
            u'GetCapabilitiesResponse': {
                u'topic': themes,
                u'municipality': [record.fosnr for record in self._municipality_reader.read()],
                u'flavour': Config.get_flavour(),
                u'language': Config.get_language(),
                u'crs': Config.get_crs()
            }
        }
        renderer_name = 'json' if self._is_json() else 'pyramid_oereb_capabilities_xml'
        response = render_to_response(renderer_name, capabilities, request=self._request)
        if self._is_json():
            response.content_type = 'application/json; charset=UTF-8'
        return response
コード例 #7
0
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
コード例 #8
0
ファイル: plr.py プロジェクト: openoereb/pyramid_oereb
    def read(self, params, real_estate, bbox):  # pylint: disable=W:0221
        """
        The read point which creates a extract, depending on a passed real estate.

        Args:
            params (pyramid_oereb.views.webservice.Parameter): The parameters of the extract request.
            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.
        """
        # 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(
                            Config.get_theme_by_code_sub_code(
                                self._plr_info['code']))
                    ]
                else:
                    # We need to investigate more in detail

                    # Try to find geometries which have spatial relation with real estate
                    geometry_results = self.collect_related_geometries_by_real_estate(
                        session, real_estate)
                    if len(geometry_results) == 0:
                        # We checked if there are spatially related elements in database. But there is none.
                        # So we can stop here.
                        self.records = [
                            EmptyPlrRecord(
                                Config.get_theme_by_code_sub_code(
                                    self._plr_info['code']))
                        ]
                    else:
                        # We found spatially related elements. This means we need to extract the actual plr
                        # information related to the found geometries.
                        self.records = []
                        legend_entries_from_db = self.collect_legend_entries_by_bbox(
                            session, bbox)
                        for geometry_result in geometry_results:
                            self.records.append(
                                self.from_db_to_plr_record(
                                    params,
                                    geometry_result.public_law_restriction,
                                    legend_entries_from_db))

            finally:
                session.close()

        # Add empty record if topic is not available
        else:
            self.records = [
                EmptyPlrRecord(Config.get_theme_by_code_sub_code(
                    self._plr_info['code']),
                               has_data=False)
            ]
コード例 #9
0
ファイル: plr.py プロジェクト: openoereb/pyramid_oereb
    def from_db_to_plr_record(self, params, public_law_restriction_from_db,
                              legend_entries_from_db):
        thresholds = self._plr_info.get('thresholds')
        min_length = thresholds.get('length').get('limit')
        length_unit = thresholds.get('length').get('unit')
        min_area = thresholds.get('area').get('limit')
        area_unit = thresholds.get('area').get('unit')
        legend_entry_record = self.from_db_to_legend_entry_record(
            public_law_restriction_from_db.legend_entry)
        legend_entry_records = self.from_db_to_legend_entry_records(
            legend_entries_from_db, legend_entry_record.theme.sub_code)
        symbol = ImageRecord(
            b64.decode(
                binascii.b2a_base64(
                    public_law_restriction_from_db.legend_entry.symbol).decode(
                        'ascii')))
        view_service_record = self.from_db_to_view_service_record(
            public_law_restriction_from_db.view_service, legend_entry_records,
            self._plr_info.get('code'))
        theme = Config.get_theme_by_code_sub_code(
            public_law_restriction_from_db.legend_entry.theme,
            public_law_restriction_from_db.legend_entry.sub_theme)
        document_records = eliminate_duplicated_document_records(
            theme.document_records,
            self.get_document_records(params, public_law_restriction_from_db))
        geometry_records = self.from_db_to_geometry_records(
            public_law_restriction_from_db.geometries)
        law_status = Config.get_law_status_by_data_code(
            self._plr_info.get('code'),
            public_law_restriction_from_db.law_status)
        sub_theme_legend_entry_record = \
            legend_entry_record.theme if legend_entry_record.theme.sub_code else None
        plr_record = self._plr_record_class(
            Config.get_theme_by_code_sub_code(legend_entry_record.theme.code),
            legend_entry_record,
            law_status,
            public_law_restriction_from_db.published_from,
            public_law_restriction_from_db.published_until,
            self.from_db_to_office_record(
                public_law_restriction_from_db.responsible_office),
            symbol,
            view_service_record,
            geometry_records,
            sub_theme=sub_theme_legend_entry_record,
            type_code=public_law_restriction_from_db.legend_entry.type_code,
            type_code_list=public_law_restriction_from_db.legend_entry.
            type_code_list,
            documents=document_records,
            min_area=min_area,
            min_length=min_length,
            area_unit=area_unit,
            length_unit=length_unit,
            view_service_id=public_law_restriction_from_db.view_service.t_id)

        return plr_record
コード例 #10
0
ファイル: __init__.py プロジェクト: svareg/pyramid_oereb
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
コード例 #11
0
ファイル: plr.py プロジェクト: openoereb/pyramid_oereb
 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
コード例 #12
0
ファイル: test_json.py プロジェクト: sasentom/pyramid_oereb
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')
    }
コード例 #13
0
    def get_capabilities(self):
        """
        Returns the capabilities of this service.

        Returns:
            pyramid.response.Response: The `capabilities` response.
        """

        params = Parameter('json' if self._is_json() else 'xml')

        supported_languages = Config.get_language()
        themes = list()
        for theme in Config.get_themes():
            text = list()
            for lang in theme.text:
                if lang in supported_languages:
                    text.append({'Language': lang, 'Text': theme.text[lang]})
            themes.append({'Code': theme.code, 'Text': text})
        capabilities = {
            u'GetCapabilitiesResponse': {
                u'topic':
                themes,
                u'municipality': [
                    record.fosnr
                    for record in self._municipality_reader.read(params)
                ],
                u'flavour':
                Config.get_flavour(),
                u'language':
                supported_languages,
                u'crs': [Config.get_crs()]
            }
        }

        # Try - catch for backward compatibility with old specification.
        try:
            output_format = self.__validate_format_param__(['xml', 'json'])
        except HTTPBadRequest:
            output_format = None
            log.warning(
                'Deprecated way to specify the format. Use "/capabilities/{format}" instead'
            )
        renderer_name = 'json' if output_format == 'json' or self._is_json(
        ) else 'pyramid_oereb_capabilities_xml'  # noqa: E501
        response = render_to_response(renderer_name,
                                      capabilities,
                                      request=self._request)
        if self._is_json():
            response.content_type = 'application/json; charset=UTF-8'
        response.extras = OerebStats(service='GetCapabilities',
                                     output_format=output_format)
        return response
コード例 #14
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)
コード例 #15
0
    def read(self, nb_ident=None, number=None, egrid=None, geometry=None):
        """
        The central read accessor method to get all desired records from configured source.

        .. note:: If you subclass this class your implementation needs to offer this method in the same
            signature. Means the parameters must be the same and the return must be a list of
            :ref:`api-pyramid_oereb-lib-records-real_estate-realestaterecord`. Otherwise the API like way the
            server works would be broken.

        Args:
            nb_ident (int or None): The identification number of the desired real estate. This
                parameter is directly related to the number parameter and both must be set!
                Combination will deliver only one result or crashes.
            number (str or None): The number of parcel or also known real estate. This parameter
                is directly related to the nb_ident parameter and both must be set!
                Combination will deliver only one result or crashes.
            (str or None): The unique identifier of the desired real estate. This will deliver
                only one result or crashes.
            geometry (str): A geometry as WKT string which is used to obtain intersected real
                estates. This may deliver several results.

        Returns:
            list of pyramid_oereb.lib.records.real_estate.RealEstateRecord:
                The list of all found records filtered by the passed criteria.
        """
        plan_for_land_register_config = Config.get_plan_for_land_register_config(
        )

        real_estate_view_service = ViewServiceRecord(
            plan_for_land_register_config.get('reference_wms'),
            plan_for_land_register_config.get('layer_index'),
            plan_for_land_register_config.get('layer_opacity'))

        plan_for_land_register_main_page_config = Config.get_plan_for_land_register_main_page_config(
        )
        real_estate_main_page_view_service = ViewServiceRecord(
            plan_for_land_register_main_page_config.get('reference_wms'),
            plan_for_land_register_main_page_config.get('layer_index'),
            plan_for_land_register_main_page_config.get('layer_opacity'))

        self._source_.read(nb_ident=nb_ident,
                           number=number,
                           egrid=egrid,
                           geometry=geometry)
        for r in self._source_.records:
            if isinstance(r, RealEstateRecord):
                r.set_view_service(real_estate_view_service)
                r.set_main_page_view_service(
                    real_estate_main_page_view_service)
        return self._source_.records
コード例 #16
0
ファイル: plr.py プロジェクト: openoereb/pyramid_oereb
 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
コード例 #17
0
ファイル: json_.py プロジェクト: sasentom/pyramid_oereb
    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
コード例 #18
0
ファイル: plr.py プロジェクト: kalbermattenm/pyramid_oereb
    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())
コード例 #19
0
ファイル: plr.py プロジェクト: daviddang91/pyramid_oereb
    def from_db_to_geometry_records(self, geometries_from_db):
        geometry_records = []
        for geometry_from_db in geometries_from_db:

            # Create law status record
            law_status = LawStatusRecord.from_config(
                Config.get_law_status(
                    self._plr_info.get('code'),
                    self._plr_info.get('law_status'),
                    geometry_from_db.law_status
                )
            )

            # Create office record
            office = self.from_db_to_office_record(geometry_from_db.responsible_office)

            # Create geometry records
            geometry_records.extend(self.create_geometry_records_(
                law_status,
                geometry_from_db.published_from,
                to_shape(geometry_from_db.geom),
                geometry_from_db.geo_metadata,
                office
            ))

        return geometry_records
コード例 #20
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)
コード例 #21
0
 def __init__(self, **kwargs):
     """
     Keyword Arguments:
         name (str): The name. You are free to choose one.
         code (str): The official code. Regarding to the federal specifications.
         geometry_type (str): The geometry type. Possible are: POINT, POLYGON, LINESTRING,
             GEOMETRYCOLLECTION
         thresholds (dict): The configuration of limits and units used for processing.
         text (dict of str): The speaking title. It must be a dictionary containing language (as
             configured) as key and text as value.
         language (str): The language this public law restriction is originally shipped with.
         federal (bool): Switch if it is a federal topic. This will be taken into account in processing
             steps.
         source (dict): The configuration dictionary of the public law restriction
         hooks (dict of str): The hook methods: get_symbol, get_symbol_ref. They have to be provided as
             dotted string for further use with dotted name resolver of pyramid package.
         law_status (dict of str): The multiple match configuration to provide more flexible use of the
             federal specified classifiers "inKraft" or "AenderungMitVorwirkung"
             or "AenderungOhneVorwirkung".
     """
     super(DatabaseOEREBlexSource, self).__init__(**kwargs)
     config = Config.get_oereblex_config()
     config["code"] = self._plr_info.get('code')
     self._oereblex_source = OEREBlexSource(**config)
     self._queried_geolinks = {}
コード例 #22
0
ファイル: plr.py プロジェクト: pvalsecc/pyramid_oereb
    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)
コード例 #23
0
    def _sort_sub_themes(self, restrictions):
        # split restrictions by theme codes
        split_by_theme_code = self._split_restrictions_by_theme_code(
            restrictions)

        # sort sub themes of the same theme
        for theme_code in split_by_theme_code:
            sub_themes = []
            non_sub_themes = []
            for restriction in split_by_theme_code[theme_code]:
                if restriction.get('Split_SubTheme', False):
                    sub_themes.append(restriction)
                else:
                    non_sub_themes.append(restriction)
            # only sort if there are multiple sub themes
            if len(sub_themes) > 1:
                sorter, params = self._get_sorter(theme_code)
                sub_themes = sorter.sort(sub_themes, params)
            split_by_theme_code[theme_code] = non_sub_themes + sub_themes

        # sort + flatten the split themes again
        sorted_restrictions = []
        for theme in Config.get_themes():
            if theme.code in split_by_theme_code:
                sorted_restrictions += split_by_theme_code[theme.code]

        return sorted_restrictions
コード例 #24
0
ファイル: __init__.py プロジェクト: openoereb/pyramid_oereb
    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
            }
コード例 #25
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
コード例 #26
0
    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
コード例 #27
0
def get_municipality(request):
    """
    Returns the requested municipality logo from database.

    Args:
        request (pyramid.request.Request): The request containing the fosnr as matchdict parameter.

    Returns:
        pyramid.response.Response: The generated response object.
    """
    fosnr = request.matchdict.get('fosnr')
    source_params = Config.get_municipality_config().get('source').get('params')
    session = database_adapter.get_session(source_params.get('db_connection'))
    try:
        model = DottedNameResolver().resolve(source_params.get('model'))
        municipality = session.query(model).filter_by(fosnr=fosnr).first()
        if municipality:
            logo = getattr(municipality, 'logo', None)
            if logo:
                response = request.response
                response.status_int = 200
                response.content_type = 'image/*'
                response.body = base64.b64decode(logo.encode('ascii'))
                return response
        raise HTTPNotFound()
    finally:
        session.close()
コード例 #28
0
 def from_db_to_document_records(self,
                                 legal_provisions_from_db,
                                 article_numbers=None):
     document_records = []
     for i, legal_provision in enumerate(legal_provisions_from_db):
         referenced_documents_db = []
         referenced_article_numbers = []
         for join in legal_provision.referenced_documents:
             referenced_documents_db.append(join.referenced_document)
             referenced_article_nrs = join.article_numbers.split(
                 '|') if join.article_numbers else None
             referenced_article_numbers.append(referenced_article_nrs)
         referenced_document_records = self.from_db_to_document_records(
             referenced_documents_db, referenced_article_numbers)
         article_records = self.from_db_to_article_records(
             legal_provision.articles)
         office_record = self.from_db_to_office_record(
             legal_provision.responsible_office)
         article_nrs = article_numbers[i] if isinstance(
             article_numbers, list) else None
         law_status = LawStatusRecord.from_config(
             Config.get_law_status(self._plr_info.get('code'),
                                   self._plr_info.get('law_status'),
                                   legal_provision.law_status))
         document_records.append(
             self._documents_reocord_class(
                 law_status, legal_provision.published_from,
                 legal_provision.title, office_record,
                 legal_provision.text_at_web, legal_provision.abbreviation,
                 legal_provision.official_number,
                 legal_provision.official_title, legal_provision.canton,
                 legal_provision.municipality, article_nrs,
                 legal_provision.file, article_records,
                 referenced_document_records))
     return document_records
コード例 #29
0
    def __init__(self,
                 type,
                 canton,
                 municipality,
                 fosnr,
                 land_registry_area,
                 limit,
                 metadata_of_geographical_base_data=None,
                 number=None,
                 identdn=None,
                 egrid=None,
                 subunit_of_land_register=None,
                 public_law_restrictions=None,
                 references=None):
        """

        Args:
            type (unicode): The property type. This attribute will be translated with the configured
                corresponding value.
            canton (unicode): The abbreviation of the canton the property is located in
            municipality (unicode): The municipality the property is located in
            fosnr (int): The federal number of the municipality defined by the statistics office
            land_registry_area (int): Area of the property as defined in the land registry
            limit (shapely.geometry.MultiPolygon): The boundary of the property as geometry in as shapely
                multi polygon
            metadata_of_geographical_base_data (uri): Link to the metadata of the geodata
            number (unicode or None):  The official cantonal number of the property
            identdn (unicode or None): The unique identifier of the property
            egrid (unicode or None): The federal property identifier
            subunit_of_land_register (unicode or None): Subunit of the land register if existing
            public_law_restrictions (list of pyramid_oereb.lib.records.plr.PlrRecord or None): List of public
                law restrictions for this real estate
            references (list of pyramid_oereb.lib.records.documents.DocumentRecord or None): Documents
                associated with this real estate
            plan_for_land_register (pyramid_oereb.lib.records.view_service.ViewServiceRecord): The view
                service to be used for the land registry map
            plan_for_land_register_main_page (pyramid_oereb.lib.records.view_service.ViewServiceRecord):
                The view service to be used for the land registry map used on the main page
        """
        self.number = number
        self.identdn = identdn
        self.egrid = egrid
        self.type = Config.get_real_estate_type_by_mapping(type)
        self.canton = canton
        self.municipality = municipality
        self.subunit_of_land_register = subunit_of_land_register
        self.fosnr = fosnr
        self.metadata_of_geographical_base_data = metadata_of_geographical_base_data
        self.land_registry_area = int(round(land_registry_area, 0))
        self.limit = limit
        if isinstance(public_law_restrictions, list):
            self.public_law_restrictions = public_law_restrictions
        else:
            self.public_law_restrictions = []
        if isinstance(references, list):
            self.references = references
        else:
            self.references = []
        self.areas_ratio = self.limit.area / self.land_registry_area
コード例 #30
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()