Class: CitySDK::FileReader

Inherits:
Object show all
Defined in:
lib/citysdk/file_reader.rb

Constant Summary collapse

RE_Y =
/lat|(y.*coord)|(y.*pos.*)|(y.*loc(atie|ation)?)/i
RE_X =
/lon|lng|(x.*coord)|(x.*pos.*)|(x.*loc(atie|ation)?)/i
RE_GEO =
/^(geom(etry)?|location|locatie|coords|coordinates)$/i
RE_NAME =
/(title|titel|naam|name)/i
RE_A_NAME =
/^(naam|name|title|titel)$/i
GEOMETRIES =
["point", "multipoint", "linestring", "multilinestring", "polygon", "multipolygon"]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pars) ⇒ FileReader

Returns a new instance of FileReader.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/citysdk/file_reader.rb', line 20

def initialize(pars)
  @params = pars
  file_path = File.expand_path(@params[:file_path])
  if File.extname(file_path) == '.csdk'
    read_csdk(file_path)
  else
    ext = @params[:originalfile] ? File.extname(@params[:originalfile]) : File.extname(file_path)
    case ext
      when /\.zip/i
        read_zip(file_path)
      when /\.(geo)?json/i
        read_json(file_path)
      when /\.shp/i
        read_shapefile(file_path)
      when /\.csv|tsv/i
        read_csv(file_path)
      when /\.csdk/i
        read_csdk(file_path)
      else
        raise "Unknown or unsupported file type: #{ext}."
    end
  end

  @params[:rowcount] = @content.length
  get_fields unless @params[:fields]
  guess_name unless @params[:name]
  guess_srid unless @params[:srid]
  find_unique_field  unless @params[:unique_id]
  get_address unless @params[:hasaddress]
  set_id_name
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



18
19
20
# File 'lib/citysdk/file_reader.rb', line 18

def content
  @content
end

#fileObject (readonly)

Returns the value of attribute file.



18
19
20
# File 'lib/citysdk/file_reader.rb', line 18

def file
  @file
end

#paramsObject (readonly)

Returns the value of attribute params.



18
19
20
# File 'lib/citysdk/file_reader.rb', line 18

def params
  @params
end

Instance Method Details

#find_col_sep(f) ⇒ Object



156
157
158
159
160
161
162
163
# File 'lib/citysdk/file_reader.rb', line 156

def find_col_sep(f)
  a = f.gets
  b = f.gets
  [";","\t","|"].each do |s|
    return s if (a.split(s).length == b.split(s).length) and b.split(s).length > 1
  end
  ','
end

#find_geometry(xfield = nil, yfield = nil) ⇒ Object



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/citysdk/file_reader.rb', line 229

def find_geometry(xfield=nil, yfield=nil)
  unless(xfield and yfield)
    @params[:hasgeometry] = nil
    xs = true
    ys = true

    @content[0][:properties][:data].each do |k,v|
      next if k.nil?

      if k.to_s =~ RE_GEO

        srid,g_type = is_wkb_geometry?(v)
        if(srid)
          @params[:srid] = srid
          @params[:geomtry_type] = g_type
          @content.each do |h|
            a,b,g = is_wkb_geometry?(h[:properties][:data][k])
            h[:geometry] = g
            h[:properties][:data].delete(k)
          end
          @params[:hasgeometry] = k
          return true
        end


        srid,g_type = is_wkt_geometry?(v)
        if(srid)
          @params[:srid] = srid
          @params[:geomtry_type] = g_type
          @content.each do |h|
            a,b,g = is_wkt_geometry?(h[:properties][:data][k])
            h[:geometry] = g
            h[:properties][:data].delete(k)
          end
          @params[:hasgeometry] = k
          return true
        end

        srid,g_type = is_geo_json?(v)
        if(srid)
          @params[:srid] = srid
          @params[:geomtry_type] = g_type
          @content.each do |h|
            h[:geometry] = h[:properties][:data][k]
            h[:properties].delete(k)
          end
          @params[:hasgeometry] = k
          return true
        end

      end

      hdc = k.to_s.downcase
      if hdc == 'longitude' or hdc == 'lon' or hdc == 'x'
        xfield=k; xs=false
      end
      if hdc == 'latitude' or hdc == 'lat' or hdc == 'y'
        yfield=k; ys=false
      end
      xfield = k if xs and (hdc =~ RE_X)
      yfield = k if ys and (hdc =~ RE_Y)
    end
  end

  if xfield and yfield and (xfield != yfield)
    @params[:hasgeometry] = [xfield,yfield].to_s
    @content.each do |h|
      h[:geometry] = {:type => 'Point', :coordinates => [h[:properties][:data][xfield].gsub(',','.').to_f, h[:properties][:data][yfield].gsub(',','.').to_f]}
      h[:properties][:data].delete(yfield)
      h[:properties][:data].delete(xfield)
    end
    @params[:geomtry_type] = 'Point'
    @params[:fields].delete(xfield) if @params[:fields]
    @params[:fields].delete(yfield) if @params[:fields]
    return true
  elsif (xfield and yfield)
    # factory = ::RGeo::Cartesian.preferred_factory()
    @params[:hasgeometry] = "[#{xfield}]"
    @content.each do |h|
      h[:geometry] = geom_from_text(h[:properties][:data][xfield])
      h[:properties][:data].delete(xfield) if h[:geometry]
    end
    @params[:geomtry_type] = ''
    @params[:fields].delete(xfield) if @params[:fields]
    return true
  end

  false
end

#find_unique_fieldObject



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/citysdk/file_reader.rb', line 90

def find_unique_field
  fields = {}
  @params[:unique_id] = nil
  @content.each do |h|
    h[:properties][:data].each do |k,v|
      fields[k] = Hash.new(0) if fields[k].nil?
      fields[k][v] += 1
    end
  end

  fields.each_key do |k|
    if fields[k].length == @params[:rowcount]
      @params[:unique_id] = k
      break
    end
  end

end

#geom_from_text(coords) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/citysdk/file_reader.rb', line 210

def geom_from_text(coords)
  # begin
  #   a = factory.parse_wkt(coords)
  # rescue
  # end

  if coords =~ /^(\w+)(.+)/
    if GEOMETRIES.include?($1.downcase)
      type = $1.capitalize
      coor = $2.gsub('(','[').gsub(')',']')
      coor = coor.gsub(/([-+]?[0-9]*\.?[0-9]+)\s+([-+]?[0-9]*\.?[0-9]+)/) { "[#{$1},#{$2}]" }
      coor = JSON.parse(coor)
      return { :type => type,
        :coordinates => coor }
    end
  end
  {}
end

#get_addressObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/citysdk/file_reader.rb', line 52

def get_address
  pd = pc = hn = ad = false
  @params[:housenumber] = nil
  @params[:hasaddress] = 'unknown'
  @params[:postcode] = nil
  @params[:fields].reverse.each do |f|
    pc = f if ( f.to_s =~ /^(post|zip|postal)code$/i )
    hn = f if ( f.to_s =~ /huisnummer|housenumber|(house|huis)(nr|no)|number/i)
    ad = f if ( f.to_s =~ /address|street|straat|adres/i)
  end
  if pc and (ad or hn)
    @params[:hasaddress] = 'certain'
  end
  @params[:postcode] = pc
  @params[:housenumber] = hn ? hn : ad

end

#get_fieldsObject



122
123
124
125
126
127
128
129
130
131
132
# File 'lib/citysdk/file_reader.rb', line 122

def get_fields
  @params[:fields] = []
  @params[:original_fields] = []
  @params[:alternate_fields] = {}
  @content[0][:properties][:data].each_key do |k|
    k = (k.to_sym rescue k) || k
    @params[:fields] << k
    @params[:original_fields] << k
    @params[:alternate_fields][k] = k
  end
end

#guess_nameObject



109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/citysdk/file_reader.rb', line 109

def guess_name
  @params[:name] = nil
  @params[:fields].reverse.each do |k|
    if(k.to_s =~ RE_A_NAME)
      @params[:name] = k
      return
    end
    if(k.to_s =~ RE_NAME)
      @params[:name] = k
    end
  end
end

#guess_sridObject



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/citysdk/file_reader.rb', line 134

def guess_srid
  return unless @content[0][:geometry] and @content[0][:geometry].class == Hash
  @params[:srid] = 4326
  g = @content[0][:geometry][:coordinates]
  if(g)
    while g[0].is_a?(Array)
      g = g[0]
    end
    lon = g[0]
    lat = g[1]
    # if lon > -180.0 and lon < 180.0 and lat > -90.0 and lat < 90.0
    #   @params[:srid] = 4326
    # else
    if lon.between?(-7000.0,300000.0) and lat.between?(289000.0,629000.0)
      # Dutch new rd system
      @params[:srid] = 28992
    end
  else

  end
end

#is_geo_json?(s) ⇒ Boolean

Returns:

  • (Boolean)


190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/citysdk/file_reader.rb', line 190

def is_geo_json?(s)
  return nil if s.class != Hash
  begin
    if GEOMETRIES.include?(s[:type].downcase)
      srid = 4326
      if s[:crs] and s[:crs][:properties]
        if s[:crs][:type] == 'OGC'
          urn = s[:crs][:properties][:urn].split(':')
          srid = urn.last.to_i if (urn[4] == 'EPSG')
        elsif s[:crs][:type] == 'EPSG'
          srid = s[:crs][:properties][:code]
        end
      end
      return srid,s[:type],s
    end
  rescue Exception=>e
  end
  nil
end

#is_wkb_geometry?(s) ⇒ Boolean

Returns:

  • (Boolean)


165
166
167
168
169
170
171
172
173
174
175
# File 'lib/citysdk/file_reader.rb', line 165

def is_wkb_geometry?(s)
  begin
    f = GeoRuby::SimpleFeatures::GeometryFactory::new
    p = GeoRuby::SimpleFeatures::HexEWKBParser.new(f)
    p.parse(s)
    g = f.geometry
    return g.srid,g.as_json[:type],g
  rescue => e
  end
  nil
end

#is_wkt_geometry?(s) ⇒ Boolean

Returns:

  • (Boolean)


177
178
179
180
181
182
183
184
185
186
187
# File 'lib/citysdk/file_reader.rb', line 177

def is_wkt_geometry?(s)
  begin
    f = GeoRuby::SimpleFeatures::GeometryFactory::new
    p = GeoRuby::SimpleFeatures::EWKTParser.new(f)
    p.parse(s)
    g = f.geometry
    return g.srid,g.as_json[:type],g
  rescue => e
  end
  nil
end

#read_csdk(path) ⇒ Object



433
434
435
436
437
# File 'lib/citysdk/file_reader.rb', line 433

def read_csdk(path)
  h = Marshal.load(File.read(path))
  @params = h[:config]
  @content = h[:content]
end

#read_csv(path) ⇒ Object



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/citysdk/file_reader.rb', line 319

def read_csv(path)
  @file = path
  c=''
  File.open(path, "r:bom|utf-8") do |fd|
    c = fd.read
  end
  unless @params[:utf8_fixed]
    detect = CharlockHolmes::EncodingDetector.detect(c)
    c =	CharlockHolmes::Converter.convert(c, detect[:encoding], 'UTF-8') if detect
  end
  c = c.force_encoding('utf-8')
  c = c.gsub(/\r\n?/, "\n")
  @content = []
  @params[:colsep] = find_col_sep(StringIO.new(c)) unless @params[:colsep]
  csv = CSV.new(c, :col_sep => @params[:colsep], :headers => true, :skip_blanks =>true)
  csv.header_convert { |h| h.blank? ? '_' : h.strip.gsub(/\s+/,'_')  }
  csv.convert { |h| h ? h.strip : '' }
  index = 0
  begin
    csv.each do |row|
      r = row.to_hash
      h = {}
      r.each do |k,v|
        h[(k.to_sym rescue k) || k] = v
      end
      @content << {properties: {data: h} }
      index += 1
    end
  rescue => e
    raise CitySDK::Exception.new("Read CSV; line #{index}; #{e.message}")
  end
  find_geometry
end

#read_json(path) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/citysdk/file_reader.rb', line 353

def read_json(path)
  @content = []
  @file = path
  raw = ''
  File.open(path, "r:bom|utf-8") do |fd|
    raw = fd.read
  end
  hash = CitySDK::parse_json(raw)

  if hash.is_a?(Hash) and hash[:type] and (hash[:type] == 'FeatureCollection')
    # GeoJSON
    hash[:features].each do |f|
      f.delete(:type)
      f[:properties] = {data: f[:properties]}
      @content << f
    end
    @params[:hasgeometry] = 'GeoJSON'
  else
    # Free-form JSON
    val,length = nil,0
    if hash.is_a?(Array)
       # one big array
       val,length = hash,hash.length
    else
      hash.each do |k,v|
        if v.is_a?(Array)
          # the longest array value in the Object
          val,length = v,v.length if v.length > length
        end
      end
    end

    if val
      val.each do |h|
        @content << { :properties => {:data => h} }
      end
    end
    find_geometry
  end
end

#read_shapefile(path) ⇒ Object



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/citysdk/file_reader.rb', line 406

def read_shapefile(path)

  @content = []
  @file = path

  prj = path.gsub(/.shp$/i,"") + '.prj'
  prj = File.exists?(prj) ? File.read(prj) : nil
  srid_from_prj(prj) if (prj and @params[:srid].nil?)

  @params[:hasgeometry] = 'ESRI Shape'

  GeoRuby::Shp4r::ShpFile.open(path) do |shp|
    shp.each do |shape|
      h = {}
      h[:geometry] = CitySDK::parse_json(shape.geometry.to_json) #a GeoRuby SimpleFeature
      h[:properties] = {:data => {}}
      att_data = shape.data #a Hash
      shp.fields.each do |field|
        s = att_data[field.name]
        s = s.force_encoding('ISO8859-1') if s.class == String
        h[:properties][:data][field.name.to_sym] = s
      end
      @content << h
    end
  end
end

#read_zip(path) ⇒ Object

Raises:



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/citysdk/file_reader.rb', line 439

def read_zip(path)
  begin
    Dir.mktmpdir("cdkfi_#{File.basename(path).gsub(/\A/,'')}") do |dir|
      raise CitySDK::Exception.new("Error unzipping #{path}.", {:originalfile => path}, __FILE__, __LINE__) if not system "unzip '#{path}' -d '#{dir}' > /dev/null 2>&1"
      if File.directory?(dir + '/' + File.basename(path).chomp(File.extname(path)))
        dir = dir + '/' + File.basename(path).chomp(File.extname(path) )
      end
      Dir.foreach(dir) do |f|
        next if f =~ /^\./
        case File.extname(f)
          when /\.(geo)?json/i
            read_json(dir+'/'+f)
            return
          when /\.shp/i
            read_shapefile(dir+'/'+f)
            return
          when /\.csv|tsv/i
            read_csv(dir+'/'+f)
            return
        end
      end
    end
  rescue Exception => e
    raise CitySDK::Exception.new(e.message, {:originalfile => path}, __FILE__, __LINE__)
  end
  raise CitySDK::Exception.new("Could not proecess file #{path}", {:originalfile => path}, __FILE__, __LINE__)
end

#set_id_nameObject



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/citysdk/file_reader.rb', line 70

def set_id_name
  count = 123456
  if @params[:unique_id]
    @content.each do |h|
      h[:properties][:id] = h[:properties][:data][@params[:unique_id]]
      h[:properties][:title] = h[:properties][:data][@params[:name]] if @params[:name]
    end
  else
    @params[:unique_id] = :csdk_gen
    # @params[:fields] << :csdk_gen
    # @params[:original_fields] << :csdk_gen
    # @params[:alternate_fields][:csdk_gen] = :csdk_gen
    @content.each do |h|
      h[:properties][:id] = "cg_#{count}"
      h[:properties][:title] = h[:properties][:data][@params[:name]] if @params[:name]
      count += 1
    end
  end
end

#srid_from_prj(str) ⇒ Object



394
395
396
397
398
399
400
401
402
403
404
# File 'lib/citysdk/file_reader.rb', line 394

def srid_from_prj(str)
  begin
    connection = Faraday.new :url => "http://prj2epsg.org"
    resp = connection.get('/search.json', {:mode => 'wkt', :terms => str})
    if resp.status.between?(200, 299)
      resp = CitySDK::parse_json resp.body
      @params[:srid] = resp[:codes][0][:code].to_i
    end
  rescue
  end
end

#write(path = nil) ⇒ Object



467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/citysdk/file_reader.rb', line 467

def write(path=nil)
  path = @file_path if path.nil?
  path = path + '.csdk'
  begin
    File.open(path,"w") do |fd|
      fd.write( Marshal.dump({:config=>@params, :content=>@content}) )
    end
  rescue
    return nil
  end
  return path
end