Class: XData::FileReader

Inherits:
Object show all
Defined in:
lib/xdata/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.*)|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.



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/xdata/file_reader.rb', line 85

def initialize(pars)
  @params = pars
  
  if @params[:file_path] =~ /^http(s)?:\/\/.+/
    download
  else
    file_path = File.expand_path(@params[:file_path])
    if File.extname(file_path) == '.xdata'
      read_xdata(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 /\.xdata/i
          read_xdata(file_path)
        when /\.xml/i
          read_xml(file_path)
        else
          raise "Unknown or unsupported file type: #{ext}."
      end
    end
  end
  fillOut
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



32
33
34
# File 'lib/xdata/file_reader.rb', line 32

def content
  @content
end

#fileObject (readonly)

Returns the value of attribute file.



32
33
34
# File 'lib/xdata/file_reader.rb', line 32

def file
  @file
end

#paramsObject (readonly)

Returns the value of attribute params.



32
33
34
# File 'lib/xdata/file_reader.rb', line 32

def params
  @params
end

Instance Method Details

#downloadObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/xdata/file_reader.rb', line 55

def download()
  data = ''
  if @params[:file_path] =~ /\/ODataFeed\//
    open(odata_json(@params[:file_path])) do |f|
      data = XData::parse_json(f.read)
      read_json(nil,data)
    end
  else
    open(@params[:file_path]) do |f|
      data = f.read
    end
    if @params[:file_path] =~ /\.csv$/i 
      read_csv(nil,data)
    elsif @params[:file_path] =~ /\.zip$/i 
      read_zip(nil,data)
    elsif data =~ /^\s*<\?xml/
      read_xml(nil,data)
    else
      begin 
        data = XData::parse_json(data)
        read_json(nil,data)
      rescue XData::Exception
        return
      end
    end
  end
  fillOut
end

#fillOutObject



34
35
36
37
38
39
40
41
42
# File 'lib/xdata/file_reader.rb', line 34

def fillOut
  @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]
  findExtends         unless @params[:bounds]
end

#find_col_sep(f) ⇒ Object



197
198
199
200
201
202
203
204
# File 'lib/xdata/file_reader.rb', line 197

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



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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
352
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
# File 'lib/xdata/file_reader.rb', line 294

def find_geometry(xfield=nil, yfield=nil)
  delete_column = (@params[:keep_geom] != true)
  return if @content.blank?
  unless(xfield and yfield)
    @params[:hasgeometry] = nil
    xs = true
    ys = true

    @content[0][:properties].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[:geometry_type] = g_type
          @content.each do |h|
            a,b,g = is_wkb_geometry?(h[:properties][k])
            h[:geometry] = g
            h[:properties].delete(k) if delete_column
          end
          @params[:hasgeometry] = k
          return true
        end

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

        srid,g_type = is_geo_json?(v)
        if(srid)
          @params[:srid] = srid
          @params[:geometry_type] = g_type
          @content.each do |h|
            h[:geometry] = h[:properties][k]
            h[:properties].delete(k) if delete_column
          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]
    @content.each do |h|
      h[:properties][xfield] = h[:properties][xfield] || ''
      h[:properties][yfield] = h[:properties][yfield] || ''
      h[:geometry] = {:type => 'Point', :coordinates => [h[:properties][xfield].gsub(',','.').to_f, h[:properties][yfield].gsub(',','.').to_f]}
      h[:properties].delete(yfield) if delete_column
      h[:properties].delete(xfield) if delete_column
    end
    @params[:geometry_type] = 'Point'
    @params[:fields].delete(xfield) if @params[:fields] and delete_column
    @params[:fields].delete(yfield) if @params[:fields] and delete_column
    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][xfield])
      h[:properties].delete(xfield) if h[:geometry] and delete_column
    end
    @params[:geometry_type] = ''
    @params[:fields].delete(xfield) if @params[:fields] and delete_column
    return true
  end
  false
end

#find_unique_fieldObject



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

def find_unique_field
  fields = {}
  @params[:unique_id] = nil
  @content.each do |h|
    h[:properties].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

#findExtendsObject



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/xdata/file_reader.rb', line 270

def findExtends
  geometries = []
  if @params[:hasgeometry]
    @content.each do |o|
      o[:geometry][:type] = 'MultiPolygon' if o[:geometry][:type] == 'Multipolygon'
      geometries << Geometry.from_geojson(o[:geometry].to_json)
    end
    geom = GeometryCollection.from_geometries(geometries, (@params[:srid] || '4326'))
    @params[:bounds] = XData.toPolygon(geom.bounding_box())
  elsif @params[:postcode]
    pc = @params[:postcode].to_sym
    @content.each do |o|
      p2 = PC4.lookup(o[:properties][pc])
      if p2
        geometries << GeoRuby::SimpleFeatures::Point.from_coordinates(p2[0], (@params[:srid] || '4326'))
        geometries << GeoRuby::SimpleFeatures::Point.from_coordinates(p2[1], (@params[:srid] || '4326'))
      end
    end
    geom = GeometryCollection.from_geometries(geometries, (@params[:srid] || '4326'))
    @params[:bounds] = XData.toPolygon(geom.bounding_box())
  end
end

#geom_from_text(coords) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/xdata/file_reader.rb', line 251

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



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/xdata/file_reader.rb', line 117

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



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

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

#guess_nameObject



153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/xdata/file_reader.rb', line 153

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



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/xdata/file_reader.rb', line 177

def guess_srid
  return if @content.blank?
  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.between?(-7000.0,300000.0) and lat.between?(289000.0,629000.0)
      # Simple minded check for Dutch new rd system
      @params[:srid] = 28992
    end
  else

  end
end

#is_geo_json?(s) ⇒ Boolean

Returns:

  • (Boolean)


231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/xdata/file_reader.rb', line 231

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)


206
207
208
209
210
211
212
213
214
215
216
# File 'lib/xdata/file_reader.rb', line 206

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)


218
219
220
221
222
223
224
225
226
227
228
# File 'lib/xdata/file_reader.rb', line 218

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

#odata_json(url) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/xdata/file_reader.rb', line 44

def odata_json(url)
  if url =~ /\/ODataFeed\//
    uri = URI.parse(url)
    return url + '?$format=json' if uri.query.nil?
    pars = CGI.parse(uri.query)
    return url if pars["$format"]
    return url + '&$format=json'
  end
  return url
end

#parseODataFields(props) ⇒ Object



494
495
496
497
498
499
500
501
502
503
# File 'lib/xdata/file_reader.rb', line 494

def parseODataFields(props)
  rank=1
  @params[:md] = {} if @params[:md].nil?
  props.each do |p|
    @params[:md]["fieldUnit.#{rank}".to_sym] = p[:Unit]
    @params[:md]["fieldDescription.#{rank}".to_sym] = p[:Description]
    @params[:md]["fieldLabel.#{rank}".to_sym] = p[:Key]
    rank += 1
  end
end

#parseODataMeta(md) ⇒ Object



481
482
483
484
485
486
487
488
489
490
491
492
# File 'lib/xdata/file_reader.rb', line 481

def parseODataMeta(md)
  @params[:md] = {} if @params[:md].nil?
  @params[:md][:title] = md[:Title]
  @params[:md][:identifier] = md[:Identifier]
  @params[:md][:description] = md[:Description]
  @params[:md][:abstract] = md[:ShortDescription]
  @params[:md][:modified] = md[:Modified]
  @params[:md][:temporal] = md[:Period]
  @params[:md][:publisher] = md[:Source]
  @params[:md][:accrualPeriodicity] = md[:Frequency]
  @params[:md][:language] = md[:Language]
end

#proces_zipped_dir(d) ⇒ Object



615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/xdata/file_reader.rb', line 615

def proces_zipped_dir(d)
  Dir.foreach(d) do |f|

    next if f =~ /^\./
    
    if File.directory?(d + '/' + f)
      return true if proces_zipped_dir(d + '/' + f)
    end

    case File.extname(f)
      when /\.(geo)?json/i
        read_json(d+'/'+f)
        return true
      when /\.shp/i
        read_shapefile(d+'/'+f)
        return true
      when /\.csv|tsv/i
        read_csv(d+'/'+f)
        return true
    end
  end
  return false
end

#read_csv(path, c = nil) ⇒ Object



385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/xdata/file_reader.rb', line 385

def read_csv(path, c = nil)
  if path 
    File.open(path, "r:bom|utf-8") do |fd|
      c = fd.read
    end
  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[:format] = 'CSV'
  @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: h }
      index += 1
    end
  rescue => e
    raise XData::Exception.new("Read CSV; line #{index}; #{e.message}")
  end
  find_geometry
end

#read_json(path, hash = nil) ⇒ Object



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
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
466
467
# File 'lib/xdata/file_reader.rb', line 421

def read_json(path, hash=nil)
  
  STDERR.puts hash.class if hash
  
  @content = []
  if path
    data = ''
    File.open(path, "r:bom|utf-8") do |fd|
      data = fd.read
    end
    hash = XData::parse_json(data)
  end
  
  if hash.is_a?(Hash) and hash[:'odata.metadata']
    read_odata(hash)
  elsif hash.is_a?(Hash) and hash[:type] and (hash[:type] == 'FeatureCollection')
    # GeoJSON
    hash[:features].each do |f|
      f.delete(:type)
      @content << f
    end
    @params[:hasgeometry] = @params[:format] = 'GeoJSON'

  else
    # Free-form JSON
    @params[:format] = '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 => h }
      end
    end
    find_geometry
  end
end

#read_odata(h) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/xdata/file_reader.rb', line 505

def read_odata(h)
  @content = []
  @params[:format] = "OData"
  @params[:odata] = {}
  links = h[:value]
  links.each do |l|
    @params[:odata][l[:name].to_sym] = l[:url]
  end
  
  begin
    open(odata_json(@params[:odata][:TableInfos])) do |f|
      md = XData::parse_json(f.read)[:value]
      parseODataMeta(md[0])
    end

    open(odata_json(@params[:odata][:DataProperties])) do |f|
      props = XData::parse_json(f.read)[:value]
      parseODataFields(props)
    end

    open(odata_json(@params[:odata][:TypedDataSet])) do |f|
      c = XData::parse_json(f.read)[:value]
      c.each do |h|
        @content << { :properties => h }
      end
    end

  rescue OpenURI::HTTPError => e
    STDERR.puts e.message
  end

  find_geometry
end

#read_shapefile(path) ⇒ Object



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
# File 'lib/xdata/file_reader.rb', line 540

def read_shapefile(path)

  @content = []

  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'
  @params[:format] = "Shape File"

  GeoRuby::Shp4r::ShpFile.open(path) do |shp|
    shp.each do |shape|
      h = {}
      h[:geometry] = XData::parse_json(shape.geometry.to_json) #a GeoRuby SimpleFeature
      h[:properties] = {}
      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][field.name.to_sym] = s
      end
      @content << h
    end
  end
end

#read_xdata(path) ⇒ Object



608
609
610
611
612
# File 'lib/xdata/file_reader.rb', line 608

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

#read_xml(path, data = nil) ⇒ Object



567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/xdata/file_reader.rb', line 567

def read_xml(path, data=nil)
  if path
    File.open(path, "r:bom|utf-8") do |fd|
      data = fd.read
    end
  end
  begin 
    feed = Feedjira::Feed.parse(data)
    if feed 
      @params[:format] = "Atom Feed"
      maxlat = -1000
      maxlon = -1000
      minlat = 1000
      minlon = 1000
      doc = Nokogiri::XML data
      a = doc.xpath("//georss:polygon")
      if a.length > 0
        # geometries << GeoRuby::SimpleFeatures::Point..from_latlong(lat, lon)
        a.each do |x|
          # 50.6 3.1 50.6 7.3 53.7 7.3 53.7 3.1 50.6 3.1
          s = x.text.split(/\s+/)
          s.each_slice(2) { |c| 
            maxlat = [maxlat,c[0].to_f].max
            maxlon = [maxlon,c[1].to_f].max
            minlat = [minlat,c[0].to_f].min
            minlon = [minlon,c[1].to_f].min
          }
        end
        @params[:bounds] = { type: 'Polygon', coordinates: [[minlon,minlat], [minlon,maxlat], [maxlon,maxlat], [maxlon,minlat], [minlon,minlat]] }
      end
    end
    # url = feed.entries[0].url
    # Dir.mktmpdir("xdfi_#{File.basename(path).gsub(/\A/,'')}") do |dir|
    #   f = dir + '/' + File.basename(path)
    # end
  rescue Exception => e
    puts e.inspect
    return -1
  end
end

#read_zip(path, data = nil) ⇒ Object

Raises:



639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# File 'lib/xdata/file_reader.rb', line 639

def read_zip(path, data=nil)
  tempfile = nil
  begin
    
    if(data)
      tempfile = Tempfile.new('xdatazip')
      tempfile.write(data)
      path = tempfile.path  
    end

    Dir.mktmpdir("xdfi_#{File.basename(path).gsub(/\A/,'')}") do |dir|
      command = "unzip '#{path}' -d '#{dir}' > /dev/null 2>&1"
      raise XData::Exception.new("Error unzipping #{path}.", {:originalfile => path}, __FILE__, __LINE__) if not system command
      if File.directory?(dir + '/' + File.basename(path).chomp(File.extname(path)))
        dir = dir + '/' + File.basename(path).chomp(File.extname(path) )
      end
      return if proces_zipped_dir(dir)
    end
  rescue Exception => e
    raise XData::Exception.new(e.message, {:originalfile => path}, __FILE__, __LINE__)
  ensure
    tempfile.unlink if tempfile
  end
  raise XData::Exception.new("Could not process file #{path}", {:originalfile => path}, __FILE__, __LINE__)
end

#srid_from_prj(str) ⇒ Object



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

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 = XData::parse_json resp.body
      @params[:srid] = resp[:codes][0][:code].to_i
    end
  rescue
  end
end

#write(path = nil) ⇒ Object



665
666
667
668
669
670
671
672
673
674
675
676
# File 'lib/xdata/file_reader.rb', line 665

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