'Apply method.
@param r: the S3Request
@param attr: controller options for this request'

@staticmethod
def apply_method(r, **attr):

    if (r.representation == 'html'):
        T = current.T
        s3db = current.s3db
        request = current.request
        response = current.response
        settings = current.deployment_settings
        s3 = current.response.s3
        title = T('Import    from    OpenStreetMap')
        resources_list = settings.get_gis_poi_export_resources()
        uploadpath = os.path.join(request.folder, 'uploads/')
        from s3utils import s3_yes_no_represent
        fields = [Field('text1', label='', default=T('Can    read    PoIs    either    from    an    OpenStreetMap    file    (.osm)    or    mirror.'), writable=False), Field('file', 'upload', length=current.MAX_FILENAME_LENGTH, uploadfolder=uploadpath, label=T('File')), Field('text2', label='', default='Or', writable=False), Field('host', default='localhost', label=T('Host')), Field('database', default='osm', label=T('Database')), Field('user', default='osm', label=T('User')), Field('password', 'string', default='planet', label=T('Password')), Field('ignore_errors', 'boolean', label=T('Ignore    Errors?'), represent=s3_yes_no_represent), Field('resources', label=T('Select    resources    to    import'), requires=IS_IN_SET(resources_list, multiple=True), default=resources_list, widget=SQLFORM.widgets.checkboxes.widget)]
        if (not r.id):
            from s3validators import IS_LOCATION
            from s3widgets import S3LocationAutocompleteWidget
            field = s3db.org_office.location_id
            field.requires = IS_EMPTY_OR(IS_LOCATION())
            field.widget = S3LocationAutocompleteWidget()
            fields.insert(3, field)
        from s3utils import s3_mark_required
        (labels, required) = s3_mark_required(fields, ['file', 'location_id'])
        s3.has_required = True
        form = SQLFORM.factory(formstyle=settings.get_ui_formstyle(), submit_button=T('Import'), labels=labels, separator='', table_name='import_poi', *fields)
        response.view = 'create.html'
        output = dict(title=title, form=form)
        if form.accepts(request.vars, current.session):
            form_vars = form.vars
            if (form_vars.file != ''):
                File = open((uploadpath + form_vars.file), 'r')
            else:
                if r.record:
                    record = r.record
                elif (not form_vars.location_id):
                    form.errors['location_id'] = T('Location    is    Required!')
                    return output
                else:
                    gtable = s3db.gis_location
                    record = current.db((gtable.id == form_vars.location_id)).select(gtable.name, gtable.wkt, limitby=(0, 1)).first()
                    if (record.wkt is None):
                        form.errors['location_id'] = T('Location    needs    to    have    WKT!')
                        return output
                error = GIS.create_poly(record)
                if error:
                    current.session.error = error
                    redirect(URL(args=r.id))
                name = record.name
                if os.path.exists(os.path.join(os.getcwd(), 'temp')):
                    TEMP = os.path.join(os.getcwd(), 'temp')
                else:
                    import tempfile
                    TEMP = tempfile.gettempdir()
                filename = os.path.join(TEMP, ('%s.osm' % name))
                cmd = ['/home/osm/osmosis/bin/osmosis', '--read-pgsql', ('host=%s' % form_vars.host), ('database=%s' % form_vars.database), ('user=%s' % form_vars.user), ('password=%s' % form_vars.password), '--dataset-dump', '--bounding-polygon', ('file=%s' % os.path.join(TEMP, ('%s.poly' % name))), '--write-xml', ('file=%s' % filename)]
                import subprocess
                try:
                    subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
                except subprocess.CalledProcessError as e:
                    current.session.error = (T('OSM    file    generation    failed:    %s') % e.output)
                    redirect(URL(args=r.id))
                except AttributeError:
                    error = subprocess.call(cmd, shell=True)
                    if error:
                        current.log.debug(cmd)
                        current.session.error = T('OSM    file    generation    failed!')
                        redirect(URL(args=r.id))
                try:
                    File = open(filename, 'r')
                except:
                    current.session.error = T('Cannot    open    created    OSM    file!')
                    redirect(URL(args=r.id))
            stylesheet = os.path.join(request.folder, 'static', 'formats', 'osm', 'import.xsl')
            ignore_errors = form_vars.get('ignore_errors', None)
            xml = current.xml
            tree = xml.parse(File)
            define_resource = s3db.resource
            response.error = ''
            import_count = 0
            import_res = list((set(form_vars['resources']) & set(resources_list)))
            for tablename in import_res:
                try:
                    s3db[tablename]
                except:
                    continue
                resource = define_resource(tablename)
                s3xml = xml.transform(tree, stylesheet_path=stylesheet, name=resource.name)
                try:
                    resource.import_xml(s3xml, ignore_errors=ignore_errors)
                    import_count += resource.import_count
                except:
                    response.error += str(sys.exc_info()[1])
            if import_count:
                response.confirmation = ('%s    %s' % (import_count, T('PoIs    successfully    imported.')))
            else:
                response.information = T('No    PoIs    available.')
        return output
    else:
        raise HTTP(405, current.ERROR.BAD_METHOD)
