Skip to content

Instantly share code, notes, and snippets.

@kzk
Created April 13, 2011 09:27
Show Gist options
  • Save kzk/917259 to your computer and use it in GitHub Desktop.
Save kzk/917259 to your computer and use it in GitHub Desktop.
module Sedue
$SEDUE_SCHEMA = "../sedue/schema.xml"
$SEDUE_KEY_FIELD = "article_id"
$SEDUE_HOST = "sedue"
$SEDUE_PORT = 11118
$SEDUE_TIMEOUT = 60
class SedueClient
public
def self.get
SedueClient.new($SEDUE_SCHEMA, $SEDUE_KEY_FIELD,
$SEDUE_HOST, $SEDUE_PORT,
$SEDUE_TIMEOUT)
end
def register(h)
xml = []
xml << "<add><doc>\n"
@fields.each { |field|
val = h[field]
val = "" if val.nil?
val = val.to_s.strip
docxml =<<END
<field name="#{field}"><![CDATA[#{val}]]></field>
END
xml << docxml
}
xml << "</doc></add>"
xml = xml.join
puts xml
post(h[@key_field], xml)
end
def del(id)
xml = "<delete><id>#{id}</id></delete>"
post(id, xml)
end
private
def initialize(schema, key_field, host, port, timeout = 3)
@fields = []
doc = REXML::Document.new(open(schema))
doc.elements.each("/schema/fields/field"){ |element|
raise "invalid schema" if element.attributes["name"].nil?
@fields << element.attributes["name"]
}
@key_field = key_field
raise if @key_field.nil? || @key_field.empty?
@host = host
@port = port
@timeout = timeout
end
def post(id, buf)
url = "http://#{@host}:#{@port}/update?key_field=#{@key_field}"
content_type = "text/xml; charset=utf-8"
begin
connection.request_post(url, buf, {"Content-type" => content_type }) { |res|
next if res.code.to_i == 200
puts "Register fail: key_field=#{id}"
puts res.body
}
rescue => ex
p ex
p ex.class
rescue Timeout::Error => ex
p ex
p ex.class
end
end
def connection
@connection ||= begin
c = Net::HTTP.new(@host, @port)
raise "Failed to connect to #{@host}:#{@port}" if c.nil?
c.read_timeout = @timeout
c
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment