-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.rb
84 lines (77 loc) · 2.28 KB
/
index.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
51
52
53
54
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
83
84
require 'bundler/setup'
require 'sinatra'
require 'sinatra/partial'
require 'pry'
require 'haml'
require 'net/http'
require 'sequel'
require 'sequel/plugins/serialization'
require 'nokogiri'
require './core_ext/object'
module NDCValidator
class IvalidNDCMessageError < RuntimeError; end
class EmptyMessageError < RuntimeError; end
class NDCParseUndefinedError < RuntimeError; end
end
SCHEMAS_DIR = "./schemas/"
SCHEMAS_VERSIONS = {
'v1-1-3' => "Version 1.1.3 (Nov 2014)",
'v15-2' => "Version 15.2 (Oct 2015)",
'v16-1' => "Version 16.1 (Feb 2016)",
'v16-2' => "Version 16.2 (Sep 2016)",
'v17-1' => "Version 17.1 (Mar 2017)",
'v17-2' => "Version 17.2 (Apr 2017)"
}
configure do
enable :partial_underscores
DB = Sequel.connect( ENV["DATABASE_URL"] || "sqlite://development.db" )
require "./models"
end
get '/' do
haml :index, :format => :html5
end
post '/validate' do
errors = []
if params[:xml_body].present? || !params[:version].present?
message = params[:xml_body]
doc = Nokogiri::XML(message)
if doc.root
ndc_method = doc.root.name
#TODO validate with methods list
if !ndc_method.empty?
@message = Message.new(xml: message, ndc_method: ndc_method)
schemas_path = SCHEMAS_DIR + params[:version]
Dir.chdir(schemas_path) do
begin
schema_file = "#{ndc_method}.xsd"
xsd = Nokogiri::XML::Schema(File.read(schema_file))
errors += xsd.validate(doc)
rescue
errors << NDCValidator::IvalidNDCMessageError.new("Invalid/unknown NDC message")
end
end
else
errors << NDCValidator::EmptyMessageError.new("Can't parse an empty message")
end
else
errors << NDCValidator::NDCParseUndefinedError.new("Unsuccessful message parsing")
end
@message.ndc_errors = errors
if @message.save && @message.valid?
redirect "/message/#{@message.hash_id}"
else
redirect "/"
end
else
haml :"400", layout: false, status: 400
end
end
get '/message/:hash_id' do
@message = Message[hash_id: params[:hash_id]]
if @message.present? && @message.valid?
@url = "http://#{request.env["HTTP_HOST"]}/message/#{@message.hash_id}"
haml :index, :format => :html5
else
haml :"404", layout: false, status: 404
end
end