Class: Layer

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

Defined Under Namespace

Modules: Geo

Constant Summary collapse

DEFAULT_SELECTION_STYLE =
{
  '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

.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

.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



92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'app/models/layer.rb', line 92

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
# 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}'

      self
    end
EOS
end

#feature_class_nameObject



84
85
86
# File 'app/models/layer.rb', line 84

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



88
89
90
# File 'app/models/layer.rb', line 88

def geometry_column
  feature_class.try(:geometry_column)
end

#get_feature_info(searchgeo) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'app/models/layer.rb', line 171

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, nil, 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



115
116
117
118
119
120
121
122
123
# File 'app/models/layer.rb', line 115

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



243
244
245
246
247
248
249
250
251
252
253
# File 'app/models/layer.rb', line 243

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



230
231
232
# File 'app/models/layer.rb', line 230

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

#info_file_autoObject



234
235
236
# File 'app/models/layer.rb', line 234

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



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

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



226
227
228
# File 'app/models/layer.rb', line 226

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

#infotabObject



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'app/models/layer.rb', line 259

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



255
256
257
# File 'app/models/layer.rb', line 255

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

#legendObject



287
288
289
290
291
292
293
294
295
296
297
# File 'app/models/layer.rb', line 287

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



279
280
281
# File 'app/models/layer.rb', line 279

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

#legend_file_autoObject



283
284
285
# File 'app/models/layer.rb', line 283

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

#legend_fnameObject



275
276
277
# File 'app/models/layer.rb', line 275

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

#parse_ogc_gml(xml) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'app/models/layer.rb', line 200

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) ⇒ Object



125
126
127
128
129
130
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
# File 'app/models/layer.rb', line 125

def query(ability, query_topic, searchgeo)
  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} ***************************************************"
      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) 
      elsif feature_class.respond_to?(:identify_query)
        logger.debug "*** Custom identify_query on layer #{name}"
        feature_class.identify_query(searchgeo, searchdistance)
      else
        logger.debug "*** Identify on layer #{name} with query fields #{query_fields(ability)} at #{searchgeo.inspect}"
        feature_class.identify_filter(searchgeo, searchdistance).select(query_fields(ability)).all
      end
      logger.debug "Number of features: #{features.size}"
      # calculate bbox of all features
      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)}<br/>db fields: #{feature_class.column_names.join(',')}<br/>missing: <font color='red'>#{(query_fields(ability).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) ⇒ Object

def filtered(ability)

feature_class.where(ability.resource_access_filter(self))

end



110
111
112
113
# File 'app/models/layer.rb', line 110

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

#quoted_wms_layersObject



299
300
301
# File 'app/models/layer.rb', line 299

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

#selection_symbolizerObject



336
337
338
339
340
341
342
343
344
# File 'app/models/layer.rb', line 336

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 DEFAULT_SELECTION_STYLE.has_key?(gtyp)
    DEFAULT_SELECTION_STYLE[gtyp] || ''
  else
    selection_style
  end
end