Class: Layer

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/layer.rb

Defined Under Namespace

Modules: Geo

Constant Summary collapse

@@default_selection_styles =
{
  'POLYGON' =>
    '<PolygonSymbolizer>'+
      '<Fill>'+
        '<CssParameter name="fill">#ff0090</CssParameter>'+
        '<CssParameter name="fill-opacity">0.6</CssParameter>'+
      '</Fill>'+
      '<Stroke>'+
        '<CssParameter name="stroke">#ff0090</CssParameter>'+
        '<CssParameter name="stroke-width">2.00</CssParameter>'+
      '</Stroke>'+
    '</PolygonSymbolizer>',
  'LINESTRING' =>
    '<LineSymbolizer>'+
      '<Stroke>'+
        '<CssParameter name="stroke">#ff0090</CssParameter>'+
        '<CssParameter name="stroke-width">10.00</CssParameter>'+
      '</Stroke>'+
    '</LineSymbolizer>',
  'POINT' =>
    '<PointSymbolizer>'+
       '<Graphic>'+
         '<Mark>'+
           '<WellKnownName>circle</WellKnownName>'+
           '<Fill>'+
             '<CssParameter name="fill">#ff0090</CssParameter>'+
           '</Fill>'+
         '</Mark>'+
         '<Size>45.0</Size>'+
       '</Graphic>'+
     '</PointSymbolizer>'
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_selection_stylesObject



352
353
354
# File 'app/models/layer.rb', line 352

def self.default_selection_styles
  @@default_selection_styles
end

.list(ability, layer_type, topic_name) ⇒ Object

Structure for Topic selection



27
28
29
30
31
32
33
34
# File 'app/models/layer.rb', line 27

def self.list(ability, layer_type, topic_name)
  ActiveRecord::Base.silence do
    topic = Topic.accessible_by(ability).includes(:layers).where(:name => topic_name).first
    layers = topic.nil? ? [] : topic.layers.accessible_by(ability).all
    topic_layers = topic.nil? ? [] : topic.topics_layers.select {|tl| layers.include?(tl.layer) }
    wms_layer_list(ability, topic, topic_layers)
  end
end

.set_default_selection_styles(styles) ⇒ Object



348
349
350
# File 'app/models/layer.rb', line 348

def self.set_default_selection_styles(styles)
  @@default_selection_styles = styles
end

.wms_layer_list(ability, topic, topic_layers) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'app/models/layer.rb', line 36

def self.wms_layer_list(ability, topic, topic_layers)
  wms_layers = topic_layers.collect do |topic_layer|
    layer = topic_layer.layer
    {
      "id" => topic_layer.id,
      "layername"=> layer.name,
      "topic"=> topic.name,
      "groupname" => layer.sublayer_group.try(:name),
      "toclayertitle"=> layer.title,
      "leglayertitle"=> layer.title,
      "showscale"=> "true",
      "minscale"=> layer.minscale,
      "maxscale"=> layer.maxscale,
      "wms_sort"=> topic_layer.wms_sort, # MapServer layer order
      #"leg_sort"=> topic_layer.leg_sort, # Not used client side (Legend sort is in defined in HTML). Query result order. 
      #"query_sort"=> topic_layer.leg_sort, # deprecated
      "toc_sort"=> topic_layer.toc_sort, # Layer tree order
      "wms"=> "false",
      "visini"=> topic_layer.visini,
      "visuser"=> topic_layer.visini, #User visibility is in request_state
      "showtoc"=> "true",
      "editeable"=> ability.can?(:edit, layer)
    }
  end
  {
    "success" => true,
    "messageProperty"=> {"topic"=> topic.name, "legendtitle"=> "Legende", "legendraster"=> "true"},
    "results"=> wms_layers.size,
    "wmslayers"=> wms_layers
  }
end

Instance Method Details

#attribute(name) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'app/models/layer.rb', line 102

def attribute(name)
  if feature_class.nil?
    ::Attribute.new(self, name)
  else
    @attrs ||= feature_class.columns.inject({}) do |h, c|
      #logger.info "************************* feature_class column c #{c.inspect}"
      h[c.name] = ::Attribute.new(self, c.name)
      h
    end
    @attrs[name] ||= ::Attribute.new(self, name) #Add ad-hoc Attr. for calculated columns (e.g. custom SQL in query fields)
  end
  #logger.info "************************* Attribute for name '#{name}': #{@attrs[name].inspect}"
end

#feature_classObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'app/models/layer.rb', line 72

def feature_class
  fc = "Geo::#{feature_class_name}".constantize rescue nil #Geo.const_defined?(feature_class_name) seems not to work here
  fc ||= Geo.module_eval <<EOS
    class #{feature_class_name} < GeoModel
      self.table_name = '#{table}'
      self.primary_key = '#{pkey}'

      if self.primary_key == 'oid'
        # include oid in attributes
        default_scope select("*").select(self.primary_key)

        # return oid as id
        def id
          read_attribute(self.class.primary_key)
        end
      end

      self
    end
EOS
end

#feature_class_nameObject



94
95
96
# File 'app/models/layer.rb', line 94

def feature_class_name
  table.camelize.singularize
end

#full_nameObject



68
69
70
# File 'app/models/layer.rb', line 68

def full_name
  "#{topic_name}-#{name}".downcase
end

#geometry_columnObject



98
99
100
# File 'app/models/layer.rb', line 98

def geometry_column
  feature_class.try(:geometry_column)
end

#get_feature_info(searchgeo) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'app/models/layer.rb', line 183

def get_feature_info(searchgeo)
  logger.debug searchgeo.inspect
  x1, y1, x2, y2 = searchgeo.split(',').collect(&:to_f)
  #Since we get the query coordinates and not pixels, we have to assume a certain scale
  dist = (x1*0.01).abs
  params = [
    "FEATURE_COUNT=10",
    "INFO_FORMAT=application/vnd.ogc.gml", #text/xml
    "REQUEST=GetFeatureInfo",
    "SERVICE=WMS",
    "BBOX=#{x1},#{y1},#{x1+dist},#{y1+dist}",
    "WIDTH=100",
    "HEIGHT=100",
    "X=0", "I=0",
    "Y=99", "J=99"
  ]
  url = "#{table}&#{params.join('&')}"
  logger.debug "*** Cascaded GetFeatureInfo: #{url}"
  uri = URI.parse(url)
  http = Net::HTTP::new(uri.host, uri.port, CASCADED_PROXY_ADDR, CASCADED_PROXY_PORT, CASCADED_PROXY_USER, CASCADED_PROXY_PASS)
  response = http.request(Net::HTTP::Get.new(uri.request_uri))
  #logger.debug response.body
  info_features = parse_ogc_gml(response.body)
  features = info_features.collect {|f| f[:attributes] }
  logger.debug features.to_s
  logger.debug "Number of features: #{features.size}"
  features
end

#ident_fields_for(ability) ⇒ Object



121
122
123
124
125
126
127
128
129
# File 'app/models/layer.rb', line 121

def ident_fields_for(ability)
  #attributes.accessible_by(ability) & fields
  #logger.info "************************* fields layer #{name}: #{ident_fields}"
  #logger.info "************************* roles: #{ability.roles.collect(&:name).join(',')}"
  fields = (ident_fields || pkey).split(',')
  allowed_fields = fields.select { |f| ability.can?(:show, attribute(f)) }
  #logger.info "************************* ident_fields layer #{name}: #{allowed_fields.inspect}"
  allowed_fields
end

#infoObject



255
256
257
258
259
260
261
262
263
264
265
# File 'app/models/layer.rb', line 255

def info
  @info ||= begin
    if File.exist?(info_file)
      "layers/custom/#{topic_name.downcase}/#{info_fname[1..-10]}"
    elsif !File.exist?(info_file_empty) && File.exist?(info_file_auto)
      "layers/custom/#{topic_name.downcase}/auto/#{info_fname[1..-10]}"
    else
      nil
    end
  end
end

#info_fileObject



242
243
244
# File 'app/models/layer.rb', line 242

def info_file
  File.join(Rails.root, 'app', 'views', 'layers', 'custom', topic_name.downcase, info_fname)
end

#info_file_autoObject



246
247
248
# File 'app/models/layer.rb', line 246

def info_file_auto
  File.join(Rails.root, 'app', 'views', 'layers', 'custom', topic_name.downcase, 'auto', info_fname)
end

#info_file_emptyObject

ignore auto file if empty file exists



251
252
253
# File 'app/models/layer.rb', line 251

def info_file_empty
  File.join(Rails.root, 'app', 'views', 'layers', 'custom', topic_name.downcase, "_#{name}_info_leer.html.erb")
end

#info_fnameObject

Partial for identify result



238
239
240
# File 'app/models/layer.rb', line 238

def info_fname
  "_#{name}_info.html.erb"
end

#infotabObject



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'app/models/layer.rb', line 271

def infotab
  #  INFOLAYOUT=0^1^2^3^4^5^6^7  *** Wenn der Parameter = 1 ist, wird ein leerer String �bergeben.
  #                              *** Wenn der Parameter = 0 ist, wird der entsprechende Teil weggelassen wenn m�glich
  #
  #  LayoutString(0) = "Im Umkreis von <EM>xUmkreisx</EM> Meter(n) wurde <EM>xAnzahlx</EM> Datensatz gefunden.<br><br>"
  #  LayoutString(1) = "Im Umkreis von <EM>xUmkreisx</EM> Meter(n) wurden <EM>xAnzahlx</EM> Datens&aumltze gefunden.<br><br>"
  #  LayoutString(2) = "layer"
  #  LayoutString(3) = "infotext"
  #  LayoutString(4) = "infotab"
  #  LayoutString(5) = "tabtitle"
  #  LayoutString(6) = "tabcell"
  #  LayoutString(7) = "2"  ( If = "" Then 1 Tabellenzeile pro Record [z.B. "1" oder ""], else [z.B. "2"] 1 Zeile pro Feld)

  "infotable_horizontal"
end

#infotext(count) ⇒ Object



267
268
269
# File 'app/models/layer.rb', line 267

def infotext(count)
  count > 0 ? "resultcount_p" : "resultcount_s"
end

#legendObject



299
300
301
302
303
304
305
306
307
308
309
# File 'app/models/layer.rb', line 299

def legend
  @legend ||= begin
    if File.exist?(legend_file)
      "layers/custom/#{topic_name.downcase}/#{legend_fname[1..-10]}"
    elsif File.exist?(legend_file_auto)
      "layers/custom/#{topic_name.downcase}/auto/#{legend_fname[1..-10]}"
    else
      nil
    end
  end
end

#legend_fileObject



291
292
293
# File 'app/models/layer.rb', line 291

def legend_file
  File.join(Rails.root, 'app', 'views', 'layers', 'custom', topic_name.downcase, legend_fname)
end

#legend_file_autoObject



295
296
297
# File 'app/models/layer.rb', line 295

def legend_file_auto
  File.join(Rails.root, 'app', 'views', 'layers', 'custom', topic_name.downcase, 'auto', legend_fname)
end

#legend_fnameObject



287
288
289
# File 'app/models/layer.rb', line 287

def legend_fname
  "_#{name}_legend.html.erb"
end

#parse_ogc_gml(xml) ⇒ Object



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'app/models/layer.rb', line 212

def parse_ogc_gml(xml)
  info_features = []
  fields = ident_fields.split(',')
  doc = Hpricot::XML(xml)

  (doc/"//gml:featureMember").each do |fm|
    fm.children.each do |feature|
      info_feature = {}

      # attributes
      attributes = {}
      feature.containers.each do |c|
        if fields.include?(c.name)
          attributes[c.name] = c.inner_text
        end
      end
      info_feature[:attributes] = attributes

      info_features << info_feature
    end
  end

  info_features
end

#query(ability, query_topic, searchgeo, nearest = nil, user = nil, client_srid = nil) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'app/models/layer.rb', line 131

def query(ability, query_topic, searchgeo, nearest=nil, user=nil, client_srid=nil)
  # use layer setting by default
  nearest = search_nearest if nearest.nil?

  if table =~ /^https?:/
    features = get_feature_info(searchgeo)
    [self, features, searchgeo.split(',')]
  elsif feature_class
    begin
      #query_topic: {... customQueries: {<layername>: <query_method> }
      #e.g.
      #{"queryTopics":[{
      #   "level":"main","topic":"Lageklassen2011ZH","divCls":"legmain","layers":"seen,lageklassen-2011-flaechen,grenzen,gemeindegrenzen,bezirkslabels"
      #   customQueries: {'seen': 'tiefen_statistik'},
      #   customParams: {'tiefe': 25}
      #  }]}
      custom_query_method = query_topic['customQueries'][name] rescue nil
      logger.debug "******** feature_class: #{feature_class} ***************************************************"
      logger.debug "******** Layer: #{name} ***************************************************"
      logger.debug "******** custom_query_method: #{custom_query_method} ***************************************************"
      logger.debug "******** query_topic: #{query_topic} ***************************************************"
      features = if custom_query_method
        logger.debug "*** Custom query on layer #{name}: #{query_topic.inspect}"
        feature_class.send(custom_query_method, self, query_topic, searchgeo, client_srid)
      elsif feature_class.respond_to?(:identify_query)
        logger.debug "*** Custom identify_query on layer #{name}"
        feature_class.identify_query(self, query_topic, searchgeo, ability, user, client_srid)
      else
        logger.debug "*** Identify on layer #{name} with query fields #{query_fields(ability, client_srid)} at #{searchgeo.inspect}"
        feature_class.identify_filter(searchgeo, searchdistance, nearest, client_srid).where(where_filter).select(query_fields(ability, client_srid)).all
      end
      logger.debug "Number of features: #{features.size}"
      # calculate bbox of all features (in client_srid)
      unless features.empty?
        envelope = GeoRuby::SimpleFeatures::Geometry.from_hex_ewkb(features.first['extent']).envelope
        features.each do |feature|
          next if feature == features.first
          envelope.extend!(GeoRuby::SimpleFeatures::Geometry.from_hex_ewkb(feature['extent']).envelope)
        end
        bbox = [envelope.lower_corner.x, envelope.lower_corner.y, envelope.upper_corner.x, envelope.upper_corner.y]
      end
    rescue Exception => e
      features = "Table: <b>#{table}</b><br/>Exception: #{e}<br/>query fields: #{query_fields(ability, client_srid)}<br/>db fields: #{feature_class.column_names.join(',')}<br/>missing: <font color='red'>#{(query_fields(ability, client_srid).split(',') - feature_class.column_names).join(', ')}</font><br/><br/>"
      logger.info "Identify error on layer #{name} #{features}"
    end
    [self, features, bbox]
  else
    logger.warn "Table for layer #{name} not found. (Table name: '#{table}')"
    nil
  end
end

#query_fields(ability, client_srid) ⇒ Object



116
117
118
119
# File 'app/models/layer.rb', line 116

def query_fields(ability, client_srid)
  return '' if feature_class.nil?
  ([pkey]+ident_fields_for(ability)+[feature_class.extent_field(client_srid), feature_class.area_field(client_srid)]).join(',')
end

#quoted_wms_layersObject



311
312
313
# File 'app/models/layer.rb', line 311

def quoted_wms_layers
  wms_layers.split(',').collect {|l| %Q<"#{l}"> }.join(',')
end

#selection_symbolizerObject



356
357
358
359
360
361
362
363
364
# File 'app/models/layer.rb', line 356

def selection_symbolizer
  if selection_style.blank?
    gtyp = feature_class.geometry_type.sub(/^MULTI/, '').sub(/M$/, '') #MULTIPOINTM -> POINT 
    logger.error "Unsupported selection geometry type #{feature_class.geometry_type}" unless self.class.default_selection_styles.has_key?(gtyp)
    self.class.default_selection_styles[gtyp] || ''
  else
    selection_style
  end
end