repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/portType.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/portType.rb
# WSDL4R - WSDL portType definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL class PortType < Info attr_reader :name # required attr_reader :operations def targetnamespace parent.targetnamespace end def initialize super @name = nil @operations = XSD::NamedElements.new end def find_binding root.bindings.find { |item| item.type == @name } or raise RuntimeError.new("#{@name} not found") end def locations bind_name = find_binding.name result = [] root.services.each do |service| service.ports.each do |port| if port.binding == bind_name result << port.soap_address.location if port.soap_address end end end result end def parse_element(element) case element when OperationName o = Operation.new @operations << o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) else nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/types.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/types.rb
# WSDL4R - WSDL types definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL class Types < Info attr_reader :schemas def initialize super @schemas = [] end def parse_element(element) case element when SchemaName o = XMLSchema::Schema.new @schemas << o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) nil end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/service.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/service.rb
# WSDL4R - WSDL service definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL class Service < Info attr_reader :name # required attr_reader :ports attr_reader :soap_address def initialize super @name = nil @ports = XSD::NamedElements.new @soap_address = nil end def targetnamespace parent.targetnamespace end def parse_element(element) case element when PortName o = Port.new @ports << o o when SOAPAddressName o = WSDL::SOAP::Address.new @soap_address = o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) else nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/import.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/import.rb
# WSDL4R - WSDL import definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/importer' module WSDL class Import < Info attr_reader :namespace attr_reader :location attr_reader :content def initialize super @namespace = nil @location = nil @content = nil @web_client = nil end def parse_element(element) case element when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NamespaceAttrName @namespace = value.source if @content @content.targetnamespace = @namespace end @namespace when LocationAttrName @location = URI.parse(value.source) if @location.relative? and !parent.location.nil? and !parent.location.relative? @location = parent.location + @location end if root.importedschema.key?(@location) @content = root.importedschema[@location] else root.importedschema[@location] = nil # placeholder @content = import(@location) if @content.is_a?(Definitions) @content.root = root if @namespace @content.targetnamespace = @namespace end end root.importedschema[@location] = @content end @location else nil end end private def import(location) Importer.import(location, root) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/operation.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/operation.rb
# WSDL4R - WSDL operation definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL class Operation < Info class NameInfo attr_reader :op_name attr_reader :optype_name attr_reader :parts def initialize(op_name, optype_name, parts) @op_name = op_name @optype_name = optype_name @parts = parts end end attr_reader :name # required attr_reader :parameter_order # optional attr_reader :input attr_reader :output attr_reader :fault attr_reader :type # required def initialize super @name = nil @type = nil @parameter_order = nil @input = nil @output = nil @fault = [] end def targetnamespace parent.targetnamespace end def input_info typename = input.find_message.name NameInfo.new(@name, typename, inputparts) end def output_info typename = output.find_message.name NameInfo.new(@name, typename, outputparts) end def inputparts sort_parts(input.find_message.parts) end def inputname XSD::QName.new(targetnamespace, input.name ? input.name.name : @name.name) end def outputparts sort_parts(output.find_message.parts) end def outputname XSD::QName.new(targetnamespace, output.name ? output.name.name : @name.name + 'Response') end def parse_element(element) case element when InputName o = Param.new @input = o o when OutputName o = Param.new @output = o o when FaultName o = Param.new @fault << o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) when TypeAttrName @type = value when ParameterOrderAttrName @parameter_order = value.source.split(/\s+/) else nil end end private def sort_parts(parts) return parts.dup unless parameter_order result = [] parameter_order.each do |orderitem| if (ele = parts.find { |part| part.name == orderitem }) result << ele end end if result.length == 0 return parts.dup end # result length can be shorter than parts's. # return part must not be a part of the parameterOrder. result end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/importer.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/importer.rb
# WSDL4R - WSDL importer library. # Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/xmlSchema/importer' require 'wsdl/parser' module WSDL class Importer < WSDL::XMLSchema::Importer def self.import(location, originalroot = nil) new.import(location, originalroot) end private def parse(content, location, originalroot) opt = { :location => location, :originalroot => originalroot } begin WSDL::Parser.new(opt).parse(content) rescue WSDL::Parser::ParseError super(content, location, originalroot) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/part.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/part.rb
# WSDL4R - WSDL part definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL class Part < Info attr_reader :name # required attr_reader :element # optional attr_reader :type # optional def initialize super @name = nil @element = nil @type = nil end def parse_element(element) case element when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = value.source when ElementAttrName @element = value when TypeAttrName @type = value else nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/cgiStubCreator.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/cgiStubCreator.rb
# WSDL4R - Creating CGI stub code from WSDL. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/soap/mappingRegistryCreator' require 'wsdl/soap/methodDefCreator' require 'wsdl/soap/classDefCreatorSupport' module WSDL module SOAP class CGIStubCreator include ClassDefCreatorSupport attr_reader :definitions def initialize(definitions) @definitions = definitions end def dump(service_name) warn("CGI stub can have only 1 port. Creating stub for the first port... Rests are ignored.") port = @definitions.service(service_name).ports[0] dump_porttype(port.porttype.name) end private def dump_porttype(name) class_name = create_class_name(name) methoddef, types = MethodDefCreator.new(@definitions).dump(name) mr_creator = MappingRegistryCreator.new(@definitions) c1 = XSD::CodeGen::ClassDef.new(class_name) c1.def_require("soap/rpc/cgistub") c1.def_require("soap/mapping/registry") c1.def_const("MappingRegistry", "::SOAP::Mapping::Registry.new") c1.def_code(mr_creator.dump(types)) c1.def_code <<-EOD Methods = [ #{methoddef.gsub(/^/, " ")} ] EOD c2 = XSD::CodeGen::ClassDef.new(class_name + "App", "::SOAP::RPC::CGIStub") c2.def_method("initialize", "*arg") do <<-EOD super(*arg) servant = #{class_name}.new #{class_name}::Methods.each do |definitions| opt = definitions.last if opt[:request_style] == :document @router.add_document_operation(servant, *definitions) else @router.add_rpc_operation(servant, *definitions) end end self.mapping_registry = #{class_name}::MappingRegistry self.level = Logger::Severity::ERROR EOD end c1.dump + "\n" + c2.dump + format(<<-EOD) #{class_name}App.new('app', nil).start EOD end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/complexType.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/complexType.rb
# WSDL4R - SOAP complexType definition for WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/xmlSchema/complexType' require 'soap/mapping' module WSDL module XMLSchema class ComplexType < Info def compoundtype @compoundtype ||= check_type end def check_type if content if attributes.empty? and content.elements.size == 1 and content.elements[0].maxoccurs != '1' if name == ::SOAP::Mapping::MapQName :TYPE_MAP else :TYPE_ARRAY end else :TYPE_STRUCT end elsif complexcontent if complexcontent.base == ::SOAP::ValueArrayName :TYPE_ARRAY else complexcontent.basetype.check_type end elsif simplecontent :TYPE_SIMPLE elsif !attributes.empty? :TYPE_STRUCT else # empty complexType definition (seen in partner.wsdl of salesforce) :TYPE_EMPTY end end def child_type(name = nil) case compoundtype when :TYPE_STRUCT if ele = find_element(name) ele.type elsif ele = find_element_by_name(name.name) ele.type end when :TYPE_ARRAY @contenttype ||= content_arytype when :TYPE_MAP item_ele = find_element_by_name("item") or raise RuntimeError.new("'item' element not found in Map definition.") content = item_ele.local_complextype or raise RuntimeError.new("No complexType definition for 'item'.") if ele = content.find_element(name) ele.type elsif ele = content.find_element_by_name(name.name) ele.type end else raise NotImplementedError.new("Unknown kind of complexType.") end end def child_defined_complextype(name) ele = nil case compoundtype when :TYPE_STRUCT, :TYPE_MAP unless ele = find_element(name) if name.namespace.nil? ele = find_element_by_name(name.name) end end when :TYPE_ARRAY if content.elements.size == 1 ele = content.elements[0] else raise RuntimeError.new("Assert: must not reach.") end else raise RuntimeError.new("Assert: Not implemented.") end unless ele raise RuntimeError.new("Cannot find #{name} as a children of #{@name}.") end ele.local_complextype end def find_arytype unless compoundtype == :TYPE_ARRAY raise RuntimeError.new("Assert: not for array") end if complexcontent complexcontent.attributes.each do |attribute| if attribute.ref == ::SOAP::AttrArrayTypeName return attribute.arytype end end if check_array_content(complexcontent.content) return element_simpletype(complexcontent.content.elements[0]) end elsif check_array_content(content) return element_simpletype(content.elements[0]) end raise RuntimeError.new("Assert: Unknown array definition.") end def find_aryelement unless compoundtype == :TYPE_ARRAY raise RuntimeError.new("Assert: not for array") end if complexcontent if check_array_content(complexcontent.content) return complexcontent.content.elements[0] end elsif check_array_content(content) return content.elements[0] end nil # use default item name end private def element_simpletype(element) if element.type element.type elsif element.local_simpletype element.local_simpletype.base else nil end end def check_array_content(content) content and content.elements.size == 1 and content.elements[0].maxoccurs != '1' end def content_arytype if arytype = find_arytype ns = arytype.namespace name = arytype.name.sub(/\[(?:,)*\]$/, '') XSD::QName.new(ns, name) else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/data.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/data.rb
# WSDL4R - WSDL SOAP binding data definitions. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' require 'wsdl/soap/definitions' require 'wsdl/soap/binding' require 'wsdl/soap/operation' require 'wsdl/soap/body' require 'wsdl/soap/element' require 'wsdl/soap/header' require 'wsdl/soap/headerfault' require 'wsdl/soap/fault' require 'wsdl/soap/address' require 'wsdl/soap/complexType' module WSDL module SOAP HeaderFaultName = XSD::QName.new(SOAPBindingNamespace, 'headerfault') LocationAttrName = XSD::QName.new(nil, 'location') StyleAttrName = XSD::QName.new(nil, 'style') TransportAttrName = XSD::QName.new(nil, 'transport') UseAttrName = XSD::QName.new(nil, 'use') PartsAttrName = XSD::QName.new(nil, 'parts') PartAttrName = XSD::QName.new(nil, 'part') NameAttrName = XSD::QName.new(nil, 'name') MessageAttrName = XSD::QName.new(nil, 'message') EncodingStyleAttrName = XSD::QName.new(nil, 'encodingStyle') NamespaceAttrName = XSD::QName.new(nil, 'namespace') SOAPActionAttrName = XSD::QName.new(nil, 'soapAction') end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/servantSkeltonCreator.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/servantSkeltonCreator.rb
# WSDL4R - Creating servant skelton code from WSDL. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/soap/classDefCreatorSupport' require 'xsd/codegen' module WSDL module SOAP class ServantSkeltonCreator include ClassDefCreatorSupport include XSD::CodeGen::GenSupport attr_reader :definitions def initialize(definitions) @definitions = definitions end def dump(porttype = nil) if porttype.nil? result = "" @definitions.porttypes.each do |type| result << dump_porttype(type.name) result << "\n" end else result = dump_porttype(porttype) end result end private def dump_porttype(name) class_name = create_class_name(name) c = XSD::CodeGen::ClassDef.new(class_name) operations = @definitions.porttype(name).operations operations.each do |operation| name = safemethodname(operation.name.name) input = operation.input params = input.find_message.parts.collect { |part| safevarname(part.name) } m = XSD::CodeGen::MethodDef.new(name, params) do <<-EOD p [#{params.join(", ")}] raise NotImplementedError.new EOD end m.comment = dump_method_signature(operation) c.add_method(m) end c.dump end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/fault.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/fault.rb
# WSDL4R - WSDL SOAP body definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module SOAP class Fault < Info attr_reader :name # required attr_reader :use # required attr_reader :encodingstyle attr_reader :namespace def initialize super @name = nil @use = nil @encodingstyle = nil @namespace = nil end def targetnamespace parent.targetnamespace end def parse_element(element) nil end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) when UseAttrName @use = value.source when EncodingStyleAttrName @encodingstyle = value.source when NamespaceAttrName @namespace = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/element.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/element.rb
# WSDL4R - XMLSchema element definition for WSDL. # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/xmlSchema/element' module WSDL module XMLSchema class Element < Info def map_as_array? maxoccurs != '1' end def attributes @local_complextype.attributes end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/driverCreator.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/driverCreator.rb
# WSDL4R - Creating driver code from WSDL. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/soap/mappingRegistryCreator' require 'wsdl/soap/methodDefCreator' require 'wsdl/soap/classDefCreatorSupport' require 'xsd/codegen' module WSDL module SOAP class DriverCreator include ClassDefCreatorSupport attr_reader :definitions def initialize(definitions) @definitions = definitions end def dump(porttype = nil) if porttype.nil? result = "" @definitions.porttypes.each do |type| result << dump_porttype(type.name) result << "\n" end else result = dump_porttype(porttype) end result end private def dump_porttype(name) class_name = create_class_name(name) methoddef, types = MethodDefCreator.new(@definitions).dump(name) mr_creator = MappingRegistryCreator.new(@definitions) binding = @definitions.bindings.find { |item| item.type == name } return '' unless binding.soapbinding # not a SOAP binding address = @definitions.porttype(name).locations[0] c = XSD::CodeGen::ClassDef.new(class_name, "::SOAP::RPC::Driver") c.def_require("soap/rpc/driver") c.def_const("MappingRegistry", "::SOAP::Mapping::Registry.new") c.def_const("DefaultEndpointUrl", ndq(address)) c.def_code(mr_creator.dump(types)) c.def_code <<-EOD Methods = [ #{methoddef.gsub(/^/, " ")} ] EOD c.def_method("initialize", "endpoint_url = nil") do <<-EOD endpoint_url ||= DefaultEndpointUrl super(endpoint_url, nil) self.mapping_registry = MappingRegistry init_methods EOD end c.def_privatemethod("init_methods") do <<-EOD Methods.each do |definitions| opt = definitions.last if opt[:request_style] == :document add_document_operation(*definitions) else add_rpc_operation(*definitions) qname = definitions[0] name = definitions[2] if qname.name != name and qname.name.capitalize == name.capitalize ::SOAP::Mapping.define_singleton_method(self, qname.name) do |*arg| __send__(name, *arg) end end end end EOD end c.dump end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/address.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/address.rb
# WSDL4R - WSDL SOAP address definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module SOAP class Address < Info attr_reader :location def initialize super @location = nil end def parse_element(element) nil end def parse_attr(attr, value) case attr when LocationAttrName @location = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/clientSkeltonCreator.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/clientSkeltonCreator.rb
# WSDL4R - Creating client skelton code from WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/soap/classDefCreatorSupport' module WSDL module SOAP class ClientSkeltonCreator include ClassDefCreatorSupport attr_reader :definitions def initialize(definitions) @definitions = definitions end def dump(service_name) result = "" @definitions.service(service_name).ports.each do |port| result << dump_porttype(port.porttype.name) result << "\n" end result end private def dump_porttype(name) drv_name = create_class_name(name) result = "" result << <<__EOD__ endpoint_url = ARGV.shift obj = #{ drv_name }.new(endpoint_url) # run ruby with -d to see SOAP wiredumps. obj.wiredump_dev = STDERR if $DEBUG __EOD__ @definitions.porttype(name).operations.each do |operation| result << dump_method_signature(operation) result << dump_input_init(operation.input) << "\n" result << dump_operation(operation) << "\n\n" end result end def dump_operation(operation) name = operation.name input = operation.input "puts obj.#{ safemethodname(name.name) }#{ dump_inputparam(input) }" end def dump_input_init(input) result = input.find_message.parts.collect { |part| safevarname(part.name) }.join(" = ") if result.empty? "" else result << " = nil" end result end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/binding.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/binding.rb
# WSDL4R - WSDL SOAP binding definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module SOAP class Binding < Info attr_reader :style attr_reader :transport def initialize super @style = nil @transport = nil end def parse_element(element) nil end def parse_attr(attr, value) case attr when StyleAttrName if ["document", "rpc"].include?(value.source) @style = value.source.intern else raise Parser::AttributeConstraintError.new( "Unexpected value #{ value }.") end when TransportAttrName @transport = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/classDefCreatorSupport.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/classDefCreatorSupport.rb
# WSDL4R - Creating class code support from WSDL. # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'soap/mapping' require 'soap/mapping/typeMap' require 'xsd/codegen/gensupport' module WSDL module SOAP module ClassDefCreatorSupport include XSD::CodeGen::GenSupport def create_class_name(qname) if klass = basetype_mapped_class(qname) ::SOAP::Mapping::DefaultRegistry.find_mapped_obj_class(klass).name else safeconstname(qname.name) end end def basetype_mapped_class(name) ::SOAP::TypeMap[name] end def dump_method_signature(operation) name = operation.name.name input = operation.input output = operation.output fault = operation.fault signature = "#{ name }#{ dump_inputparam(input) }" str = <<__EOD__ # SYNOPSIS # #{name}#{dump_inputparam(input)} # # ARGS #{dump_inout_type(input).chomp} # # RETURNS #{dump_inout_type(output).chomp} # __EOD__ unless fault.empty? faultstr = (fault.collect { |f| dump_inout_type(f).chomp }).join(', ') str <<<<__EOD__ # RAISES # #{faultstr} # __EOD__ end str end def dq(ele) ele.dump end def ndq(ele) ele.nil? ? 'nil' : dq(ele) end def sym(ele) ':' + ele end def dqname(qname) qname.dump end private def dump_inout_type(param) if param message = param.find_message params = "" message.parts.each do |part| name = safevarname(part.name) if part.type typename = safeconstname(part.type.name) params << add_at("# #{name}", "#{typename} - #{part.type}\n", 20) elsif part.element typename = safeconstname(part.element.name) params << add_at("# #{name}", "#{typename} - #{part.element}\n", 20) end end unless params.empty? return params end end "# N/A\n" end def dump_inputparam(input) message = input.find_message params = "" message.parts.each do |part| params << ", " unless params.empty? params << safevarname(part.name) end if params.empty? "" else "(#{ params })" end end def add_at(base, str, pos) if base.size >= pos base + ' ' + str else base + ' ' * (pos - base.size) + str end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/definitions.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/definitions.rb
# WSDL4R - WSDL additional definitions for SOAP. # Copyright (C) 2002-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' require 'soap/mapping' module WSDL class Definitions < Info def self.soap_rpc_complextypes types = XSD::NamedElements.new types << array_complextype types << fault_complextype types << exception_complextype types end def self.array_complextype type = XMLSchema::ComplexType.new(::SOAP::ValueArrayName) type.complexcontent = XMLSchema::ComplexContent.new type.complexcontent.base = ::SOAP::ValueArrayName attr = XMLSchema::Attribute.new attr.ref = ::SOAP::AttrArrayTypeName anytype = XSD::AnyTypeName.dup anytype.name += '[]' attr.arytype = anytype type.complexcontent.attributes << attr type end =begin <xs:complexType name="Fault" final="extension"> <xs:sequence> <xs:element name="faultcode" type="xs:QName" /> <xs:element name="faultstring" type="xs:string" /> <xs:element name="faultactor" type="xs:anyURI" minOccurs="0" /> <xs:element name="detail" type="tns:detail" minOccurs="0" /> </xs:sequence> </xs:complexType> =end def self.fault_complextype type = XMLSchema::ComplexType.new(::SOAP::EleFaultName) faultcode = XMLSchema::Element.new(::SOAP::EleFaultCodeName, XSD::XSDQName::Type) faultstring = XMLSchema::Element.new(::SOAP::EleFaultStringName, XSD::XSDString::Type) faultactor = XMLSchema::Element.new(::SOAP::EleFaultActorName, XSD::XSDAnyURI::Type) faultactor.minoccurs = 0 detail = XMLSchema::Element.new(::SOAP::EleFaultDetailName, XSD::AnyTypeName) detail.minoccurs = 0 type.all_elements = [faultcode, faultstring, faultactor, detail] type.final = 'extension' type end def self.exception_complextype type = XMLSchema::ComplexType.new(XSD::QName.new( ::SOAP::Mapping::RubyCustomTypeNamespace, 'SOAPException')) excn_name = XMLSchema::Element.new(XSD::QName.new(nil, 'excn_type_name'), XSD::XSDString::Type) cause = XMLSchema::Element.new(XSD::QName.new(nil, 'cause'), XSD::AnyTypeName) backtrace = XMLSchema::Element.new(XSD::QName.new(nil, 'backtrace'), ::SOAP::ValueArrayName) message = XMLSchema::Element.new(XSD::QName.new(nil, 'message'), XSD::XSDString::Type) type.all_elements = [excn_name, cause, backtrace, message] type end def soap_rpc_complextypes(binding) types = rpc_operation_complextypes(binding) types + self.class.soap_rpc_complextypes end def collect_faulttypes result = [] collect_fault_messages.each do |name| faultparts = message(name).parts if faultparts.size != 1 raise RuntimeError.new("expecting fault message to have only 1 part") end if result.index(faultparts[0].type).nil? result << faultparts[0].type end end result end private def collect_fault_messages result = [] porttypes.each do |porttype| porttype.operations.each do |operation| operation.fault.each do |fault| if result.index(fault.message).nil? result << fault.message end end end end result end def rpc_operation_complextypes(binding) types = XSD::NamedElements.new binding.operations.each do |op_bind| if op_bind_rpc?(op_bind) operation = op_bind.find_operation if op_bind.input type = XMLSchema::ComplexType.new(op_bind.soapoperation_name) message = messages[operation.input.message] type.sequence_elements = elements_from_message(message) types << type end if op_bind.output type = XMLSchema::ComplexType.new(operation.outputname) message = messages[operation.output.message] type.sequence_elements = elements_from_message(message) types << type end end end types end def op_bind_rpc?(op_bind) op_bind.soapoperation_style == :rpc end def elements_from_message(message) message.parts.collect { |part| if part.element collect_elements[part.element] elsif part.name.nil? or part.type.nil? raise RuntimeError.new("part of a message must be an element or typed") else qname = XSD::QName.new(nil, part.name) XMLSchema::Element.new(qname, part.type) end } end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/classDefCreator.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/classDefCreator.rb
# WSDL4R - Creating class definition from WSDL # Copyright (C) 2002, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/data' require 'wsdl/soap/classDefCreatorSupport' require 'xsd/codegen' module WSDL module SOAP class ClassDefCreator include ClassDefCreatorSupport def initialize(definitions) @elements = definitions.collect_elements @simpletypes = definitions.collect_simpletypes @complextypes = definitions.collect_complextypes @faulttypes = nil if definitions.respond_to?(:collect_faulttypes) @faulttypes = definitions.collect_faulttypes end end def dump(type = nil) result = "require 'xsd/qname'\n" if type result = dump_classdef(type.name, type) else str = dump_element unless str.empty? result << "\n" unless result.empty? result << str end str = dump_complextype unless str.empty? result << "\n" unless result.empty? result << str end str = dump_simpletype unless str.empty? result << "\n" unless result.empty? result << str end end result end private def dump_element @elements.collect { |ele| if ele.local_complextype dump_classdef(ele.name, ele.local_complextype, ele.elementform == 'qualified') elsif ele.local_simpletype dump_simpletypedef(ele.name, ele.local_simpletype) else nil end }.compact.join("\n") end def dump_simpletype @simpletypes.collect { |type| dump_simpletypedef(type.name, type) }.compact.join("\n") end def dump_complextype @complextypes.collect { |type| case type.compoundtype when :TYPE_STRUCT, :TYPE_EMPTY dump_classdef(type.name, type) when :TYPE_ARRAY dump_arraydef(type) when :TYPE_SIMPLE dump_simpleclassdef(type) when :TYPE_MAP # mapped as a general Hash nil else raise RuntimeError.new( "unknown kind of complexContent: #{type.compoundtype}") end }.compact.join("\n") end def dump_simpletypedef(qname, simpletype) if !simpletype.restriction or simpletype.restriction.enumeration.empty? return nil end c = XSD::CodeGen::ModuleDef.new(create_class_name(qname)) c.comment = "#{qname}" const = {} simpletype.restriction.enumeration.each do |value| constname = safeconstname(value) const[constname] ||= 0 if (const[constname] += 1) > 1 constname += "_#{const[constname]}" end c.def_const(constname, ndq(value)) end c.dump end def dump_simpleclassdef(type_or_element) qname = type_or_element.name base = create_class_name(type_or_element.simplecontent.base) c = XSD::CodeGen::ClassDef.new(create_class_name(qname), base) c.comment = "#{qname}" c.dump end def dump_classdef(qname, typedef, qualified = false) if @faulttypes and @faulttypes.index(qname) c = XSD::CodeGen::ClassDef.new(create_class_name(qname), '::StandardError') else c = XSD::CodeGen::ClassDef.new(create_class_name(qname)) end c.comment = "#{qname}" c.def_classvar('schema_type', ndq(qname.name)) c.def_classvar('schema_ns', ndq(qname.namespace)) c.def_classvar('schema_qualified', dq('true')) if qualified schema_element = [] init_lines = '' params = [] typedef.each_element do |element| if element.type == XSD::AnyTypeName type = nil elsif klass = element_basetype(element) type = klass.name elsif element.type type = create_class_name(element.type) else type = nil # means anyType. # do we define a class for local complexType from it's name? # type = create_class_name(element.name) # <element> # <complexType> # <seq...> # </complexType> # </element> end name = name_element(element).name attrname = safemethodname?(name) ? name : safemethodname(name) varname = safevarname(name) c.def_attr(attrname, true, varname) init_lines << "@#{varname} = #{varname}\n" if element.map_as_array? params << "#{varname} = []" type << '[]' if type else params << "#{varname} = nil" end # nil means @@schema_ns + varname eleqname = (varname == name && element.name.namespace == qname.namespace) ? nil : element.name schema_element << [varname, eleqname, type] end unless typedef.attributes.empty? define_attribute(c, typedef.attributes) init_lines << "@__xmlattr = {}\n" end c.def_classvar('schema_element', '[' + schema_element.collect { |varname, name, type| '[' + ( if name varname.dump + ', [' + ndq(type) + ', ' + dqname(name) + ']' else varname.dump + ', ' + ndq(type) end ) + ']' }.join(', ') + ']' ) c.def_method('initialize', *params) do init_lines end c.dump end def element_basetype(ele) if klass = basetype_class(ele.type) klass elsif ele.local_simpletype basetype_class(ele.local_simpletype.base) else nil end end def attribute_basetype(attr) if klass = basetype_class(attr.type) klass elsif attr.local_simpletype basetype_class(attr.local_simpletype.base) else nil end end def basetype_class(type) return nil if type.nil? if simpletype = @simpletypes[type] basetype_mapped_class(simpletype.base) else basetype_mapped_class(type) end end def define_attribute(c, attributes) schema_attribute = [] attributes.each do |attribute| name = name_attribute(attribute) if klass = attribute_basetype(attribute) type = klass.name else type = nil end methodname = safemethodname('xmlattr_' + name.name) c.def_method(methodname) do <<-__EOD__ (@__xmlattr ||= {})[#{dqname(name)}] __EOD__ end c.def_method(methodname + '=', 'value') do <<-__EOD__ (@__xmlattr ||= {})[#{dqname(name)}] = value __EOD__ end schema_attribute << [name, type] end c.def_classvar('schema_attribute', '{' + schema_attribute.collect { |name, type| dqname(name) + ' => ' + ndq(type) }.join(', ') + '}' ) end def name_element(element) return element.name if element.name return element.ref if element.ref raise RuntimeError.new("cannot define name of #{element}") end def name_attribute(attribute) return attribute.name if attribute.name return attribute.ref if attribute.ref raise RuntimeError.new("cannot define name of #{attribute}") end DEFAULT_ITEM_NAME = XSD::QName.new(nil, 'item') def dump_arraydef(complextype) qname = complextype.name c = XSD::CodeGen::ClassDef.new(create_class_name(qname), '::Array') c.comment = "#{qname}" child_type = complextype.child_type c.def_classvar('schema_type', ndq(child_type.name)) c.def_classvar('schema_ns', ndq(child_type.namespace)) child_element = complextype.find_aryelement schema_element = [] if child_type == XSD::AnyTypeName type = nil elsif child_element and (klass = element_basetype(child_element)) type = klass.name elsif child_type type = create_class_name(child_type) else type = nil end if child_element if child_element.map_as_array? type << '[]' if type end child_element_name = child_element.name else child_element_name = DEFAULT_ITEM_NAME end schema_element << [child_element_name.name, child_element_name, type] c.def_classvar('schema_element', '[' + schema_element.collect { |varname, name, type| '[' + ( if name varname.dump + ', [' + ndq(type) + ', ' + dqname(name) + ']' else varname.dump + ', ' + ndq(type) end ) + ']' }.join(', ') + ']' ) c.dump end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/methodDefCreator.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/methodDefCreator.rb
# WSDL4R - Creating driver code from WSDL. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/soap/classDefCreatorSupport' require 'soap/rpc/element' module WSDL module SOAP class MethodDefCreator include ClassDefCreatorSupport attr_reader :definitions def initialize(definitions) @definitions = definitions @simpletypes = @definitions.collect_simpletypes @complextypes = @definitions.collect_complextypes @elements = @definitions.collect_elements @types = [] end def dump(porttype) @types.clear result = "" operations = @definitions.porttype(porttype).operations binding = @definitions.porttype_binding(porttype) operations.each do |operation| op_bind = binding.operations[operation.name] next unless op_bind # no binding is defined next unless op_bind.soapoperation # not a SOAP operation binding result << ",\n" unless result.empty? result << dump_method(operation, op_bind).chomp end return result, @types end def collect_rpcparameter(operation) result = operation.inputparts.collect { |part| collect_type(part.type) param_set(::SOAP::RPC::SOAPMethod::IN, part.name, rpcdefinedtype(part)) } outparts = operation.outputparts if outparts.size > 0 retval = outparts[0] collect_type(retval.type) result << param_set(::SOAP::RPC::SOAPMethod::RETVAL, retval.name, rpcdefinedtype(retval)) cdr(outparts).each { |part| collect_type(part.type) result << param_set(::SOAP::RPC::SOAPMethod::OUT, part.name, rpcdefinedtype(part)) } end result end def collect_documentparameter(operation) param = [] operation.inputparts.each do |input| param << param_set(::SOAP::RPC::SOAPMethod::IN, input.name, documentdefinedtype(input), elementqualified(input)) end operation.outputparts.each do |output| param << param_set(::SOAP::RPC::SOAPMethod::OUT, output.name, documentdefinedtype(output), elementqualified(output)) end param end private def dump_method(operation, binding) name = safemethodname(operation.name.name) name_as = operation.name.name style = binding.soapoperation_style inputuse = binding.input.soapbody_use outputuse = binding.output.soapbody_use namespace = binding.input.soapbody.namespace if style == :rpc qname = XSD::QName.new(namespace, name_as) paramstr = param2str(collect_rpcparameter(operation)) else qname = nil paramstr = param2str(collect_documentparameter(operation)) end if paramstr.empty? paramstr = '[]' else paramstr = "[ " << paramstr.split(/\r?\n/).join("\n ") << " ]" end definitions = <<__EOD__ #{ndq(binding.soapaction)}, #{dq(name)}, #{paramstr}, { :request_style => #{sym(style.id2name)}, :request_use => #{sym(inputuse.id2name)}, :response_style => #{sym(style.id2name)}, :response_use => #{sym(outputuse.id2name)} } __EOD__ if style == :rpc return <<__EOD__ [ #{qname.dump}, #{definitions}] __EOD__ else return <<__EOD__ [ #{definitions}] __EOD__ end end def rpcdefinedtype(part) if mapped = basetype_mapped_class(part.type) ['::' + mapped.name] elsif definedtype = @simpletypes[part.type] ['::' + basetype_mapped_class(definedtype.base).name] elsif definedtype = @elements[part.element] #['::SOAP::SOAPStruct', part.element.namespace, part.element.name] ['nil', part.element.namespace, part.element.name] elsif definedtype = @complextypes[part.type] case definedtype.compoundtype when :TYPE_STRUCT, :TYPE_EMPTY # ToDo: empty should be treated as void. type = create_class_name(part.type) [type, part.type.namespace, part.type.name] when :TYPE_MAP [Hash.name, part.type.namespace, part.type.name] when :TYPE_ARRAY arytype = definedtype.find_arytype || XSD::AnyTypeName ns = arytype.namespace name = arytype.name.sub(/\[(?:,)*\]$/, '') type = create_class_name(XSD::QName.new(ns, name)) [type + '[]', ns, name] else raise NotImplementedError.new("must not reach here") end else raise RuntimeError.new("part: #{part.name} cannot be resolved") end end def documentdefinedtype(part) if mapped = basetype_mapped_class(part.type) ['::' + mapped.name, nil, part.name] elsif definedtype = @simpletypes[part.type] ['::' + basetype_mapped_class(definedtype.base).name, nil, part.name] elsif definedtype = @elements[part.element] ['::SOAP::SOAPElement', part.element.namespace, part.element.name] elsif definedtype = @complextypes[part.type] ['::SOAP::SOAPElement', part.type.namespace, part.type.name] else raise RuntimeError.new("part: #{part.name} cannot be resolved") end end def elementqualified(part) if mapped = basetype_mapped_class(part.type) false elsif definedtype = @simpletypes[part.type] false elsif definedtype = @elements[part.element] definedtype.elementform == 'qualified' elsif definedtype = @complextypes[part.type] false else raise RuntimeError.new("part: #{part.name} cannot be resolved") end end def param_set(io_type, name, type, ele = nil) [io_type, name, type, ele] end def collect_type(type) # ignore inline type definition. return if type.nil? return if @types.include?(type) @types << type return unless @complextypes[type] @complextypes[type].each_element do |element| collect_type(element.type) end end def param2str(params) params.collect { |param| io, name, type, ele = param unless ele.nil? "[#{dq(io)}, #{dq(name)}, #{type2str(type)}, #{ele2str(ele)}]" else "[#{dq(io)}, #{dq(name)}, #{type2str(type)}]" end }.join(",\n") end def type2str(type) if type.size == 1 "[#{dq(type[0])}]" else "[#{dq(type[0])}, #{ndq(type[1])}, #{dq(type[2])}]" end end def ele2str(ele) qualified = ele if qualified "true" else "false" end end def cdr(ary) result = ary.dup result.shift result end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/body.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/body.rb
# WSDL4R - WSDL SOAP body definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module SOAP class Body < Info attr_reader :parts attr_reader :use # required attr_reader :encodingstyle attr_reader :namespace def initialize super @parts = nil @use = nil @encodingstyle = nil @namespace = nil end def parse_element(element) nil end def parse_attr(attr, value) case attr when PartsAttrName @parts = value.source when UseAttrName if ['literal', 'encoded'].include?(value.source) @use = value.source.intern else raise RuntimeError.new("unknown use of soap:body: #{value.source}") end when EncodingStyleAttrName @encodingstyle = value.source when NamespaceAttrName @namespace = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/standaloneServerStubCreator.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/standaloneServerStubCreator.rb
# WSDL4R - Creating standalone server stub code from WSDL. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/soap/mappingRegistryCreator' require 'wsdl/soap/methodDefCreator' require 'wsdl/soap/classDefCreatorSupport' module WSDL module SOAP class StandaloneServerStubCreator include ClassDefCreatorSupport attr_reader :definitions def initialize(definitions) @definitions = definitions end def dump(service_name) warn("- Standalone stub can have only 1 port for now. So creating stub for the first port and rests are ignored.") warn("- Standalone server stub ignores port location defined in WSDL. Location is http://localhost:10080/ by default. Generated client from WSDL must be configured to point this endpoint manually.") port = @definitions.service(service_name).ports[0] dump_porttype(port.porttype.name) end private def dump_porttype(name) class_name = create_class_name(name) methoddef, types = MethodDefCreator.new(@definitions).dump(name) mr_creator = MappingRegistryCreator.new(@definitions) c1 = XSD::CodeGen::ClassDef.new(class_name) c1.def_require("soap/rpc/standaloneServer") c1.def_require("soap/mapping/registry") c1.def_const("MappingRegistry", "::SOAP::Mapping::Registry.new") c1.def_code(mr_creator.dump(types)) c1.def_code <<-EOD Methods = [ #{methoddef.gsub(/^/, " ")} ] EOD c2 = XSD::CodeGen::ClassDef.new(class_name + "App", "::SOAP::RPC::StandaloneServer") c2.def_method("initialize", "*arg") do <<-EOD super(*arg) servant = #{class_name}.new #{class_name}::Methods.each do |definitions| opt = definitions.last if opt[:request_style] == :document @router.add_document_operation(servant, *definitions) else @router.add_rpc_operation(servant, *definitions) end end self.mapping_registry = #{class_name}::MappingRegistry EOD end c1.dump + "\n" + c2.dump + format(<<-EOD) if $0 == __FILE__ # Change listen port. server = #{class_name}App.new('app', nil, '0.0.0.0', 10080) trap(:INT) do server.shutdown end server.start end EOD end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/wsdl2ruby.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/wsdl2ruby.rb
# WSDL4R - WSDL to ruby mapping library. # Copyright (C) 2002-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'logger' require 'xsd/qname' require 'wsdl/importer' require 'wsdl/soap/classDefCreator' require 'wsdl/soap/servantSkeltonCreator' require 'wsdl/soap/driverCreator' require 'wsdl/soap/clientSkeltonCreator' require 'wsdl/soap/standaloneServerStubCreator' require 'wsdl/soap/cgiStubCreator' module WSDL module SOAP class WSDL2Ruby attr_accessor :location attr_reader :opt attr_accessor :logger attr_accessor :basedir def run unless @location raise RuntimeError, "WSDL location not given" end @wsdl = import(@location) @name = @wsdl.name ? @wsdl.name.name : 'default' create_file end private def initialize @location = nil @opt = {} @logger = Logger.new(STDERR) @basedir = nil @wsdl = nil @name = nil end def create_file create_classdef if @opt.key?('classdef') create_servant_skelton(@opt['servant_skelton']) if @opt.key?('servant_skelton') create_cgi_stub(@opt['cgi_stub']) if @opt.key?('cgi_stub') create_standalone_server_stub(@opt['standalone_server_stub']) if @opt.key?('standalone_server_stub') create_driver(@opt['driver']) if @opt.key?('driver') create_client_skelton(@opt['client_skelton']) if @opt.key?('client_skelton') end def create_classdef @logger.info { "Creating class definition." } @classdef_filename = @name + '.rb' check_file(@classdef_filename) or return write_file(@classdef_filename) do |f| f << WSDL::SOAP::ClassDefCreator.new(@wsdl).dump end end def create_client_skelton(servicename) @logger.info { "Creating client skelton." } servicename ||= @wsdl.services[0].name.name @client_skelton_filename = servicename + 'Client.rb' check_file(@client_skelton_filename) or return write_file(@client_skelton_filename) do |f| f << shbang << "\n" f << "require '#{@driver_filename}'\n\n" if @driver_filename f << WSDL::SOAP::ClientSkeltonCreator.new(@wsdl).dump( create_name(servicename)) end end def create_servant_skelton(porttypename) @logger.info { "Creating servant skelton." } @servant_skelton_filename = (porttypename || @name + 'Servant') + '.rb' check_file(@servant_skelton_filename) or return write_file(@servant_skelton_filename) do |f| f << "require '#{@classdef_filename}'\n\n" if @classdef_filename f << WSDL::SOAP::ServantSkeltonCreator.new(@wsdl).dump( create_name(porttypename)) end end def create_cgi_stub(servicename) @logger.info { "Creating CGI stub." } servicename ||= @wsdl.services[0].name.name @cgi_stubFilename = servicename + '.cgi' check_file(@cgi_stubFilename) or return write_file(@cgi_stubFilename) do |f| f << shbang << "\n" if @servant_skelton_filename f << "require '#{@servant_skelton_filename}'\n\n" end f << WSDL::SOAP::CGIStubCreator.new(@wsdl).dump(create_name(servicename)) end end def create_standalone_server_stub(servicename) @logger.info { "Creating standalone stub." } servicename ||= @wsdl.services[0].name.name @standalone_server_stub_filename = servicename + '.rb' check_file(@standalone_server_stub_filename) or return write_file(@standalone_server_stub_filename) do |f| f << shbang << "\n" f << "require '#{@servant_skelton_filename}'\n\n" if @servant_skelton_filename f << WSDL::SOAP::StandaloneServerStubCreator.new(@wsdl).dump( create_name(servicename)) end end def create_driver(porttypename) @logger.info { "Creating driver." } @driver_filename = (porttypename || @name) + 'Driver.rb' check_file(@driver_filename) or return write_file(@driver_filename) do |f| f << "require '#{@classdef_filename}'\n\n" if @classdef_filename f << WSDL::SOAP::DriverCreator.new(@wsdl).dump( create_name(porttypename)) end end def write_file(filename) if @basedir filename = File.join(basedir, filename) end File.open(filename, "w") do |f| yield f end end def check_file(filename) if @basedir filename = File.join(basedir, filename) end if FileTest.exist?(filename) if @opt.key?('force') @logger.warn { "File '#{filename}' exists but overrides it." } true else @logger.warn { "File '#{filename}' exists. #{$0} did not override it." } false end else @logger.info { "Creates file '#{filename}'." } true end end def shbang "#!/usr/bin/env ruby" end def create_name(name) name ? XSD::QName.new(@wsdl.targetnamespace, name) : nil end def import(location) WSDL::Importer.import(location) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/operation.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/operation.rb
# WSDL4R - WSDL SOAP operation definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module SOAP class Operation < Info class OperationInfo attr_reader :style attr_reader :op_name attr_reader :optype_name attr_reader :headerparts attr_reader :bodyparts attr_reader :faultpart attr_reader :soapaction def initialize(style, op_name, optype_name, headerparts, bodyparts, faultpart, soapaction) @style = style @op_name = op_name @optype_name = optype_name @headerparts = headerparts @bodyparts = bodyparts @faultpart = faultpart @soapaction = soapaction end end attr_reader :soapaction attr_reader :style def initialize super @soapaction = nil @style = nil end def parse_element(element) nil end def parse_attr(attr, value) case attr when StyleAttrName if ["document", "rpc"].include?(value.source) @style = value.source.intern else raise Parser::AttributeConstraintError.new( "Unexpected value #{ value }.") end when SOAPActionAttrName @soapaction = value.source else nil end end def input_info name_info = parent.find_operation.input_info param_info(name_info, parent.input) end def output_info name_info = parent.find_operation.output_info param_info(name_info, parent.output) end def operation_style return @style if @style if parent_binding.soapbinding return parent_binding.soapbinding.style end nil end private def parent_binding parent.parent end def param_info(name_info, param) op_name = name_info.op_name optype_name = name_info.optype_name soapheader = param.soapheader headerparts = soapheader.collect { |item| item.find_part } soapbody = param.soapbody if soapbody.encodingstyle and soapbody.encodingstyle != ::SOAP::EncodingNamespace raise NotImplementedError.new( "EncodingStyle '#{ soapbody.encodingstyle }' not supported.") end if soapbody.namespace op_name = XSD::QName.new(soapbody.namespace, op_name.name) end if soapbody.parts target = soapbody.parts.split(/\s+/) bodyparts = name_info.parts.find_all { |part| target.include?(part.name) } else bodyparts = name_info.parts end faultpart = nil OperationInfo.new(operation_style, op_name, optype_name, headerparts, bodyparts, faultpart, parent.soapaction) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/header.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/header.rb
# WSDL4R - WSDL SOAP body definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module SOAP class Header < Info attr_reader :headerfault attr_reader :message # required attr_reader :part # required attr_reader :use # required attr_reader :encodingstyle attr_reader :namespace def initialize super @message = nil @part = nil @use = nil @encodingstyle = nil @namespace = nil @headerfault = nil end def targetnamespace parent.targetnamespace end def find_message root.message(@message) or raise RuntimeError.new("#{@message} not found") end def find_part find_message.parts.each do |part| if part.name == @part return part end end raise RuntimeError.new("#{@part} not found") end def parse_element(element) case element when HeaderFaultName o = WSDL::SOAP::HeaderFault.new @headerfault = o o else nil end end def parse_attr(attr, value) case attr when MessageAttrName if value.namespace.nil? value = XSD::QName.new(targetnamespace, value.source) end @message = value when PartAttrName @part = value.source when UseAttrName @use = value.source when EncodingStyleAttrName @encodingstyle = value.source when NamespaceAttrName @namespace = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/headerfault.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/headerfault.rb
# WSDL4R - WSDL SOAP body definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module SOAP class HeaderFault < Info attr_reader :message # required attr_reader :part # required attr_reader :use # required attr_reader :encodingstyle attr_reader :namespace def initialize super @message = nil @part = nil @use = nil @encodingstyle = nil @namespace = nil end def parse_element(element) nil end def parse_attr(attr, value) case attr when MessageAttrName @message = value when PartAttrName @part = value.source when UseAttrName @use = value.source when EncodingStyleAttrName @encodingstyle = value.source when NamespaceAttrName @namespace = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/mappingRegistryCreator.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/soap/mappingRegistryCreator.rb
# WSDL4R - Creating MappingRegistry code from WSDL. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/soap/classDefCreatorSupport' module WSDL module SOAP class MappingRegistryCreator include ClassDefCreatorSupport attr_reader :definitions def initialize(definitions) @definitions = definitions @complextypes = @definitions.collect_complextypes @types = nil end def dump(types) @types = types map_cache = [] map = "" @types.each do |type| if map_cache.index(type).nil? map_cache << type if type.namespace != XSD::Namespace if typemap = dump_typemap(type) map << typemap end end end end return map end private def dump_typemap(type) if definedtype = @complextypes[type] case definedtype.compoundtype when :TYPE_STRUCT dump_struct_typemap(definedtype) when :TYPE_ARRAY dump_array_typemap(definedtype) when :TYPE_MAP, :TYPE_EMPTY nil else raise NotImplementedError.new("must not reach here") end end end def dump_struct_typemap(definedtype) ele = definedtype.name return <<__EOD__ MappingRegistry.set( #{create_class_name(ele)}, ::SOAP::SOAPStruct, ::SOAP::Mapping::Registry::TypedStructFactory, { :type => #{dqname(ele)} } ) __EOD__ end def dump_array_typemap(definedtype) ele = definedtype.name arytype = definedtype.find_arytype || XSD::AnyTypeName type = XSD::QName.new(arytype.namespace, arytype.name.sub(/\[(?:,)*\]$/, '')) @types << type return <<__EOD__ MappingRegistry.set( #{create_class_name(ele)}, ::SOAP::SOAPArray, ::SOAP::Mapping::Registry::TypedArrayFactory, { :type => #{dqname(type)} } ) __EOD__ end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/complexType.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/complexType.rb
# WSDL4R - XMLSchema complexType definition for WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/xmlSchema/content' require 'wsdl/xmlSchema/element' require 'xsd/namedelements' module WSDL module XMLSchema class ComplexType < Info attr_accessor :name attr_accessor :complexcontent attr_accessor :simplecontent attr_reader :content attr_accessor :final attr_accessor :mixed attr_reader :attributes def initialize(name = nil) super() @name = name @complexcontent = nil @simplecontent = nil @content = nil @final = nil @mixed = false @attributes = XSD::NamedElements.new end def targetnamespace # inner elements can be qualified # parent.is_a?(WSDL::XMLSchema::Element) ? nil : parent.targetnamespace parent.targetnamespace end def elementformdefault parent.elementformdefault end AnyAsElement = Element.new(XSD::QName.new(nil, 'any'), XSD::AnyTypeName) def each_element if content content.elements.each do |element| if element.is_a?(Any) yield(AnyAsElement) else yield(element) end end end end def find_element(name) if content content.elements.each do |element| if element.is_a?(Any) return AnyAsElement if name == AnyAsElement.name else return element if name == element.name end end end nil end def find_element_by_name(name) if content content.elements.each do |element| if element.is_a?(Any) return AnyAsElement if name == AnyAsElement.name.name else return element if name == element.name.name end end end nil end def sequence_elements=(elements) @content = Sequence.new elements.each do |element| @content << element end end def all_elements=(elements) @content = All.new elements.each do |element| @content << element end end def parse_element(element) case element when AllName @content = All.new when SequenceName @content = Sequence.new when ChoiceName @content = Choice.new when ComplexContentName @complexcontent = ComplexContent.new when SimpleContentName @simplecontent = SimpleContent.new when AttributeName o = Attribute.new @attributes << o o else nil end end def parse_attr(attr, value) case attr when FinalAttrName @final = value.source when MixedAttrName @mixed = (value.source == 'true') when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/data.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/data.rb
# WSDL4R - XMLSchema data definitions. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/datatypes' require 'wsdl/xmlSchema/annotation' require 'wsdl/xmlSchema/schema' require 'wsdl/xmlSchema/import' require 'wsdl/xmlSchema/include' require 'wsdl/xmlSchema/simpleType' require 'wsdl/xmlSchema/simpleRestriction' require 'wsdl/xmlSchema/simpleExtension' require 'wsdl/xmlSchema/complexType' require 'wsdl/xmlSchema/complexContent' require 'wsdl/xmlSchema/simpleContent' require 'wsdl/xmlSchema/any' require 'wsdl/xmlSchema/element' require 'wsdl/xmlSchema/all' require 'wsdl/xmlSchema/choice' require 'wsdl/xmlSchema/sequence' require 'wsdl/xmlSchema/attribute' require 'wsdl/xmlSchema/unique' require 'wsdl/xmlSchema/enumeration' require 'wsdl/xmlSchema/length' require 'wsdl/xmlSchema/pattern' module WSDL module XMLSchema AllName = XSD::QName.new(XSD::Namespace, 'all') AnnotationName = XSD::QName.new(XSD::Namespace, 'annotation') AnyName = XSD::QName.new(XSD::Namespace, 'any') AttributeName = XSD::QName.new(XSD::Namespace, 'attribute') ChoiceName = XSD::QName.new(XSD::Namespace, 'choice') ComplexContentName = XSD::QName.new(XSD::Namespace, 'complexContent') ComplexTypeName = XSD::QName.new(XSD::Namespace, 'complexType') ElementName = XSD::QName.new(XSD::Namespace, 'element') EnumerationName = XSD::QName.new(XSD::Namespace, 'enumeration') ExtensionName = XSD::QName.new(XSD::Namespace, 'extension') ImportName = XSD::QName.new(XSD::Namespace, 'import') IncludeName = XSD::QName.new(XSD::Namespace, 'include') LengthName = XSD::QName.new(XSD::Namespace, 'length') PatternName = XSD::QName.new(XSD::Namespace, 'pattern') RestrictionName = XSD::QName.new(XSD::Namespace, 'restriction') SequenceName = XSD::QName.new(XSD::Namespace, 'sequence') SchemaName = XSD::QName.new(XSD::Namespace, 'schema') SimpleContentName = XSD::QName.new(XSD::Namespace, 'simpleContent') SimpleTypeName = XSD::QName.new(XSD::Namespace, 'simpleType') UniqueName = XSD::QName.new(XSD::Namespace, 'unique') AttributeFormDefaultAttrName = XSD::QName.new(nil, 'attributeFormDefault') BaseAttrName = XSD::QName.new(nil, 'base') DefaultAttrName = XSD::QName.new(nil, 'default') ElementFormDefaultAttrName = XSD::QName.new(nil, 'elementFormDefault') FinalAttrName = XSD::QName.new(nil, 'final') FixedAttrName = XSD::QName.new(nil, 'fixed') FormAttrName = XSD::QName.new(nil, 'form') IdAttrName = XSD::QName.new(nil, 'id') MaxOccursAttrName = XSD::QName.new(nil, 'maxOccurs') MinOccursAttrName = XSD::QName.new(nil, 'minOccurs') MixedAttrName = XSD::QName.new(nil, 'mixed') NameAttrName = XSD::QName.new(nil, 'name') NamespaceAttrName = XSD::QName.new(nil, 'namespace') NillableAttrName = XSD::QName.new(nil, 'nillable') ProcessContentsAttrName = XSD::QName.new(nil, 'processContents') RefAttrName = XSD::QName.new(nil, 'ref') SchemaLocationAttrName = XSD::QName.new(nil, 'schemaLocation') TargetNamespaceAttrName = XSD::QName.new(nil, 'targetNamespace') TypeAttrName = XSD::QName.new(nil, 'type') UseAttrName = XSD::QName.new(nil, 'use') ValueAttrName = XSD::QName.new(nil, 'value') end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/content.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/content.rb
# WSDL4R - XMLSchema complexType definition for WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Content < Info attr_accessor :final attr_accessor :mixed attr_accessor :type attr_reader :contents attr_reader :elements def initialize super() @final = nil @mixed = false @type = nil @contents = [] @elements = [] end def targetnamespace parent.targetnamespace end def <<(content) @contents << content update_elements end def each @contents.each do |content| yield content end end def parse_element(element) case element when AllName, SequenceName, ChoiceName o = Content.new o.type = element.name @contents << o o when AnyName o = Any.new @contents << o o when ElementName o = Element.new @contents << o o else nil end end def parse_attr(attr, value) case attr when FinalAttrName @final = value.source when MixedAttrName @mixed = (value.source == 'true') else nil end end def parse_epilogue update_elements end private def update_elements @elements = [] @contents.each do |content| if content.is_a?(Element) @elements << [content.name, content] end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/element.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/element.rb
# WSDL4R - XMLSchema element definition for WSDL. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Element < Info class << self if RUBY_VERSION > "1.7.0" def attr_reader_ref(symbol) name = symbol.to_s define_method(name) { instance_variable_get("@#{name}") || (refelement ? refelement.__send__(name) : nil) } end else def attr_reader_ref(symbol) name = symbol.to_s module_eval <<-EOS def #{name} @#{name} || (refelement ? refelement.#{name} : nil) end EOS end end end attr_writer :name # required attr_writer :form attr_writer :type attr_writer :local_simpletype attr_writer :local_complextype attr_writer :constraint attr_writer :maxoccurs attr_writer :minoccurs attr_writer :nillable attr_reader_ref :name attr_reader_ref :form attr_reader_ref :type attr_reader_ref :local_simpletype attr_reader_ref :local_complextype attr_reader_ref :constraint attr_reader_ref :maxoccurs attr_reader_ref :minoccurs attr_reader_ref :nillable attr_accessor :ref def initialize(name = nil, type = nil) super() @name = name @form = nil @type = type @local_simpletype = @local_complextype = nil @constraint = nil @maxoccurs = '1' @minoccurs = '1' @nillable = nil @ref = nil @refelement = nil end def refelement @refelement ||= (@ref ? root.collect_elements[@ref] : nil) end def targetnamespace parent.targetnamespace end def elementformdefault parent.elementformdefault end def elementform self.form.nil? ? parent.elementformdefault : self.form end def parse_element(element) case element when SimpleTypeName @local_simpletype = SimpleType.new @local_simpletype when ComplexTypeName @type = nil @local_complextype = ComplexType.new @local_complextype when UniqueName @constraint = Unique.new @constraint else nil end end def parse_attr(attr, value) case attr when NameAttrName # namespace may be nil if directelement? or elementform == 'qualified' @name = XSD::QName.new(targetnamespace, value.source) else @name = XSD::QName.new(nil, value.source) end when FormAttrName @form = value.source when TypeAttrName @type = value when RefAttrName @ref = value when MaxOccursAttrName if parent.is_a?(All) if value.source != '1' raise Parser::AttrConstraintError.new( "cannot parse #{value} for #{attr}") end end @maxoccurs = value.source when MinOccursAttrName if parent.is_a?(All) unless ['0', '1'].include?(value.source) raise Parser::AttrConstraintError.new( "cannot parse #{value} for #{attr}") end end @minoccurs = value.source when NillableAttrName @nillable = (value.source == 'true') else nil end end private def directelement? parent.is_a?(Schema) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/include.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/include.rb
# WSDL4R - XMLSchema include definition. # Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/xmlSchema/importer' module WSDL module XMLSchema class Include < Info attr_reader :schemalocation attr_reader :content def initialize super @schemalocation = nil @content = nil end def parse_element(element) nil end def parse_attr(attr, value) case attr when SchemaLocationAttrName @schemalocation = URI.parse(value.source) if @schemalocation.relative? @schemalocation = parent.location + @schemalocation end @content = import(@schemalocation) @schemalocation else nil end end private def import(location) Importer.import(location) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/simpleType.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/simpleType.rb
# WSDL4R - XMLSchema simpleType definition for WSDL. # Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL module XMLSchema class SimpleType < Info attr_accessor :name attr_reader :restriction def check_lexical_format(value) if @restriction check_restriction(value) else raise ArgumentError.new("incomplete simpleType") end end def base if @restriction @restriction.base else raise ArgumentError.new("incomplete simpleType") end end def initialize(name = nil) super() @name = name @restriction = nil end def targetnamespace parent.targetnamespace end def parse_element(element) case element when RestrictionName @restriction = SimpleRestriction.new @restriction end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) end end private def check_restriction(value) unless @restriction.valid?(value) raise XSD::ValueSpaceError.new("#{@name}: cannot accept '#{value}'") end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/xsd2ruby.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/xsd2ruby.rb
# XSD4R - XSD to ruby mapping library. # Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/codegen/gensupport' require 'wsdl/xmlSchema/importer' require 'wsdl/soap/classDefCreator' module WSDL module XMLSchema class XSD2Ruby attr_accessor :location attr_reader :opt attr_accessor :logger attr_accessor :basedir def run unless @location raise RuntimeError, "XML Schema location not given" end @xsd = import(@location) @name = create_classname(@xsd) create_file end private def initialize @location = nil @opt = {} @logger = Logger.new(STDERR) @basedir = nil @xsd = nil @name = nil end def create_file create_classdef end def create_classdef @logger.info { "Creating class definition." } @classdef_filename = @name + '.rb' check_file(@classdef_filename) or return write_file(@classdef_filename) do |f| f << WSDL::SOAP::ClassDefCreator.new(@xsd).dump end end def write_file(filename) if @basedir filename = File.join(basedir, filename) end File.open(filename, "w") do |f| yield f end end def check_file(filename) if @basedir filename = File.join(basedir, filename) end if FileTest.exist?(filename) if @opt.key?('force') @logger.warn { "File '#{filename}' exists but overrides it." } true else @logger.warn { "File '#{filename}' exists. #{$0} did not override it." } false end else @logger.info { "Creates file '#{filename}'." } true end end def create_classname(xsd) name = nil if xsd.targetnamespace name = xsd.targetnamespace.scan(/[a-zA-Z0-9]+$/)[0] end if name.nil? 'default' else XSD::CodeGen::GenSupport.safevarname(name) end end def import(location) WSDL::XMLSchema::Importer.import(location) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/annotation.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/annotation.rb
# WSDL4R - WSDL SOAP documentation element. # Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Annotation < Info def initialize super end def parse_element(element) # Accepts any element. self end def parse_attr(attr, value) # Accepts any attribute. true end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/attribute.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/attribute.rb
# WSDL4R - XMLSchema attribute definition for WSDL. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Attribute < Info class << self if RUBY_VERSION > "1.7.0" def attr_reader_ref(symbol) name = symbol.to_s define_method(name) { instance_variable_get("@#{name}") || (refelement ? refelement.__send__(name) : nil) } end else def attr_reader_ref(symbol) name = symbol.to_s module_eval <<-EOS def #{name} @#{name} || (refelement ? refelement.#{name} : nil) end EOS end end end attr_writer :use attr_writer :form attr_writer :name attr_writer :type attr_writer :local_simpletype attr_writer :default attr_writer :fixed attr_reader_ref :use attr_reader_ref :form attr_reader_ref :name attr_reader_ref :type attr_reader_ref :local_simpletype attr_reader_ref :default attr_reader_ref :fixed attr_accessor :ref attr_accessor :arytype def initialize super @use = nil @form = nil @name = nil @type = nil @local_simpletype = nil @default = nil @fixed = nil @ref = nil @refelement = nil @arytype = nil end def refelement @refelement ||= root.collect_attributes[@ref] end def targetnamespace parent.targetnamespace end def parse_element(element) case element when SimpleTypeName @local_simpletype = SimpleType.new @local_simpletype end end def parse_attr(attr, value) case attr when RefAttrName @ref = value when UseAttrName @use = value.source when FormAttrName @form = value.source when NameAttrName if directelement? @name = XSD::QName.new(targetnamespace, value.source) else @name = XSD::QName.new(nil, value.source) end when TypeAttrName @type = value when DefaultAttrName @default = value.source when FixedAttrName @fixed = value.source when ArrayTypeAttrName @arytype = if value.namespace.nil? XSD::QName.new(XSD::Namespace, value.source) else value end else nil end end private def directelement? parent.is_a?(Schema) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/length.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/length.rb
# WSDL4R - XMLSchema length definition for WSDL. # Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Length < Info def initialize super end def parse_element(element) nil end def parse_attr(attr, value) case attr when ValueAttrName value.source end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/unique.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/unique.rb
# WSDL4R - XMLSchema unique element. # Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Unique < Info def initialize super end def parse_element(element) # Accepts any element. self end def parse_attr(attr, value) # Accepts any attribute. true end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/any.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/any.rb
# WSDL4R - XMLSchema any definition for WSDL. # Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Any < Info attr_accessor :maxoccurs attr_accessor :minoccurs attr_accessor :namespace attr_accessor :process_contents def initialize super() @maxoccurs = '1' @minoccurs = '1' @namespace = '##any' @process_contents = 'strict' end def targetnamespace parent.targetnamespace end def parse_element(element) nil end def parse_attr(attr, value) case attr when MaxOccursAttrName @maxoccurs = value.source when MinOccursAttrName @minoccurs = value.source when NamespaceAttrName @namespace = value.source when ProcessContentsAttrName @process_contents = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/parser.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/parser.rb
# WSDL4R - WSDL XML Instance parser library. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' require 'xsd/ns' require 'xsd/charset' require 'xsd/datatypes' require 'xsd/xmlparser' require 'wsdl/xmlSchema/data' module WSDL module XMLSchema class Parser include XSD class ParseError < Error; end class FormatDecodeError < ParseError; end class UnknownElementError < FormatDecodeError; end class UnknownAttributeError < FormatDecodeError; end class UnexpectedElementError < FormatDecodeError; end class ElementConstraintError < FormatDecodeError; end class AttributeConstraintError < FormatDecodeError; end private class ParseFrame attr_reader :ns attr_reader :name attr_accessor :node private def initialize(ns, name, node) @ns = ns @name = name @node = node end end public def initialize(opt = {}) @parser = XSD::XMLParser.create_parser(self, opt) @parsestack = nil @lastnode = nil @ignored = {} @location = opt[:location] @originalroot = opt[:originalroot] end def parse(string_or_readable) @parsestack = [] @lastnode = nil @textbuf = '' @parser.do_parse(string_or_readable) @lastnode end def charset @parser.charset end def start_element(name, attrs) lastframe = @parsestack.last ns = parent = nil if lastframe ns = lastframe.ns.clone_ns parent = lastframe.node else ns = XSD::NS.new parent = nil end attrs = XSD::XMLParser.filter_ns(ns, attrs) node = decode_tag(ns, name, attrs, parent) @parsestack << ParseFrame.new(ns, name, node) end def characters(text) lastframe = @parsestack.last if lastframe # Need not to be cloned because character does not have attr. ns = lastframe.ns decode_text(ns, text) else p text if $DEBUG end end def end_element(name) lastframe = @parsestack.pop unless name == lastframe.name raise UnexpectedElementError.new("closing element name '#{name}' does not match with opening element '#{lastframe.name}'") end decode_tag_end(lastframe.ns, lastframe.node) @lastnode = lastframe.node end private def decode_tag(ns, name, attrs, parent) o = nil elename = ns.parse(name) if !parent if elename == SchemaName o = Schema.parse_element(elename) o.location = @location else raise UnknownElementError.new("unknown element: #{elename}") end o.root = @originalroot if @originalroot # o.root = o otherwise else if elename == AnnotationName # only the first annotation element is allowed for each element. o = Annotation.new else o = parent.parse_element(elename) end unless o unless @ignored.key?(elename) warn("ignored element: #{elename} of #{parent.class}") @ignored[elename] = elename end o = Documentation.new # which accepts any element. end # node could be a pseudo element. pseudo element has its own parent. o.root = parent.root o.parent = parent if o.parent.nil? end attrs.each do |key, value| attr_ele = ns.parse(key, true) value_ele = ns.parse(value, true) value_ele.source = value # for recovery; value may not be a QName if attr_ele == IdAttrName o.id = value_ele else unless o.parse_attr(attr_ele, value_ele) unless @ignored.key?(attr_ele) warn("ignored attr: #{attr_ele}") @ignored[attr_ele] = attr_ele end end end end o end def decode_tag_end(ns, node) node.parse_epilogue end def decode_text(ns, text) @textbuf << text end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/enumeration.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/enumeration.rb
# WSDL4R - XMLSchema enumeration definition for WSDL. # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Enumeration < Info def initialize super end def parse_element(element) nil end def parse_attr(attr, value) case attr when ValueAttrName parent.enumeration << value.source value.source end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/sequence.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/sequence.rb
# WSDL4R - XMLSchema complexType definition for WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Sequence < Info attr_reader :minoccurs attr_reader :maxoccurs attr_reader :elements def initialize super() @minoccurs = '1' @maxoccurs = '1' @elements = [] end def targetnamespace parent.targetnamespace end def elementformdefault parent.elementformdefault end def <<(element) @elements << element end def parse_element(element) case element when AnyName o = Any.new @elements << o o when ElementName o = Element.new @elements << o o else nil end end def parse_attr(attr, value) case attr when MaxOccursAttrName @maxoccurs = value.source when MinOccursAttrName @minoccurs = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/simpleExtension.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/simpleExtension.rb
# WSDL4R - XMLSchema simpleType extension definition for WSDL. # Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL module XMLSchema class SimpleExtension < Info attr_reader :base attr_reader :attributes def initialize super @base = nil @attributes = XSD::NamedElements.new end def targetnamespace parent.targetnamespace end def valid?(value) true end def parse_element(element) case element when AttributeName o = Attribute.new @attributes << o o end end def parse_attr(attr, value) case attr when BaseAttrName @base = value end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/choice.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/choice.rb
# WSDL4R - XMLSchema complexType definition for WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Choice < Info attr_reader :minoccurs attr_reader :maxoccurs attr_reader :elements def initialize super() @minoccurs = '1' @maxoccurs = '1' @elements = [] end def targetnamespace parent.targetnamespace end def elementformdefault parent.elementformdefault end def <<(element) @elements << element end def parse_element(element) case element when AnyName o = Any.new @elements << o o when ElementName o = Element.new @elements << o o else nil end end def parse_attr(attr, value) case attr when MaxOccursAttrName @maxoccurs = value.source when MinOccursAttrName @minoccurs = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/pattern.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/pattern.rb
# WSDL4R - XMLSchema pattern definition for WSDL. # Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class Pattern < Info def initialize super end def parse_element(element) nil end def parse_attr(attr, value) case attr when ValueAttrName parent.pattern = /\A#{value.source}\z/n value.source end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/import.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/import.rb
# WSDL4R - XMLSchema import definition. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'wsdl/xmlSchema/importer' module WSDL module XMLSchema class Import < Info attr_reader :namespace attr_reader :schemalocation attr_reader :content def initialize super @namespace = nil @schemalocation = nil @content = nil end def parse_element(element) nil end def parse_attr(attr, value) case attr when NamespaceAttrName @namespace = value.source when SchemaLocationAttrName @schemalocation = URI.parse(value.source) if @schemalocation.relative? and !parent.location.nil? and !parent.location.relative? @schemalocation = parent.location + @schemalocation end if root.importedschema.key?(@schemalocation) @content = root.importedschema[@schemalocation] else root.importedschema[@schemalocation] = nil # placeholder @content = import(@schemalocation) root.importedschema[@schemalocation] = @content end @schemalocation else nil end end private def import(location) Importer.import(location, root) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/simpleRestriction.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/simpleRestriction.rb
# WSDL4R - XMLSchema simpleContent restriction definition for WSDL. # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL module XMLSchema class SimpleRestriction < Info attr_reader :base attr_reader :enumeration attr_accessor :length attr_accessor :pattern def initialize super @base = nil @enumeration = [] # NamedElements? @length = nil @pattern = nil end def valid?(value) return false unless check_restriction(value) return false unless check_length(value) return false unless check_pattern(value) true end def parse_element(element) case element when EnumerationName Enumeration.new # just a parsing handler when LengthName Length.new # just a parsing handler when PatternName Pattern.new # just a parsing handler end end def parse_attr(attr, value) case attr when BaseAttrName @base = value end end private def check_restriction(value) @enumeration.empty? or @enumeration.include?(value) end def check_length(value) @length.nil? or value.size == @length end def check_pattern(value) @pattern.nil? or @pattern =~ value end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/importer.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/importer.rb
# WSDL4R - XSD importer library. # Copyright (C) 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'soap/httpconfigloader' require 'wsdl/xmlSchema/parser' module WSDL module XMLSchema class Importer def self.import(location, originalroot = nil) new.import(location, originalroot) end def initialize @web_client = nil end def import(location, originalroot = nil) unless location.is_a?(URI) location = URI.parse(location) end content = parse(fetch(location), location, originalroot) content.location = location content end private def parse(content, location, originalroot) opt = { :location => location, :originalroot => originalroot } WSDL::XMLSchema::Parser.new(opt).parse(content) end def fetch(location) warn("importing: #{location}") if $DEBUG content = nil if location.scheme == 'file' or (location.relative? and FileTest.exist?(location.path)) content = File.open(location.path).read elsif location.scheme and location.scheme.size == 1 and FileTest.exist?(location.to_s) # ToDo: remove this ugly workaround for a path with drive letter # (D://foo/bar) content = File.open(location.to_s).read else client = web_client.new(nil, "WSDL4R") client.proxy = ::SOAP::Env::HTTP_PROXY client.no_proxy = ::SOAP::Env::NO_PROXY if opt = ::SOAP::Property.loadproperty(::SOAP::PropertyName) ::SOAP::HTTPConfigLoader.set_options(client, opt["client.protocol.http"]) end content = client.get_content(location) end content end def web_client @web_client ||= begin require 'http-access2' if HTTPAccess2::VERSION < "2.0" raise LoadError.new("http-access/2.0 or later is required.") end HTTPAccess2::Client rescue LoadError warn("Loading http-access2 failed. Net/http is used.") if $DEBUG require 'soap/netHttpClient' ::SOAP::NetHttpClient end @web_client end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/complexContent.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/complexContent.rb
# WSDL4R - XMLSchema complexContent definition for WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL module XMLSchema class ComplexContent < Info attr_accessor :base attr_reader :derivetype attr_reader :content attr_reader :attributes def initialize super @base = nil @derivetype = nil @content = nil @attributes = XSD::NamedElements.new @basetype = nil end def targetnamespace parent.targetnamespace end def elementformdefault parent.elementformdefault end def basetype @basetype ||= root.collect_complextypes[@base] end def parse_element(element) case element when RestrictionName, ExtensionName @derivetype = element.name self when AllName if @derivetype.nil? raise Parser::ElementConstraintError.new("base attr not found.") end @content = All.new @content when SequenceName if @derivetype.nil? raise Parser::ElementConstraintError.new("base attr not found.") end @content = Sequence.new @content when ChoiceName if @derivetype.nil? raise Parser::ElementConstraintError.new("base attr not found.") end @content = Choice.new @content when AttributeName if @derivetype.nil? raise Parser::ElementConstraintError.new("base attr not found.") end o = Attribute.new @attributes << o o end end def parse_attr(attr, value) if @derivetype.nil? return nil end case attr when BaseAttrName @base = value else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/schema.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/schema.rb
# WSDL4R - XMLSchema schema definition for WSDL. # Copyright (C) 2002, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL module XMLSchema class Schema < Info attr_reader :targetnamespace # required attr_reader :complextypes attr_reader :simpletypes attr_reader :elements attr_reader :attributes attr_reader :imports attr_accessor :attributeformdefault attr_accessor :elementformdefault attr_reader :importedschema def initialize super @targetnamespace = nil @complextypes = XSD::NamedElements.new @simpletypes = XSD::NamedElements.new @elements = XSD::NamedElements.new @attributes = XSD::NamedElements.new @imports = [] @attributeformdefault = "unqualified" @elementformdefault = "unqualified" @importedschema = {} @location = nil @root = self end def location @location || (root.nil? ? nil : root.location) end def location=(location) @location = location end def parse_element(element) case element when ImportName o = Import.new @imports << o o when IncludeName o = Include.new @imports << o o when ComplexTypeName o = ComplexType.new @complextypes << o o when SimpleTypeName o = SimpleType.new @simpletypes << o o when ElementName o = Element.new @elements << o o when AttributeName o = Attribute.new @attributes << o o else nil end end def parse_attr(attr, value) case attr when TargetNamespaceAttrName @targetnamespace = value.source when AttributeFormDefaultAttrName @attributeformdefault = value.source when ElementFormDefaultAttrName @elementformdefault = value.source else nil end end def collect_attributes result = XSD::NamedElements.new result.concat(@attributes) @imports.each do |import| result.concat(import.content.collect_attributes) if import.content end result end def collect_elements result = XSD::NamedElements.new result.concat(@elements) @imports.each do |import| result.concat(import.content.collect_elements) if import.content end result end def collect_complextypes result = XSD::NamedElements.new result.concat(@complextypes) @imports.each do |import| result.concat(import.content.collect_complextypes) if import.content end result end def collect_simpletypes result = XSD::NamedElements.new result.concat(@simpletypes) @imports.each do |import| result.concat(import.content.collect_simpletypes) if import.content end result end def self.parse_element(element) if element == SchemaName Schema.new else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/simpleContent.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/simpleContent.rb
# WSDL4R - XMLSchema simpleContent definition for WSDL. # Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL module XMLSchema class SimpleContent < Info attr_reader :restriction attr_reader :extension def check_lexical_format(value) check(value) end def initialize super @restriction = nil @extension = nil end def base content.base end def targetnamespace parent.targetnamespace end def parse_element(element) case element when RestrictionName @restriction = SimpleRestriction.new @restriction when ExtensionName @extension = SimpleExtension.new @extension end end private def content @restriction || @extension end def check(value) unless content.valid?(value) raise XSD::ValueSpaceError.new("#{@name}: cannot accept '#{value}'") end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/all.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/xmlSchema/all.rb
# WSDL4R - XMLSchema complexType definition for WSDL. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL module XMLSchema class All < Info attr_reader :minoccurs attr_reader :maxoccurs attr_reader :elements def initialize super() @minoccurs = '1' @maxoccurs = '1' @elements = [] end def targetnamespace parent.targetnamespace end def elementformdefault parent.elementformdefault end def <<(element) @elements << element end def parse_element(element) case element when AnyName o = Any.new @elements << o o when ElementName o = Element.new @elements << o o else nil end end def parse_attr(attr, value) case attr when MaxOccursAttrName @maxoccurs = value.source when MinOccursAttrName @minoccurs = value.source else nil end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri/generic.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri/generic.rb
# # = uri/generic.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: generic.rb 16085 2008-04-19 11:56:22Z knu $ # require 'uri/common' module URI # # Base class for all URI classes. # Implements generic URI syntax as per RFC 2396. # class Generic include URI include REGEXP DEFAULT_PORT = nil # # Returns default port # def self.default_port self::DEFAULT_PORT end def default_port self.class.default_port end COMPONENT = [ :scheme, :userinfo, :host, :port, :registry, :path, :opaque, :query, :fragment ].freeze # # Components of the URI in the order. # def self.component self::COMPONENT end USE_REGISTRY = false # # DOC: FIXME! # def self.use_registry self::USE_REGISTRY end # # == Synopsis # # See #new # # == Description # # At first, tries to create a new URI::Generic instance using # URI::Generic::build. But, if exception URI::InvalidComponentError is raised, # then it URI::Escape.escape all URI components and tries again. # # def self.build2(args) begin return self.build(args) rescue InvalidComponentError if args.kind_of?(Array) return self.build(args.collect{|x| if x URI.escape(x) else x end }) elsif args.kind_of?(Hash) tmp = {} args.each do |key, value| tmp[key] = if value URI.escape(value) else value end end return self.build(tmp) end end end # # == Synopsis # # See #new # # == Description # # Creates a new URI::Generic instance from components of URI::Generic # with check. Components are: scheme, userinfo, host, port, registry, path, # opaque, query and fragment. You can provide arguments either by an Array or a Hash. # See #new for hash keys to use or for order of array items. # def self.build(args) if args.kind_of?(Array) && args.size == ::URI::Generic::COMPONENT.size tmp = args elsif args.kind_of?(Hash) tmp = ::URI::Generic::COMPONENT.collect do |c| if args.include?(c) args[c] else nil end end else raise ArgumentError, "expected Array of or Hash of components of #{self.class} (#{self.class.component.join(', ')})" end tmp << true return self.new(*tmp) end # # == Args # # +scheme+:: # Protocol scheme, i.e. 'http','ftp','mailto' and so on. # +userinfo+:: # User name and password, i.e. 'sdmitry:bla' # +host+:: # Server host name # +port+:: # Server port # +registry+:: # DOC: FIXME! # +path+:: # Path on server # +opaque+:: # DOC: FIXME! # +query+:: # Query data # +fragment+:: # A part of URI after '#' sign # +arg_check+:: # Check arguments [false by default] # # == Description # # Creates a new URI::Generic instance from ``generic'' components without check. # def initialize(scheme, userinfo, host, port, registry, path, opaque, query, fragment, arg_check = false) @scheme = nil @user = nil @password = nil @host = nil @port = nil @path = nil @query = nil @opaque = nil @registry = nil @fragment = nil if arg_check self.scheme = scheme self.userinfo = userinfo self.host = host self.port = port self.path = path self.query = query self.opaque = opaque self.registry = registry self.fragment = fragment else self.set_scheme(scheme) self.set_userinfo(userinfo) self.set_host(host) self.set_port(port) self.set_path(path) self.set_query(query) self.set_opaque(opaque) self.set_registry(registry) self.set_fragment(fragment) end if @registry && !self.class.use_registry raise InvalidURIError, "the scheme #{@scheme} does not accept registry part: #{@registry} (or bad hostname?)" end @scheme.freeze if @scheme self.set_path('') if !@path && !@opaque # (see RFC2396 Section 5.2) self.set_port(self.default_port) if self.default_port && !@port end attr_reader :scheme attr_reader :host attr_reader :port attr_reader :registry attr_reader :path attr_reader :query attr_reader :opaque attr_reader :fragment # replace self by other URI object def replace!(oth) if self.class != oth.class raise ArgumentError, "expected #{self.class} object" end component.each do |c| self.__send__("#{c}=", oth.__send__(c)) end end private :replace! def component self.class.component end def check_scheme(v) if v && SCHEME !~ v raise InvalidComponentError, "bad component(expected scheme component): #{v}" end return true end private :check_scheme def set_scheme(v) @scheme = v end protected :set_scheme def scheme=(v) check_scheme(v) set_scheme(v) v end def check_userinfo(user, password = nil) if !password user, password = split_userinfo(user) end check_user(user) check_password(password, user) return true end private :check_userinfo def check_user(v) if @registry || @opaque raise InvalidURIError, "can not set user with registry or opaque" end return v unless v if USERINFO !~ v raise InvalidComponentError, "bad component(expected userinfo component or user component): #{v}" end return true end private :check_user def check_password(v, user = @user) if @registry || @opaque raise InvalidURIError, "can not set password with registry or opaque" end return v unless v if !user raise InvalidURIError, "password component depends user component" end if USERINFO !~ v raise InvalidComponentError, "bad component(expected user component): #{v}" end return true end private :check_password # # Sets userinfo, argument is string like 'name:pass' # def userinfo=(userinfo) if userinfo.nil? return nil end check_userinfo(*userinfo) set_userinfo(*userinfo) # returns userinfo end def user=(user) check_user(user) set_user(user) # returns user end def password=(password) check_password(password) set_password(password) # returns password end def set_userinfo(user, password = nil) unless password user, password = split_userinfo(user) end @user = user @password = password if password [@user, @password] end protected :set_userinfo def set_user(v) set_userinfo(v, @password) v end protected :set_user def set_password(v) @password = v # returns v end protected :set_password def split_userinfo(ui) return nil, nil unless ui user, password = ui.split(/:/, 2) return user, password end private :split_userinfo def escape_userpass(v) v = URI.escape(v, /[@:\/]/o) # RFC 1738 section 3.1 #/ end private :escape_userpass def userinfo if @user.nil? nil elsif @password.nil? @user else @user + ':' + @password end end def user @user end def password @password end def check_host(v) return v unless v if @registry || @opaque raise InvalidURIError, "can not set host with registry or opaque" elsif HOST !~ v raise InvalidComponentError, "bad component(expected host component): #{v}" end return true end private :check_host def set_host(v) @host = v end protected :set_host def host=(v) check_host(v) set_host(v) v end def check_port(v) return v unless v if @registry || @opaque raise InvalidURIError, "can not set port with registry or opaque" elsif !v.kind_of?(Fixnum) && PORT !~ v raise InvalidComponentError, "bad component(expected port component): #{v}" end return true end private :check_port def set_port(v) unless !v || v.kind_of?(Fixnum) if v.empty? v = nil else v = v.to_i end end @port = v end protected :set_port def port=(v) check_port(v) set_port(v) port end def check_registry(v) return v unless v # raise if both server and registry are not nil, because: # authority = server | reg_name # server = [ [ userinfo "@" ] hostport ] if @host || @port || @user # userinfo = @user + ':' + @password raise InvalidURIError, "can not set registry with host, port, or userinfo" elsif v && REGISTRY !~ v raise InvalidComponentError, "bad component(expected registry component): #{v}" end return true end private :check_registry def set_registry(v) @registry = v end protected :set_registry def registry=(v) check_registry(v) set_registry(v) v end def check_path(v) # raise if both hier and opaque are not nil, because: # absoluteURI = scheme ":" ( hier_part | opaque_part ) # hier_part = ( net_path | abs_path ) [ "?" query ] if v && @opaque raise InvalidURIError, "path conflicts with opaque" end if @scheme if v && v != '' && ABS_PATH !~ v raise InvalidComponentError, "bad component(expected absolute path component): #{v}" end else if v && v != '' && ABS_PATH !~ v && REL_PATH !~ v raise InvalidComponentError, "bad component(expected relative path component): #{v}" end end return true end private :check_path def set_path(v) @path = v end protected :set_path def path=(v) check_path(v) set_path(v) v end def check_query(v) return v unless v # raise if both hier and opaque are not nil, because: # absoluteURI = scheme ":" ( hier_part | opaque_part ) # hier_part = ( net_path | abs_path ) [ "?" query ] if @opaque raise InvalidURIError, "query conflicts with opaque" end if v && v != '' && QUERY !~ v raise InvalidComponentError, "bad component(expected query component): #{v}" end return true end private :check_query def set_query(v) @query = v end protected :set_query def query=(v) check_query(v) set_query(v) v end def check_opaque(v) return v unless v # raise if both hier and opaque are not nil, because: # absoluteURI = scheme ":" ( hier_part | opaque_part ) # hier_part = ( net_path | abs_path ) [ "?" query ] if @host || @port || @user || @path # userinfo = @user + ':' + @password raise InvalidURIError, "can not set opaque with host, port, userinfo or path" elsif v && OPAQUE !~ v raise InvalidComponentError, "bad component(expected opaque component): #{v}" end return true end private :check_opaque def set_opaque(v) @opaque = v end protected :set_opaque def opaque=(v) check_opaque(v) set_opaque(v) v end def check_fragment(v) return v unless v if v && v != '' && FRAGMENT !~ v raise InvalidComponentError, "bad component(expected fragment component): #{v}" end return true end private :check_fragment def set_fragment(v) @fragment = v end protected :set_fragment def fragment=(v) check_fragment(v) set_fragment(v) v end # # Checks if URI has a path # def hierarchical? if @path true else false end end # # Checks if URI is an absolute one # def absolute? if @scheme true else false end end alias absolute absolute? # # Checks if URI is relative # def relative? !absolute? end def split_path(path) path.split(%r{/+}, -1) end private :split_path def merge_path(base, rel) # RFC2396, Section 5.2, 5) # RFC2396, Section 5.2, 6) base_path = split_path(base) rel_path = split_path(rel) # RFC2396, Section 5.2, 6), a) base_path << '' if base_path.last == '..' while i = base_path.index('..') base_path.slice!(i - 1, 2) end if (first = rel_path.first) and first.empty? base_path.clear rel_path.shift end # RFC2396, Section 5.2, 6), c) # RFC2396, Section 5.2, 6), d) rel_path.push('') if rel_path.last == '.' || rel_path.last == '..' rel_path.delete('.') # RFC2396, Section 5.2, 6), e) tmp = [] rel_path.each do |x| if x == '..' && !(tmp.empty? || tmp.last == '..') tmp.pop else tmp << x end end add_trailer_slash = !tmp.empty? if base_path.empty? base_path = [''] # keep '/' for root directory elsif add_trailer_slash base_path.pop end while x = tmp.shift if x == '..' # RFC2396, Section 4 # a .. or . in an absolute path has no special meaning base_path.pop if base_path.size > 1 else # if x == '..' # valid absolute (but abnormal) path "/../..." # else # valid absolute path # end base_path << x tmp.each {|t| base_path << t} add_trailer_slash = false break end end base_path.push('') if add_trailer_slash return base_path.join('/') end private :merge_path # # == Args # # +oth+:: # URI or String # # == Description # # Destructive form of #merge # # == Usage # # require 'uri' # # uri = URI.parse("http://my.example.com") # uri.merge!("/main.rbx?page=1") # p uri # # => #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1> # def merge!(oth) t = merge(oth) if self == t nil else replace!(t) self end end # # == Args # # +oth+:: # URI or String # # == Description # # Merges two URI's. # # == Usage # # require 'uri' # # uri = URI.parse("http://my.example.com") # p uri.merge("/main.rbx?page=1") # # => #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1> # def merge(oth) begin base, rel = merge0(oth) rescue raise $!.class, $!.message end if base == rel return base end authority = rel.userinfo || rel.host || rel.port # RFC2396, Section 5.2, 2) if (rel.path.nil? || rel.path.empty?) && !authority && !rel.query base.set_fragment(rel.fragment) if rel.fragment return base end base.set_query(nil) base.set_fragment(nil) # RFC2396, Section 5.2, 4) if !authority base.set_path(merge_path(base.path, rel.path)) if base.path && rel.path else # RFC2396, Section 5.2, 4) base.set_path(rel.path) if rel.path end # RFC2396, Section 5.2, 7) base.set_userinfo(rel.userinfo) if rel.userinfo base.set_host(rel.host) if rel.host base.set_port(rel.port) if rel.port base.set_query(rel.query) if rel.query base.set_fragment(rel.fragment) if rel.fragment return base end # merge alias + merge # return base and rel. # you can modify `base', but can not `rel'. def merge0(oth) case oth when Generic when String oth = URI.parse(oth) else raise ArgumentError, "bad argument(expected URI object or URI string)" end if self.relative? && oth.relative? raise BadURIError, "both URI are relative" end if self.absolute? && oth.absolute? #raise BadURIError, # "both URI are absolute" # hmm... should return oth for usability? return oth, oth end if self.absolute? return self.dup, oth else return oth, oth end end private :merge0 def route_from_path(src, dst) # RFC2396, Section 4.2 return '' if src == dst src_path = split_path(src) dst_path = split_path(dst) # hmm... dst has abnormal absolute path, # like "/./", "/../", "/x/../", ... if dst_path.include?('..') || dst_path.include?('.') return dst.dup end src_path.pop # discard same parts while dst_path.first == src_path.first break if dst_path.empty? src_path.shift dst_path.shift end tmp = dst_path.join('/') # calculate if src_path.empty? if tmp.empty? return './' elsif dst_path.first.include?(':') # (see RFC2396 Section 5) return './' + tmp else return tmp end end return '../' * src_path.size + tmp end private :route_from_path def route_from0(oth) case oth when Generic when String oth = URI.parse(oth) else raise ArgumentError, "bad argument(expected URI object or URI string)" end if self.relative? raise BadURIError, "relative URI: #{self}" end if oth.relative? raise BadURIError, "relative URI: #{oth}" end if self.scheme != oth.scheme return self, self.dup end rel = URI::Generic.new(nil, # it is relative URI self.userinfo, self.host, self.port, self.registry, self.path, self.opaque, self.query, self.fragment) if rel.userinfo != oth.userinfo || rel.host.to_s.downcase != oth.host.to_s.downcase || rel.port != oth.port if self.userinfo.nil? && self.host.nil? return self, self.dup end rel.set_port(nil) if rel.port == oth.default_port return rel, rel end rel.set_userinfo(nil) rel.set_host(nil) rel.set_port(nil) if rel.path && rel.path == oth.path rel.set_path('') rel.set_query(nil) if rel.query == oth.query return rel, rel elsif rel.opaque && rel.opaque == oth.opaque rel.set_opaque('') rel.set_query(nil) if rel.query == oth.query return rel, rel end # you can modify `rel', but can not `oth'. return oth, rel end private :route_from0 # # == Args # # +oth+:: # URI or String # # == Description # # Calculates relative path from oth to self # # == Usage # # require 'uri' # # uri = URI.parse('http://my.example.com/main.rbx?page=1') # p uri.route_from('http://my.example.com') # #=> #<URI::Generic:0x20218858 URL:/main.rbx?page=1> # def route_from(oth) # you can modify `rel', but can not `oth'. begin oth, rel = route_from0(oth) rescue raise $!.class, $!.message end if oth == rel return rel end rel.set_path(route_from_path(oth.path, self.path)) if rel.path == './' && self.query # "./?foo" -> "?foo" rel.set_path('') end return rel end alias - route_from # # == Args # # +oth+:: # URI or String # # == Description # # Calculates relative path to oth from self # # == Usage # # require 'uri' # # uri = URI.parse('http://my.example.com') # p uri.route_to('http://my.example.com/main.rbx?page=1') # #=> #<URI::Generic:0x2020c2f6 URL:/main.rbx?page=1> # def route_to(oth) case oth when Generic when String oth = URI.parse(oth) else raise ArgumentError, "bad argument(expected URI object or URI string)" end oth.route_from(self) end # # Returns normalized URI # def normalize uri = dup uri.normalize! uri end # # Destructive version of #normalize # def normalize! if path && path == '' set_path('/') end if host && host != host.downcase set_host(self.host.downcase) end end def path_query str = @path if @query str += '?' + @query end str end private :path_query # # Constructs String from URI # def to_s str = '' if @scheme str << @scheme str << ':' end if @opaque str << @opaque else if @registry str << @registry else if @host str << '//' end if self.userinfo str << self.userinfo str << '@' end if @host str << @host end if @port && @port != self.default_port str << ':' str << @port.to_s end end str << path_query end if @fragment str << '#' str << @fragment end str end # # Compares to URI's # def ==(oth) if self.class == oth.class self.normalize.component_ary == oth.normalize.component_ary else false end end def hash self.component_ary.hash end def eql?(oth) self.component_ary.eql?(oth.component_ary) end =begin --- URI::Generic#===(oth) =end # def ===(oth) # raise NotImplementedError # end =begin =end def component_ary component.collect do |x| self.send(x) end end protected :component_ary # == Args # # +components+:: # Multiple Symbol arguments defined in URI::HTTP # # == Description # # Selects specified components from URI # # == Usage # # require 'uri' # # uri = URI.parse('http://myuser:mypass@my.example.com/test.rbx') # p uri.select(:userinfo, :host, :path) # # => ["myuser:mypass", "my.example.com", "/test.rbx"] # def select(*components) components.collect do |c| if component.include?(c) self.send(c) else raise ArgumentError, "expected of components of #{self.class} (#{self.class.component.join(', ')})" end end end @@to_s = Kernel.instance_method(:to_s) def inspect @@to_s.bind(self).call.sub!(/>\z/) {" URL:#{self}>"} end def coerce(oth) case oth when String oth = URI.parse(oth) else super end return oth, self end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri/common.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri/common.rb
# = uri/common.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # Revision:: $Id: common.rb 14178 2007-12-10 09:31:55Z matz $ # License:: # You can redistribute it and/or modify it under the same term as Ruby. # module URI module REGEXP # # Patterns used to parse URI's # module PATTERN # :stopdoc: # RFC 2396 (URI Generic Syntax) # RFC 2732 (IPv6 Literal Addresses in URL's) # RFC 2373 (IPv6 Addressing Architecture) # alpha = lowalpha | upalpha ALPHA = "a-zA-Z" # alphanum = alpha | digit ALNUM = "#{ALPHA}\\d" # hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | # "a" | "b" | "c" | "d" | "e" | "f" HEX = "a-fA-F\\d" # escaped = "%" hex hex ESCAPED = "%[#{HEX}]{2}" # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | # "(" | ")" # unreserved = alphanum | mark UNRESERVED = "-_.!~*'()#{ALNUM}" # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | # "$" | "," # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | # "$" | "," | "[" | "]" (RFC 2732) RESERVED = ";/?:@&=+$,\\[\\]" # uric = reserved | unreserved | escaped URIC = "(?:[#{UNRESERVED}#{RESERVED}]|#{ESCAPED})" # uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" | # "&" | "=" | "+" | "$" | "," URIC_NO_SLASH = "(?:[#{UNRESERVED};?:@&=+$,]|#{ESCAPED})" # query = *uric QUERY = "#{URIC}*" # fragment = *uric FRAGMENT = "#{URIC}*" # domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum DOMLABEL = "(?:[#{ALNUM}](?:[-#{ALNUM}]*[#{ALNUM}])?)" # toplabel = alpha | alpha *( alphanum | "-" ) alphanum TOPLABEL = "(?:[#{ALPHA}](?:[-#{ALNUM}]*[#{ALNUM}])?)" # hostname = *( domainlabel "." ) toplabel [ "." ] HOSTNAME = "(?:#{DOMLABEL}\\.)*#{TOPLABEL}\\.?" # RFC 2373, APPENDIX B: # IPv6address = hexpart [ ":" IPv4address ] # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT # hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ] # hexseq = hex4 *( ":" hex4) # hex4 = 1*4HEXDIG # # XXX: This definition has a flaw. "::" + IPv4address must be # allowed too. Here is a replacement. # # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT IPV4ADDR = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" # hex4 = 1*4HEXDIG HEX4 = "[#{HEX}]{1,4}" # lastpart = hex4 | IPv4address LASTPART = "(?:#{HEX4}|#{IPV4ADDR})" # hexseq1 = *( hex4 ":" ) hex4 HEXSEQ1 = "(?:#{HEX4}:)*#{HEX4}" # hexseq2 = *( hex4 ":" ) lastpart HEXSEQ2 = "(?:#{HEX4}:)*#{LASTPART}" # IPv6address = hexseq2 | [ hexseq1 ] "::" [ hexseq2 ] IPV6ADDR = "(?:#{HEXSEQ2}|(?:#{HEXSEQ1})?::(?:#{HEXSEQ2})?)" # IPv6prefix = ( hexseq1 | [ hexseq1 ] "::" [ hexseq1 ] ) "/" 1*2DIGIT # unused # ipv6reference = "[" IPv6address "]" (RFC 2732) IPV6REF = "\\[#{IPV6ADDR}\\]" # host = hostname | IPv4address # host = hostname | IPv4address | IPv6reference (RFC 2732) HOST = "(?:#{HOSTNAME}|#{IPV4ADDR}|#{IPV6REF})" # port = *digit PORT = '\d*' # hostport = host [ ":" port ] HOSTPORT = "#{HOST}(?::#{PORT})?" # userinfo = *( unreserved | escaped | # ";" | ":" | "&" | "=" | "+" | "$" | "," ) USERINFO = "(?:[#{UNRESERVED};:&=+$,]|#{ESCAPED})*" # pchar = unreserved | escaped | # ":" | "@" | "&" | "=" | "+" | "$" | "," PCHAR = "(?:[#{UNRESERVED}:@&=+$,]|#{ESCAPED})" # param = *pchar PARAM = "#{PCHAR}*" # segment = *pchar *( ";" param ) SEGMENT = "#{PCHAR}*(?:;#{PARAM})*" # path_segments = segment *( "/" segment ) PATH_SEGMENTS = "#{SEGMENT}(?:/#{SEGMENT})*" # server = [ [ userinfo "@" ] hostport ] SERVER = "(?:#{USERINFO}@)?#{HOSTPORT}" # reg_name = 1*( unreserved | escaped | "$" | "," | # ";" | ":" | "@" | "&" | "=" | "+" ) REG_NAME = "(?:[#{UNRESERVED}$,;:@&=+]|#{ESCAPED})+" # authority = server | reg_name AUTHORITY = "(?:#{SERVER}|#{REG_NAME})" # rel_segment = 1*( unreserved | escaped | # ";" | "@" | "&" | "=" | "+" | "$" | "," ) REL_SEGMENT = "(?:[#{UNRESERVED};@&=+$,]|#{ESCAPED})+" # scheme = alpha *( alpha | digit | "+" | "-" | "." ) SCHEME = "[#{ALPHA}][-+.#{ALPHA}\\d]*" # abs_path = "/" path_segments ABS_PATH = "/#{PATH_SEGMENTS}" # rel_path = rel_segment [ abs_path ] REL_PATH = "#{REL_SEGMENT}(?:#{ABS_PATH})?" # net_path = "//" authority [ abs_path ] NET_PATH = "//#{AUTHORITY}(?:#{ABS_PATH})?" # hier_part = ( net_path | abs_path ) [ "?" query ] HIER_PART = "(?:#{NET_PATH}|#{ABS_PATH})(?:\\?(?:#{QUERY}))?" # opaque_part = uric_no_slash *uric OPAQUE_PART = "#{URIC_NO_SLASH}#{URIC}*" # absoluteURI = scheme ":" ( hier_part | opaque_part ) ABS_URI = "#{SCHEME}:(?:#{HIER_PART}|#{OPAQUE_PART})" # relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] REL_URI = "(?:#{NET_PATH}|#{ABS_PATH}|#{REL_PATH})(?:\\?#{QUERY})?" # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] URI_REF = "(?:#{ABS_URI}|#{REL_URI})?(?:##{FRAGMENT})?" # XXX: X_ABS_URI = " (#{PATTERN::SCHEME}): (?# 1: scheme) (?: (#{PATTERN::OPAQUE_PART}) (?# 2: opaque) | (?:(?: //(?: (?:(?:(#{PATTERN::USERINFO})@)? (?# 3: userinfo) (?:(#{PATTERN::HOST})(?::(\\d*))?))?(?# 4: host, 5: port) | (#{PATTERN::REG_NAME}) (?# 6: registry) ) | (?!//)) (?# XXX: '//' is the mark for hostport) (#{PATTERN::ABS_PATH})? (?# 7: path) )(?:\\?(#{PATTERN::QUERY}))? (?# 8: query) ) (?:\\#(#{PATTERN::FRAGMENT}))? (?# 9: fragment) " X_REL_URI = " (?: (?: // (?: (?:(#{PATTERN::USERINFO})@)? (?# 1: userinfo) (#{PATTERN::HOST})?(?::(\\d*))? (?# 2: host, 3: port) | (#{PATTERN::REG_NAME}) (?# 4: registry) ) ) | (#{PATTERN::REL_SEGMENT}) (?# 5: rel_segment) )? (#{PATTERN::ABS_PATH})? (?# 6: abs_path) (?:\\?(#{PATTERN::QUERY}))? (?# 7: query) (?:\\#(#{PATTERN::FRAGMENT}))? (?# 8: fragment) " # :startdoc: end # PATTERN # :stopdoc: # for URI::split ABS_URI = Regexp.new('^' + PATTERN::X_ABS_URI + '$', #' Regexp::EXTENDED, 'N').freeze REL_URI = Regexp.new('^' + PATTERN::X_REL_URI + '$', #' Regexp::EXTENDED, 'N').freeze # for URI::extract URI_REF = Regexp.new(PATTERN::URI_REF, false, 'N').freeze ABS_URI_REF = Regexp.new(PATTERN::X_ABS_URI, Regexp::EXTENDED, 'N').freeze REL_URI_REF = Regexp.new(PATTERN::X_REL_URI, Regexp::EXTENDED, 'N').freeze # for URI::escape/unescape ESCAPED = Regexp.new(PATTERN::ESCAPED, false, 'N').freeze UNSAFE = Regexp.new("[^#{PATTERN::UNRESERVED}#{PATTERN::RESERVED}]", false, 'N').freeze # for Generic#initialize SCHEME = Regexp.new("^#{PATTERN::SCHEME}$", false, 'N').freeze #" USERINFO = Regexp.new("^#{PATTERN::USERINFO}$", false, 'N').freeze #" HOST = Regexp.new("^#{PATTERN::HOST}$", false, 'N').freeze #" PORT = Regexp.new("^#{PATTERN::PORT}$", false, 'N').freeze #" OPAQUE = Regexp.new("^#{PATTERN::OPAQUE_PART}$", false, 'N').freeze #" REGISTRY = Regexp.new("^#{PATTERN::REG_NAME}$", false, 'N').freeze #" ABS_PATH = Regexp.new("^#{PATTERN::ABS_PATH}$", false, 'N').freeze #" REL_PATH = Regexp.new("^#{PATTERN::REL_PATH}$", false, 'N').freeze #" QUERY = Regexp.new("^#{PATTERN::QUERY}$", false, 'N').freeze #" FRAGMENT = Regexp.new("^#{PATTERN::FRAGMENT}$", false, 'N').freeze #" # :startdoc: end # REGEXP module Util # :nodoc: def make_components_hash(klass, array_hash) tmp = {} if array_hash.kind_of?(Array) && array_hash.size == klass.component.size - 1 klass.component[1..-1].each_index do |i| begin tmp[klass.component[i + 1]] = array_hash[i].clone rescue TypeError tmp[klass.component[i + 1]] = array_hash[i] end end elsif array_hash.kind_of?(Hash) array_hash.each do |key, value| begin tmp[key] = value.clone rescue TypeError tmp[key] = value end end else raise ArgumentError, "expected Array of or Hash of components of #{klass.to_s} (#{klass.component[1..-1].join(', ')})" end tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase return tmp end module_function :make_components_hash end module Escape include REGEXP # # == Synopsis # # URI.escape(str [, unsafe]) # # == Args # # +str+:: # String to replaces in. # +unsafe+:: # Regexp that matches all symbols that must be replaced with codes. # By default uses <tt>REGEXP::UNSAFE</tt>. # When this argument is a String, it represents a character set. # # == Description # # Escapes the string, replacing all unsafe characters with codes. # # == Usage # # require 'uri' # # enc_uri = URI.escape("http://example.com/?a=\11\15") # p enc_uri # # => "http://example.com/?a=%09%0D" # # p URI.unescape(enc_uri) # # => "http://example.com/?a=\t\r" # # p URI.escape("@?@!", "!?") # # => "@%3F@%21" # def escape(str, unsafe = UNSAFE) unless unsafe.kind_of?(Regexp) # perhaps unsafe is String object unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false, 'N') end str.gsub(unsafe) do |us| tmp = '' us.each_byte do |uc| tmp << sprintf('%%%02X', uc) end tmp end end alias encode escape # # == Synopsis # # URI.unescape(str) # # == Args # # +str+:: # Unescapes the string. # # == Usage # # require 'uri' # # enc_uri = URI.escape("http://example.com/?a=\11\15") # p enc_uri # # => "http://example.com/?a=%09%0D" # # p URI.unescape(enc_uri) # # => "http://example.com/?a=\t\r" # def unescape(str) str.gsub(ESCAPED) do $&[1,2].hex.chr end end alias decode unescape end include REGEXP extend Escape @@schemes = {} # # Base class for all URI exceptions. # class Error < StandardError; end # # Not a URI. # class InvalidURIError < Error; end # # Not a URI component. # class InvalidComponentError < Error; end # # URI is valid, bad usage is not. # class BadURIError < Error; end # # == Synopsis # # URI::split(uri) # # == Args # # +uri+:: # String with URI. # # == Description # # Splits the string on following parts and returns array with result: # # * Scheme # * Userinfo # * Host # * Port # * Registry # * Path # * Opaque # * Query # * Fragment # # == Usage # # require 'uri' # # p URI.split("http://www.ruby-lang.org/") # # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil] # def self.split(uri) case uri when '' # null uri when ABS_URI scheme, opaque, userinfo, host, port, registry, path, query, fragment = $~[1..-1] # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] # absoluteURI = scheme ":" ( hier_part | opaque_part ) # hier_part = ( net_path | abs_path ) [ "?" query ] # opaque_part = uric_no_slash *uric # abs_path = "/" path_segments # net_path = "//" authority [ abs_path ] # authority = server | reg_name # server = [ [ userinfo "@" ] hostport ] if !scheme raise InvalidURIError, "bad URI(absolute but no scheme): #{uri}" end if !opaque && (!path && (!host && !registry)) raise InvalidURIError, "bad URI(absolute but no path): #{uri}" end when REL_URI scheme = nil opaque = nil userinfo, host, port, registry, rel_segment, abs_path, query, fragment = $~[1..-1] if rel_segment && abs_path path = rel_segment + abs_path elsif rel_segment path = rel_segment elsif abs_path path = abs_path end # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] # relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] # net_path = "//" authority [ abs_path ] # abs_path = "/" path_segments # rel_path = rel_segment [ abs_path ] # authority = server | reg_name # server = [ [ userinfo "@" ] hostport ] else raise InvalidURIError, "bad URI(is not URI?): #{uri}" end path = '' if !path && !opaque # (see RFC2396 Section 5.2) ret = [ scheme, userinfo, host, port, # X registry, # X path, # Y opaque, # Y query, fragment ] return ret end # # == Synopsis # # URI::parse(uri_str) # # == Args # # +uri_str+:: # String with URI. # # == Description # # Creates one of the URI's subclasses instance from the string. # # == Raises # # URI::InvalidURIError # Raised if URI given is not a correct one. # # == Usage # # require 'uri' # # uri = URI.parse("http://www.ruby-lang.org/") # p uri # # => #<URI::HTTP:0x202281be URL:http://www.ruby-lang.org/> # p uri.scheme # # => "http" # p uri.host # # => "www.ruby-lang.org" # def self.parse(uri) scheme, userinfo, host, port, registry, path, opaque, query, fragment = self.split(uri) if scheme && @@schemes.include?(scheme.upcase) @@schemes[scheme.upcase].new(scheme, userinfo, host, port, registry, path, opaque, query, fragment) else Generic.new(scheme, userinfo, host, port, registry, path, opaque, query, fragment) end end # # == Synopsis # # URI::join(str[, str, ...]) # # == Args # # +str+:: # String(s) to work with # # == Description # # Joins URIs. # # == Usage # # require 'uri' # # p URI.join("http://localhost/","main.rbx") # # => #<URI::HTTP:0x2022ac02 URL:http://localhost/main.rbx> # def self.join(*str) u = self.parse(str[0]) str[1 .. -1].each do |x| u = u.merge(x) end u end # # == Synopsis # # URI::extract(str[, schemes][,&blk]) # # == Args # # +str+:: # String to extract URIs from. # +schemes+:: # Limit URI matching to a specific schemes. # # == Description # # Extracts URIs from a string. If block given, iterates through all matched URIs. # Returns nil if block given or array with matches. # # == Usage # # require "uri" # # URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.") # # => ["http://foo.example.com/bla", "mailto:test@example.com"] # def self.extract(str, schemes = nil, &block) if block_given? str.scan(regexp(schemes)) { yield $& } nil else result = [] str.scan(regexp(schemes)) { result.push $& } result end end # # == Synopsis # # URI::regexp([match_schemes]) # # == Args # # +match_schemes+:: # Array of schemes. If given, resulting regexp matches to URIs # whose scheme is one of the match_schemes. # # == Description # Returns a Regexp object which matches to URI-like strings. # The Regexp object returned by this method includes arbitrary # number of capture group (parentheses). Never rely on it's number. # # == Usage # # require 'uri' # # # extract first URI from html_string # html_string.slice(URI.regexp) # # # remove ftp URIs # html_string.sub(URI.regexp(['ftp']) # # # You should not rely on the number of parentheses # html_string.scan(URI.regexp) do |*matches| # p $& # end # def self.regexp(schemes = nil) unless schemes ABS_URI_REF else /(?=#{Regexp.union(*schemes)}:)#{PATTERN::X_ABS_URI}/xn end end end module Kernel # alias for URI.parse. # # This method is introduced at 1.8.2. def URI(uri_str) # :doc: URI.parse(uri_str) end module_function :URI end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri/mailto.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri/mailto.rb
# # = uri/mailto.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: mailto.rb 11747 2007-02-15 02:41:45Z knu $ # require 'uri/generic' module URI # # RFC2368, The mailto URL scheme # class MailTo < Generic include REGEXP DEFAULT_PORT = nil COMPONENT = [ :scheme, :to, :headers ].freeze # :stopdoc: # "hname" and "hvalue" are encodings of an RFC 822 header name and # value, respectively. As with "to", all URL reserved characters must # be encoded. # # "#mailbox" is as specified in RFC 822 [RFC822]. This means that it # consists of zero or more comma-separated mail addresses, possibly # including "phrase" and "comment" components. Note that all URL # reserved characters in "to" must be encoded: in particular, # parentheses, commas, and the percent sign ("%"), which commonly occur # in the "mailbox" syntax. # # Within mailto URLs, the characters "?", "=", "&" are reserved. # hname = *urlc # hvalue = *urlc # header = hname "=" hvalue HEADER_PATTERN = "(?:[^?=&]*=[^?=&]*)".freeze HEADER_REGEXP = Regexp.new(HEADER_PATTERN, 'N').freeze # headers = "?" header *( "&" header ) # to = #mailbox # mailtoURL = "mailto:" [ to ] [ headers ] MAILBOX_PATTERN = "(?:#{PATTERN::ESCAPED}|[^(),%?=&])".freeze MAILTO_REGEXP = Regexp.new(" # :nodoc: \\A (#{MAILBOX_PATTERN}*?) (?# 1: to) (?: \\? (#{HEADER_PATTERN}(?:\\&#{HEADER_PATTERN})*) (?# 2: headers) )? (?: \\# (#{PATTERN::FRAGMENT}) (?# 3: fragment) )? \\z ", Regexp::EXTENDED, 'N').freeze # :startdoc: # # == Description # # Creates a new URI::MailTo object from components, with syntax checking. # # Components can be provided as an Array or Hash. If an Array is used, # the components must be supplied as [to, headers]. # # If a Hash is used, the keys are the component names preceded by colons. # # The headers can be supplied as a pre-encoded string, such as # "subject=subscribe&cc=address", or as an Array of Arrays like # [['subject', 'subscribe'], ['cc', 'address']] # # Examples: # # require 'uri' # # m1 = URI::MailTo.build(['joe@example.com', 'subject=Ruby']) # puts m1.to_s -> mailto:joe@example.com?subject=Ruby # # m2 = URI::MailTo.build(['john@example.com', [['Subject', 'Ruby'], ['Cc', 'jack@example.com']]]) # puts m2.to_s -> mailto:john@example.com?Subject=Ruby&Cc=jack@example.com # # m3 = URI::MailTo.build({:to => 'listman@example.com', :headers => [['subject', 'subscribe']]}) # puts m3.to_s -> mailto:listman@example.com?subject=subscribe # def self.build(args) tmp = Util::make_components_hash(self, args) if tmp[:to] tmp[:opaque] = tmp[:to] else tmp[:opaque] = '' end if tmp[:headers] tmp[:opaque] << '?' if tmp[:headers].kind_of?(Array) tmp[:opaque] << tmp[:headers].collect { |x| if x.kind_of?(Array) x[0] + '=' + x[1..-1].to_s else x.to_s end }.join('&') elsif tmp[:headers].kind_of?(Hash) tmp[:opaque] << tmp[:headers].collect { |h,v| h + '=' + v }.join('&') else tmp[:opaque] << tmp[:headers].to_s end end return super(tmp) end # # == Description # # Creates a new URI::MailTo object from generic URL components with # no syntax checking. # # This method is usually called from URI::parse, which checks # the validity of each component. # def initialize(*arg) super(*arg) @to = nil @headers = [] if MAILTO_REGEXP =~ @opaque if arg[-1] self.to = $1 self.headers = $2 else set_to($1) set_headers($2) end else raise InvalidComponentError, "unrecognised opaque part for mailtoURL: #{@opaque}" end end # The primary e-mail address of the URL, as a String attr_reader :to # E-mail headers set by the URL, as an Array of Arrays attr_reader :headers def check_to(v) return true unless v return true if v.size == 0 if OPAQUE !~ v || /\A#{MAILBOX_PATTERN}*\z/o !~ v raise InvalidComponentError, "bad component(expected opaque component): #{v}" end return true end private :check_to def set_to(v) @to = v end protected :set_to def to=(v) check_to(v) set_to(v) v end def check_headers(v) return true unless v return true if v.size == 0 if OPAQUE !~ v || /\A(#{HEADER_PATTERN}(?:\&#{HEADER_PATTERN})*)\z/o !~ v raise InvalidComponentError, "bad component(expected opaque component): #{v}" end return true end private :check_headers def set_headers(v) @headers = [] if v v.scan(HEADER_REGEXP) do |x| @headers << x.split(/=/o, 2) end end end protected :set_headers def headers=(v) check_headers(v) set_headers(v) v end def to_s @scheme + ':' + if @to @to else '' end + if @headers.size > 0 '?' + @headers.collect{|x| x.join('=')}.join('&') else '' end + if @fragment '#' + @fragment else '' end end # Returns the RFC822 e-mail text equivalent of the URL, as a String. # # Example: # # require 'uri' # # uri = URI.parse("mailto:ruby-list@ruby-lang.org?Subject=subscribe&cc=myaddr") # uri.to_mailtext # # => "To: ruby-list@ruby-lang.org\nSubject: subscribe\nCc: myaddr\n\n\n" # def to_mailtext to = URI::unescape(@to) head = '' body = '' @headers.each do |x| case x[0] when 'body' body = URI::unescape(x[1]) when 'to' to << ', ' + URI::unescape(x[1]) else head << URI::unescape(x[0]).capitalize + ': ' + URI::unescape(x[1]) + "\n" end end return "To: #{to} #{head} #{body} " end alias to_rfc822text to_mailtext end @@schemes['MAILTO'] = MailTo end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri/ldaps.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri/ldaps.rb
require 'uri/ldap' module URI # The default port for LDAPS URIs is 636, and the scheme is 'ldaps:' rather # than 'ldap:'. Other than that, LDAPS URIs are identical to LDAP URIs; # see URI::LDAP. class LDAPS < LDAP DEFAULT_PORT = 636 end @@schemes['LDAPS'] = LDAPS end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri/http.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri/http.rb
# # = uri/http.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: http.rb 11747 2007-02-15 02:41:45Z knu $ # require 'uri/generic' module URI # # The syntax of HTTP URIs is defined in RFC1738 section 3.3. # # Note that the Ruby URI library allows HTTP URLs containing usernames and # passwords. This is not legal as per the RFC, but used to be # supported in Internet Explorer 5 and 6, before the MS04-004 security # update. See <URL:http://support.microsoft.com/kb/834489>. # class HTTP < Generic DEFAULT_PORT = 80 COMPONENT = [ :scheme, :userinfo, :host, :port, :path, :query, :fragment ].freeze # # == Description # # Create a new URI::HTTP object from components, with syntax checking. # # The components accepted are userinfo, host, port, path, query and # fragment. # # The components should be provided either as an Array, or as a Hash # with keys formed by preceding the component names with a colon. # # If an Array is used, the components must be passed in the order # [userinfo, host, port, path, query, fragment]. # # Example: # # newuri = URI::HTTP.build({:host => 'www.example.com', # :path> => '/foo/bar'}) # # newuri = URI::HTTP.build([nil, "www.example.com", nil, "/path", # "query", 'fragment']) # # Currently, if passed userinfo components this method generates # invalid HTTP URIs as per RFC 1738. # def self.build(args) tmp = Util::make_components_hash(self, args) return super(tmp) end # # == Description # # Create a new URI::HTTP object from generic URI components as per # RFC 2396. No HTTP-specific syntax checking (as per RFC 1738) is # performed. # # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+, # +opaque+, +query+ and +fragment+, in that order. # # Example: # # uri = URI::HTTP.new(['http', nil, "www.example.com", nil, "/path", # "query", 'fragment']) # def initialize(*arg) super(*arg) end # # == Description # # Returns the full path for an HTTP request, as required by Net::HTTP::Get. # # If the URI contains a query, the full path is URI#path + '?' + URI#query. # Otherwise, the path is simply URI#path. # def request_uri r = path_query if r[0] != ?/ r = '/' + r end r end end @@schemes['HTTP'] = HTTP end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri/ftp.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri/ftp.rb
# # = uri/ftp.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: ftp.rb 16085 2008-04-19 11:56:22Z knu $ # require 'uri/generic' module URI # # FTP URI syntax is defined by RFC1738 section 3.2. # class FTP < Generic DEFAULT_PORT = 21 COMPONENT = [ :scheme, :userinfo, :host, :port, :path, :typecode ].freeze # # Typecode is "a", "i" or "d". # # * "a" indicates a text file (the FTP command was ASCII) # * "i" indicates a binary file (FTP command IMAGE) # * "d" indicates the contents of a directory should be displayed # TYPECODE = ['a', 'i', 'd'].freeze TYPECODE_PREFIX = ';type='.freeze def self.new2(user, password, host, port, path, typecode = nil, arg_check = true) typecode = nil if typecode.size == 0 if typecode && !TYPECODE.include?(typecode) raise ArgumentError, "bad typecode is specified: #{typecode}" end # do escape self.new('ftp', [user, password], host, port, nil, typecode ? path + TYPECODE_PREFIX + typecode : path, nil, nil, nil, arg_check) end # # == Description # # Creates a new URI::FTP object from components, with syntax checking. # # The components accepted are +userinfo+, +host+, +port+, +path+ and # +typecode+. # # The components should be provided either as an Array, or as a Hash # with keys formed by preceding the component names with a colon. # # If an Array is used, the components must be passed in the order # [userinfo, host, port, path, typecode] # # If the path supplied is absolute, it will be escaped in order to # make it absolute in the URI. Examples: # # require 'uri' # # uri = URI::FTP.build(['user:password', 'ftp.example.com', nil, # '/path/file.> zip', 'i']) # puts uri.to_s -> ftp://user:password@ftp.example.com/%2Fpath/file.zip;type=a # # uri2 = URI::FTP.build({:host => 'ftp.example.com', # :path => 'ruby/src'}) # puts uri2.to_s -> ftp://ftp.example.com/ruby/src # def self.build(args) # Fix the incoming path to be generic URL syntax # FTP path -> URL path # foo/bar /foo/bar # /foo/bar /%2Ffoo/bar # if args.kind_of?(Array) args[3] = '/' + args[3].sub(/^\//, '%2F') else args[:path] = '/' + args[:path].sub(/^\//, '%2F') end tmp = Util::make_components_hash(self, args) if tmp[:typecode] if tmp[:typecode].size == 1 tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode] end tmp[:path] << tmp[:typecode] end return super(tmp) end # # == Description # # Creates a new URI::FTP object from generic URL components with no # syntax checking. # # Unlike build(), this method does not escape the path component as # required by RFC1738; instead it is treated as per RFC2396. # # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+, # +opaque+, +query+ and +fragment+, in that order. # def initialize(*arg) super(*arg) @typecode = nil tmp = @path.index(TYPECODE_PREFIX) if tmp typecode = @path[tmp + TYPECODE_PREFIX.size..-1] self.set_path(@path[0..tmp - 1]) if arg[-1] self.typecode = typecode else self.set_typecode(typecode) end end end attr_reader :typecode def check_typecode(v) if TYPECODE.include?(v) return true else raise InvalidComponentError, "bad typecode(expected #{TYPECODE.join(', ')}): #{v}" end end private :check_typecode def set_typecode(v) @typecode = v end protected :set_typecode def typecode=(typecode) check_typecode(typecode) set_typecode(typecode) typecode end def merge(oth) # :nodoc: tmp = super(oth) if self != tmp tmp.set_typecode(oth.typecode) end return tmp end # Returns the path from an FTP URI. # # RFC 1738 specifically states that the path for an FTP URI does not # include the / which separates the URI path from the URI host. Example: # # ftp://ftp.example.com/pub/ruby # # The above URI indicates that the client should connect to # ftp.example.com then cd pub/ruby from the initial login directory. # # If you want to cd to an absolute directory, you must include an # escaped / (%2F) in the path. Example: # # ftp://ftp.example.com/%2Fpub/ruby # # This method will then return "/pub/ruby" # def path return @path.sub(/^\//,'').sub(/^%2F/i,'/') end def to_s save_path = nil if @typecode save_path = @path @path = @path + TYPECODE_PREFIX + @typecode end str = super if @typecode @path = save_path end return str end end @@schemes['FTP'] = FTP end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri/ldap.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri/ldap.rb
# # = uri/ldap.rb # # Author:: # Takaaki Tateishi <ttate@jaist.ac.jp> # Akira Yamada <akira@ruby-lang.org> # License:: # URI::LDAP is copyrighted free software by Takaaki Tateishi and Akira Yamada. # You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: ldap.rb 11708 2007-02-12 23:01:19Z shyouhei $ # require 'uri/generic' module URI # # LDAP URI SCHEMA (described in RFC2255) # ldap://<host>/<dn>[?<attrs>[?<scope>[?<filter>[?<extensions>]]]] # class LDAP < Generic DEFAULT_PORT = 389 COMPONENT = [ :scheme, :host, :port, :dn, :attributes, :scope, :filter, :extensions, ].freeze SCOPE = [ SCOPE_ONE = 'one', SCOPE_SUB = 'sub', SCOPE_BASE = 'base', ].freeze def self.build(args) tmp = Util::make_components_hash(self, args) if tmp[:dn] tmp[:path] = tmp[:dn] end query = [] [:extensions, :filter, :scope, :attributes].collect do |x| next if !tmp[x] && query.size == 0 query.unshift(tmp[x]) end tmp[:query] = query.join('?') return super(tmp) end def initialize(*arg) super(*arg) if @fragment raise InvalidURIError, 'bad LDAP URL' end parse_dn parse_query end def parse_dn @dn = @path[1..-1] end private :parse_dn def parse_query @attributes = nil @scope = nil @filter = nil @extensions = nil if @query attrs, scope, filter, extensions = @query.split('?') @attributes = attrs if attrs && attrs.size > 0 @scope = scope if scope && scope.size > 0 @filter = filter if filter && filter.size > 0 @extensions = extensions if extensions && extensions.size > 0 end end private :parse_query def build_path_query @path = '/' + @dn query = [] [@extensions, @filter, @scope, @attributes].each do |x| next if !x && query.size == 0 query.unshift(x) end @query = query.join('?') end private :build_path_query def dn @dn end def set_dn(val) @dn = val build_path_query @dn end protected :set_dn def dn=(val) set_dn(val) val end def attributes @attributes end def set_attributes(val) @attributes = val build_path_query @attributes end protected :set_attributes def attributes=(val) set_attributes(val) val end def scope @scope end def set_scope(val) @scope = val build_path_query @scope end protected :set_scope def scope=(val) set_scope(val) val end def filter @filter end def set_filter(val) @filter = val build_path_query @filter end protected :set_filter def filter=(val) set_filter(val) val end def extensions @extensions end def set_extensions(val) @extensions = val build_path_query @extensions end protected :set_extensions def extensions=(val) set_extensions(val) val end def hierarchical? false end end @@schemes['LDAP'] = LDAP end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri/https.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri/https.rb
# # = uri/https.rb # # Author:: Akira Yamada <akira@ruby-lang.org> # License:: You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: https.rb 11747 2007-02-15 02:41:45Z knu $ # require 'uri/http' module URI # The default port for HTTPS URIs is 443, and the scheme is 'https:' rather # than 'http:'. Other than that, HTTPS URIs are identical to HTTP URIs; # see URI::HTTP. class HTTPS < HTTP DEFAULT_PORT = 443 end @@schemes['HTTPS'] = HTTPS end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/datatypes1999.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/datatypes1999.rb
# XSD4R - XML Schema Datatype 1999 support # Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/datatypes' module XSD Namespace.replace('http://www.w3.org/1999/XMLSchema') InstanceNamespace.replace('http://www.w3.org/1999/XMLSchema-instance') AnyTypeLiteral.replace('ur-type') AnySimpleTypeLiteral.replace('ur-type') NilLiteral.replace('null') NilValue.replace('1') DateTimeLiteral.replace('timeInstant') end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/datatypes.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/datatypes.rb
# XSD4R - XML Schema Datatype implementation. # Copyright (C) 2000, 2001, 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' require 'xsd/charset' require 'uri' ### ## XMLSchamaDatatypes general definitions. # module XSD Namespace = 'http://www.w3.org/2001/XMLSchema' InstanceNamespace = 'http://www.w3.org/2001/XMLSchema-instance' AttrType = 'type' NilValue = 'true' AnyTypeLiteral = 'anyType' AnySimpleTypeLiteral = 'anySimpleType' NilLiteral = 'nil' StringLiteral = 'string' BooleanLiteral = 'boolean' DecimalLiteral = 'decimal' FloatLiteral = 'float' DoubleLiteral = 'double' DurationLiteral = 'duration' DateTimeLiteral = 'dateTime' TimeLiteral = 'time' DateLiteral = 'date' GYearMonthLiteral = 'gYearMonth' GYearLiteral = 'gYear' GMonthDayLiteral = 'gMonthDay' GDayLiteral = 'gDay' GMonthLiteral = 'gMonth' HexBinaryLiteral = 'hexBinary' Base64BinaryLiteral = 'base64Binary' AnyURILiteral = 'anyURI' QNameLiteral = 'QName' NormalizedStringLiteral = 'normalizedString' #3.3.2 token #3.3.3 language #3.3.4 NMTOKEN #3.3.5 NMTOKENS #3.3.6 Name #3.3.7 NCName #3.3.8 ID #3.3.9 IDREF #3.3.10 IDREFS #3.3.11 ENTITY #3.3.12 ENTITIES IntegerLiteral = 'integer' NonPositiveIntegerLiteral = 'nonPositiveInteger' NegativeIntegerLiteral = 'negativeInteger' LongLiteral = 'long' IntLiteral = 'int' ShortLiteral = 'short' ByteLiteral = 'byte' NonNegativeIntegerLiteral = 'nonNegativeInteger' UnsignedLongLiteral = 'unsignedLong' UnsignedIntLiteral = 'unsignedInt' UnsignedShortLiteral = 'unsignedShort' UnsignedByteLiteral = 'unsignedByte' PositiveIntegerLiteral = 'positiveInteger' AttrTypeName = QName.new(InstanceNamespace, AttrType) AttrNilName = QName.new(InstanceNamespace, NilLiteral) AnyTypeName = QName.new(Namespace, AnyTypeLiteral) AnySimpleTypeName = QName.new(Namespace, AnySimpleTypeLiteral) class Error < StandardError; end class ValueSpaceError < Error; end ### ## The base class of all datatypes with Namespace. # class NSDBase @@types = [] attr_accessor :type def self.inherited(klass) @@types << klass end def self.types @@types end def initialize end def init(type) @type = type end end ### ## The base class of XSD datatypes. # class XSDAnySimpleType < NSDBase include XSD Type = QName.new(Namespace, AnySimpleTypeLiteral) # @data represents canonical space (ex. Integer: 123). attr_reader :data # @is_nil represents this data is nil or not. attr_accessor :is_nil def initialize(value = nil) init(Type, value) end # true or raise def check_lexical_format(value) screen_data(value) true end # set accepts a string which follows lexical space (ex. String: "+123"), or # an object which follows canonical space (ex. Integer: 123). def set(value) if value.nil? @is_nil = true @data = nil _set(nil) else @is_nil = false _set(screen_data(value)) end end # to_s creates a string which follows lexical space (ex. String: "123"). def to_s() if @is_nil "" else _to_s end end private def init(type, value) super(type) set(value) end # raises ValueSpaceError if check failed def screen_data(value) value end def _set(value) @data = value end def _to_s @data.to_s end end class XSDNil < XSDAnySimpleType Type = QName.new(Namespace, NilLiteral) Value = 'true' def initialize(value = nil) init(Type, value) end end ### ## Primitive datatypes. # class XSDString < XSDAnySimpleType Type = QName.new(Namespace, StringLiteral) def initialize(value = nil) init(Type, value) end private def screen_data(value) unless XSD::Charset.is_ces(value, XSD::Charset.encoding) raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.") end value end end class XSDBoolean < XSDAnySimpleType Type = QName.new(Namespace, BooleanLiteral) def initialize(value = nil) init(Type, value) end private def screen_data(value) if value.is_a?(String) str = value.strip if str == 'true' || str == '1' true elsif str == 'false' || str == '0' false else raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.") end else value ? true : false end end end class XSDDecimal < XSDAnySimpleType Type = QName.new(Namespace, DecimalLiteral) def initialize(value = nil) init(Type, value) end def nonzero? (@number != '0') end private def screen_data(d) if d.is_a?(String) # Integer("00012") => 10 in Ruby. d.sub!(/^([+\-]?)0*(?=\d)/, "\\1") end screen_data_str(d) end def screen_data_str(str) /^([+\-]?)(\d*)(?:\.(\d*)?)?$/ =~ str.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.") end sign = $1 || '+' int_part = $2 frac_part = $3 int_part = '0' if int_part.empty? frac_part = frac_part ? frac_part.sub(/0+$/, '') : '' point = - frac_part.size number = int_part + frac_part # normalize if sign == '+' sign = '' elsif sign == '-' if number == '0' sign = '' end end [sign, point, number] end def _set(data) if data.nil? @sign = @point = @number = @data = nil return end @sign, @point, @number = data @data = _to_s @data.freeze end # 0.0 -> 0; right? def _to_s str = @number.dup if @point.nonzero? str[@number.size + @point, 0] = '.' end @sign + str end end module FloatConstants NaN = 0.0/0.0 POSITIVE_INF = +1.0/0.0 NEGATIVE_INF = -1.0/0.0 POSITIVE_ZERO = +1.0/POSITIVE_INF NEGATIVE_ZERO = -1.0/POSITIVE_INF MIN_POSITIVE_SINGLE = 2.0 ** -149 end class XSDFloat < XSDAnySimpleType include FloatConstants Type = QName.new(Namespace, FloatLiteral) def initialize(value = nil) init(Type, value) end private def screen_data(value) # "NaN".to_f => 0 in some environment. libc? if value.is_a?(Float) return narrow32bit(value) end str = value.to_s.strip if str == 'NaN' NaN elsif str == 'INF' POSITIVE_INF elsif str == '-INF' NEGATIVE_INF else if /^[+\-\.\deE]+$/ !~ str raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.") end # Float("-1.4E") might fail on some system. str << '0' if /e$/i =~ str begin return narrow32bit(Float(str)) rescue ArgumentError raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.") end end end def _to_s if @data.nan? 'NaN' elsif @data.infinite? == 1 'INF' elsif @data.infinite? == -1 '-INF' else sign = XSDFloat.positive?(@data) ? '+' : '-' sign + sprintf("%.10g", @data.abs).sub(/[eE]([+-])?0+/) { 'e' + $1 } end end # Convert to single-precision 32-bit floating point value. def narrow32bit(f) if f.nan? || f.infinite? f elsif f.abs < MIN_POSITIVE_SINGLE XSDFloat.positive?(f) ? POSITIVE_ZERO : NEGATIVE_ZERO else f end end def self.positive?(value) (1 / value) > 0.0 end end # Ruby's Float is double-precision 64-bit floating point value. class XSDDouble < XSDAnySimpleType include FloatConstants Type = QName.new(Namespace, DoubleLiteral) def initialize(value = nil) init(Type, value) end private def screen_data(value) # "NaN".to_f => 0 in some environment. libc? if value.is_a?(Float) return value end str = value.to_s.strip if str == 'NaN' NaN elsif str == 'INF' POSITIVE_INF elsif str == '-INF' NEGATIVE_INF else begin return Float(str) rescue ArgumentError # '1.4e' cannot be parsed on some architecture. if /e\z/i =~ str begin return Float(str + '0') rescue ArgumentError raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.") end else raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.") end end end end def _to_s if @data.nan? 'NaN' elsif @data.infinite? == 1 'INF' elsif @data.infinite? == -1 '-INF' else sign = (1 / @data > 0.0) ? '+' : '-' sign + sprintf("%.16g", @data.abs).sub(/[eE]([+-])?0+/) { 'e' + $1 } end end end class XSDDuration < XSDAnySimpleType Type = QName.new(Namespace, DurationLiteral) attr_accessor :sign attr_accessor :year attr_accessor :month attr_accessor :day attr_accessor :hour attr_accessor :min attr_accessor :sec def initialize(value = nil) init(Type, value) end private def screen_data(value) /^([+\-]?)P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/ =~ value.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.") end if ($5 and ((!$2 and !$3 and !$4) or (!$6 and !$7 and !$8))) # Should we allow 'PT5S' here? raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.") end sign = $1 year = $2.to_i month = $3.to_i day = $4.to_i hour = $6.to_i min = $7.to_i sec = $8 ? XSDDecimal.new($8) : 0 [sign, year, month, day, hour, min, sec] end def _set(data) if data.nil? @sign = @year = @month = @day = @hour = @min = @sec = @data = nil return end @sign, @year, @month, @day, @hour, @min, @sec = data @data = _to_s @data.freeze end def _to_s str = '' str << @sign if @sign str << 'P' l = '' l << "#{ @year }Y" if @year.nonzero? l << "#{ @month }M" if @month.nonzero? l << "#{ @day }D" if @day.nonzero? r = '' r << "#{ @hour }H" if @hour.nonzero? r << "#{ @min }M" if @min.nonzero? r << "#{ @sec }S" if @sec.nonzero? str << l if l.empty? str << "0D" end unless r.empty? str << "T" << r end str end end require 'rational' require 'date' module XSDDateTimeImpl SecInDay = 86400 # 24 * 60 * 60 def to_obj(klass) if klass == Time to_time elsif klass == Date to_date elsif klass == DateTime to_datetime else nil end end def to_time begin if @data.offset * SecInDay == Time.now.utc_offset d = @data usec = (d.sec_fraction * SecInDay * 1000000).round Time.local(d.year, d.month, d.mday, d.hour, d.min, d.sec, usec) else d = @data.newof usec = (d.sec_fraction * SecInDay * 1000000).round Time.gm(d.year, d.month, d.mday, d.hour, d.min, d.sec, usec) end rescue ArgumentError nil end end def to_date Date.new0(@data.class.jd_to_ajd(@data.jd, 0, 0), 0, @data.start) end def to_datetime data end def tz2of(str) /^(?:Z|(?:([+\-])(\d\d):(\d\d))?)$/ =~ str sign = $1 hour = $2.to_i min = $3.to_i of = case sign when '+' of = +(hour.to_r * 60 + min) / 1440 # 24 * 60 when '-' of = -(hour.to_r * 60 + min) / 1440 # 24 * 60 else 0 end of end def of2tz(offset) diffmin = offset * 24 * 60 if diffmin.zero? 'Z' else ((diffmin < 0) ? '-' : '+') << format('%02d:%02d', (diffmin.abs / 60.0).to_i, (diffmin.abs % 60.0).to_i) end end def screen_data(t) # convert t to a DateTime as an internal representation. if t.respond_to?(:to_datetime) # 1.9 or later t.to_datetime elsif t.is_a?(DateTime) t elsif t.is_a?(Date) t = screen_data_str(t) t <<= 12 if t.year < 0 t elsif t.is_a?(Time) jd = DateTime.civil_to_jd(t.year, t.mon, t.mday, DateTime::ITALY) fr = DateTime.time_to_day_fraction(t.hour, t.min, [t.sec, 59].min) + t.usec.to_r / 1000000 / SecInDay of = t.utc_offset.to_r / SecInDay DateTime.new0(DateTime.jd_to_ajd(jd, fr, of), of, DateTime::ITALY) else screen_data_str(t) end end def add_tz(s) s + of2tz(@data.offset) end end class XSDDateTime < XSDAnySimpleType include XSDDateTimeImpl Type = QName.new(Namespace, DateTimeLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(t) /^([+\-]?\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d(?:\.(\d*))?)(Z|(?:[+\-]\d\d:\d\d)?)?$/ =~ t.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end if $1 == '0000' raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end year = $1.to_i if year < 0 year += 1 end mon = $2.to_i mday = $3.to_i hour = $4.to_i min = $5.to_i sec = $6.to_i secfrac = $7 zonestr = $8 data = DateTime.civil(year, mon, mday, hour, min, sec, tz2of(zonestr)) if secfrac diffday = secfrac.to_i.to_r / (10 ** secfrac.size) / SecInDay data += diffday # FYI: new0 and jd_to_rjd are not necessary to use if you don't have # exceptional reason. end [data, secfrac] end def _set(data) if data.nil? @data = @secfrac = nil return end @data, @secfrac = data end def _to_s year = (@data.year > 0) ? @data.year : @data.year - 1 s = format('%.4d-%02d-%02dT%02d:%02d:%02d', year, @data.mon, @data.mday, @data.hour, @data.min, @data.sec) if @data.sec_fraction.nonzero? if @secfrac s << ".#{ @secfrac }" else s << sprintf("%.16f", (@data.sec_fraction * SecInDay).to_f).sub(/^0/, '').sub(/0*$/, '') end end add_tz(s) end end class XSDTime < XSDAnySimpleType include XSDDateTimeImpl Type = QName.new(Namespace, TimeLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(t) /^(\d\d):(\d\d):(\d\d(?:\.(\d*))?)(Z|(?:([+\-])(\d\d):(\d\d))?)?$/ =~ t.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end hour = $1.to_i min = $2.to_i sec = $3.to_i secfrac = $4 zonestr = $5 data = DateTime.civil(1, 1, 1, hour, min, sec, tz2of(zonestr)) if secfrac diffday = secfrac.to_i.to_r / (10 ** secfrac.size) / SecInDay data += diffday end [data, secfrac] end def _set(data) if data.nil? @data = @secfrac = nil return end @data, @secfrac = data end def _to_s s = format('%02d:%02d:%02d', @data.hour, @data.min, @data.sec) if @data.sec_fraction.nonzero? if @secfrac s << ".#{ @secfrac }" else s << sprintf("%.16f", (@data.sec_fraction * SecInDay).to_f).sub(/^0/, '').sub(/0*$/, '') end end add_tz(s) end end class XSDDate < XSDAnySimpleType include XSDDateTimeImpl Type = QName.new(Namespace, DateLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(t) /^([+\-]?\d{4,})-(\d\d)-(\d\d)(Z|(?:([+\-])(\d\d):(\d\d))?)?$/ =~ t.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end year = $1.to_i if year < 0 year += 1 end mon = $2.to_i mday = $3.to_i zonestr = $4 DateTime.civil(year, mon, mday, 0, 0, 0, tz2of(zonestr)) end def _to_s year = (@data.year > 0) ? @data.year : @data.year - 1 s = format('%.4d-%02d-%02d', year, @data.mon, @data.mday) add_tz(s) end end class XSDGYearMonth < XSDAnySimpleType include XSDDateTimeImpl Type = QName.new(Namespace, GYearMonthLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(t) /^([+\-]?\d{4,})-(\d\d)(Z|(?:([+\-])(\d\d):(\d\d))?)?$/ =~ t.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end year = $1.to_i if year < 0 year += 1 end mon = $2.to_i zonestr = $3 DateTime.civil(year, mon, 1, 0, 0, 0, tz2of(zonestr)) end def _to_s year = (@data.year > 0) ? @data.year : @data.year - 1 s = format('%.4d-%02d', year, @data.mon) add_tz(s) end end class XSDGYear < XSDAnySimpleType include XSDDateTimeImpl Type = QName.new(Namespace, GYearLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(t) /^([+\-]?\d{4,})(Z|(?:([+\-])(\d\d):(\d\d))?)?$/ =~ t.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end year = $1.to_i if year < 0 year += 1 end zonestr = $2 DateTime.civil(year, 1, 1, 0, 0, 0, tz2of(zonestr)) end def _to_s year = (@data.year > 0) ? @data.year : @data.year - 1 s = format('%.4d', year) add_tz(s) end end class XSDGMonthDay < XSDAnySimpleType include XSDDateTimeImpl Type = QName.new(Namespace, GMonthDayLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(t) /^(\d\d)-(\d\d)(Z|(?:[+\-]\d\d:\d\d)?)?$/ =~ t.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end mon = $1.to_i mday = $2.to_i zonestr = $3 DateTime.civil(1, mon, mday, 0, 0, 0, tz2of(zonestr)) end def _to_s s = format('%02d-%02d', @data.mon, @data.mday) add_tz(s) end end class XSDGDay < XSDAnySimpleType include XSDDateTimeImpl Type = QName.new(Namespace, GDayLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(t) /^(\d\d)(Z|(?:[+\-]\d\d:\d\d)?)?$/ =~ t.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end mday = $1.to_i zonestr = $2 DateTime.civil(1, 1, mday, 0, 0, 0, tz2of(zonestr)) end def _to_s s = format('%02d', @data.mday) add_tz(s) end end class XSDGMonth < XSDAnySimpleType include XSDDateTimeImpl Type = QName.new(Namespace, GMonthLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(t) /^(\d\d)(Z|(?:[+\-]\d\d:\d\d)?)?$/ =~ t.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ t }'.") end mon = $1.to_i zonestr = $2 DateTime.civil(1, mon, 1, 0, 0, 0, tz2of(zonestr)) end def _to_s s = format('%02d', @data.mon) add_tz(s) end end class XSDHexBinary < XSDAnySimpleType Type = QName.new(Namespace, HexBinaryLiteral) # String in Ruby could be a binary. def initialize(value = nil) init(Type, value) end def set_encoded(value) if /^[0-9a-fA-F]*$/ !~ value raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.") end @data = String.new(value).strip @is_nil = false end def string [@data].pack("H*") end private def screen_data(value) value.unpack("H*")[0].tr('a-f', 'A-F') end end class XSDBase64Binary < XSDAnySimpleType Type = QName.new(Namespace, Base64BinaryLiteral) # String in Ruby could be a binary. def initialize(value = nil) init(Type, value) end def set_encoded(value) if /^[A-Za-z0-9+\/=]*$/ !~ value raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.") end @data = String.new(value).strip @is_nil = false end def string @data.unpack("m")[0] end private def screen_data(value) [value].pack("m").strip end end class XSDAnyURI < XSDAnySimpleType Type = QName.new(Namespace, AnyURILiteral) def initialize(value = nil) init(Type, value) end private def screen_data(value) begin URI.parse(value.to_s.strip) rescue URI::InvalidURIError raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.") end end end class XSDQName < XSDAnySimpleType Type = QName.new(Namespace, QNameLiteral) def initialize(value = nil) init(Type, value) end private def screen_data(value) /^(?:([^:]+):)?([^:]+)$/ =~ value.to_s.strip unless Regexp.last_match raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.") end prefix = $1 localpart = $2 [prefix, localpart] end def _set(data) if data.nil? @prefix = @localpart = @data = nil return end @prefix, @localpart = data @data = _to_s @data.freeze end def _to_s if @prefix "#{ @prefix }:#{ @localpart }" else "#{ @localpart }" end end end ### ## Derived types # class XSDNormalizedString < XSDString Type = QName.new(Namespace, NormalizedStringLiteral) def initialize(value = nil) init(Type, value) end private def screen_data(value) if /[\t\r\n]/ =~ value raise ValueSpaceError.new("#{ type }: cannot accept '#{ value }'.") end super end end class XSDInteger < XSDDecimal Type = QName.new(Namespace, IntegerLiteral) def initialize(value = nil) init(Type, value) end private def screen_data_str(str) begin data = Integer(str) rescue ArgumentError raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.") end unless validate(data) raise ValueSpaceError.new("#{ type }: cannot accept '#{ str }'.") end data end def _set(value) @data = value end def _to_s() @data.to_s end def validate(v) max = maxinclusive min = mininclusive (max.nil? or v <= max) and (min.nil? or v >= min) end def maxinclusive nil end def mininclusive nil end PositiveMinInclusive = 1 def positive(v) PositiveMinInclusive <= v end end class XSDNonPositiveInteger < XSDInteger Type = QName.new(Namespace, NonPositiveIntegerLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive 0 end def mininclusive nil end end class XSDNegativeInteger < XSDNonPositiveInteger Type = QName.new(Namespace, NegativeIntegerLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive -1 end def mininclusive nil end end class XSDLong < XSDInteger Type = QName.new(Namespace, LongLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive +9223372036854775807 end def mininclusive -9223372036854775808 end end class XSDInt < XSDLong Type = QName.new(Namespace, IntLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive +2147483647 end def mininclusive -2147483648 end end class XSDShort < XSDInt Type = QName.new(Namespace, ShortLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive +32767 end def mininclusive -32768 end end class XSDByte < XSDShort Type = QName.new(Namespace, ByteLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive +127 end def mininclusive -128 end end class XSDNonNegativeInteger < XSDInteger Type = QName.new(Namespace, NonNegativeIntegerLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive nil end def mininclusive 0 end end class XSDUnsignedLong < XSDNonNegativeInteger Type = QName.new(Namespace, UnsignedLongLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive +18446744073709551615 end def mininclusive 0 end end class XSDUnsignedInt < XSDUnsignedLong Type = QName.new(Namespace, UnsignedIntLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive +4294967295 end def mininclusive 0 end end class XSDUnsignedShort < XSDUnsignedInt Type = QName.new(Namespace, UnsignedShortLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive +65535 end def mininclusive 0 end end class XSDUnsignedByte < XSDUnsignedShort Type = QName.new(Namespace, UnsignedByteLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive +255 end def mininclusive 0 end end class XSDPositiveInteger < XSDNonNegativeInteger Type = QName.new(Namespace, PositiveIntegerLiteral) def initialize(value = nil) init(Type, value) end private def maxinclusive nil end def mininclusive 1 end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/mapping.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/mapping.rb
# XSD4R - XML Mapping for Ruby # Copyright (C) 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require "soap/parser" require 'soap/encodingstyle/literalHandler' require "soap/generator" require "soap/mapping" require "soap/mapping/wsdlliteralregistry" module XSD module Mapping MappingRegistry = SOAP::Mapping::WSDLLiteralRegistry.new MappingOpt = {:default_encodingstyle => SOAP::LiteralNamespace} def self.obj2xml(obj, elename = nil, io = nil) if !elename.nil? and !elename.is_a?(XSD::QName) elename = XSD::QName.new(nil, elename) end elename ||= XSD::QName.new(nil, SOAP::Mapping.name2elename(obj.class.to_s)) soap = SOAP::Mapping.obj2soap(obj, MappingRegistry) soap.elename = elename generator = SOAP::SOAPGenerator.new(MappingOpt) generator.generate(soap, io) end def self.xml2obj(stream) parser = SOAP::Parser.new(MappingOpt) soap = parser.parse(stream) SOAP::Mapping.soap2obj(soap, MappingRegistry) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/ns.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/ns.rb
# XSD4R - XML Schema Namespace library # Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/datatypes' module XSD class NS class Assigner def initialize @count = 0 end def assign(ns) @count += 1 "n#{@count}" end end attr_reader :default_namespace class FormatError < Error; end public def initialize(tag2ns = {}) @tag2ns = tag2ns @assigner = nil @ns2tag = {} @tag2ns.each do |tag, ns| @ns2tag[ns] = tag end @default_namespace = nil end def assign(ns, tag = nil) if (tag == '') @default_namespace = ns tag else @assigner ||= Assigner.new tag ||= @assigner.assign(ns) @ns2tag[ns] = tag @tag2ns[tag] = ns tag end end def assigned?(ns) @default_namespace == ns or @ns2tag.key?(ns) end def assigned_tag?(tag) @tag2ns.key?(tag) end def clone_ns cloned = NS.new(@tag2ns.dup) cloned.assigner = @assigner cloned.assign(@default_namespace, '') if @default_namespace cloned end def name(name) if (name.namespace == @default_namespace) name.name elsif @ns2tag.key?(name.namespace) "#{@ns2tag[name.namespace]}:#{name.name}" else raise FormatError.new("namespace: #{name.namespace} not defined yet") end end def compare(ns, name, rhs) if (ns == @default_namespace) return true if (name == rhs) end @tag2ns.each do |assigned_tag, assigned_ns| if assigned_ns == ns && "#{assigned_tag}:#{name}" == rhs return true end end false end # $1 and $2 are necessary. ParseRegexp = Regexp.new('^([^:]+)(?::(.+))?$') def parse(str, local = false) if ParseRegexp =~ str if (name = $2) and (ns = @tag2ns[$1]) return XSD::QName.new(ns, name) end end XSD::QName.new(local ? nil : @default_namespace, str) end # For local attribute key parsing # <foo xmlns="urn:a" xmlns:n1="urn:a" bar="1" n1:baz="2" /> # => # {}bar, {urn:a}baz def parse_local(elem) ParseRegexp =~ elem if $2 ns = @tag2ns[$1] name = $2 if !ns raise FormatError.new("unknown namespace qualifier: #{$1}") end elsif $1 ns = nil name = $1 else raise FormatError.new("illegal element format: #{elem}") end XSD::QName.new(ns, name) end def each_ns @ns2tag.each do |ns, tag| yield(ns, tag) end end protected def assigner=(assigner) @assigner = assigner end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/qname.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/qname.rb
# XSD4R - XML QName definition. # Copyright (C) 2002, 2003, 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. module XSD class QName attr_accessor :namespace attr_accessor :name attr_accessor :source def initialize(namespace = nil, name = nil) @namespace = namespace @name = name @source = nil end def dup_name(name) XSD::QName.new(@namespace, name) end def dump ns = @namespace.nil? ? 'nil' : @namespace.dump name = @name.nil? ? 'nil' : @name.dump "XSD::QName.new(#{ns}, #{name})" end def match(rhs) if rhs.namespace and (rhs.namespace != @namespace) return false end if rhs.name and (rhs.name != @name) return false end true end def ==(rhs) !rhs.nil? and @namespace == rhs.namespace and @name == rhs.name end def ===(rhs) (self == rhs) end def eql?(rhs) (self == rhs) end def hash @namespace.hash ^ @name.hash end def to_s "{#{ namespace }}#{ name }" end def inspect sprintf("#<%s:0x%x %s>", self.class.name, __id__, "{#{ namespace }}#{ name }") end NormalizedNameRegexp = /^\{([^}]*)\}(.*)$/ def parse(str) NormalizedNameRegexp =~ str self.new($1, $2) end EMPTY = QName.new.freeze end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser.rb
# XSD4R - XML Instance parser library. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/xmlparser/parser' module XSD module XMLParser def create_parser(host, opt) XSD::XMLParser::Parser.create_parser(host, opt) end module_function :create_parser # $1 is necessary. NSParseRegexp = Regexp.new('^xmlns:?(.*)$') def filter_ns(ns, attrs) return attrs if attrs.nil? or attrs.empty? newattrs = {} attrs.each do |key, value| if (NSParseRegexp =~ key) # '' means 'default namespace'. tag = $1 || '' ns.assign(value, tag) else newattrs[key] = value end end newattrs end module_function :filter_ns end end # Try to load XML processor. loaded = false [ 'xsd/xmlparser/xmlparser', 'xsd/xmlparser/xmlscanner', 'xsd/xmlparser/rexmlparser', ].each do |lib| begin require lib loaded = true break rescue LoadError end end unless loaded raise RuntimeError.new("XML processor module not found.") end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen.rb
# XSD4R - Generating code library # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/codegen/gensupport' require 'xsd/codegen/moduledef' require 'xsd/codegen/classdef' require 'xsd/codegen/methoddef'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/namedelements.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/namedelements.rb
# XSD4R - WSDL named element collection. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. module XSD class NamedElements include Enumerable def initialize @elements = [] @cache = {} end def dup o = NamedElements.new o.elements = @elements.dup o end def freeze super @elements.freeze self end def empty? size == 0 end def size @elements.size end def [](idx) if idx.is_a?(Numeric) @elements[idx] else @cache[idx] ||= @elements.find { |item| item.name == idx } end end def find_name(name) @elements.find { |item| item.name.name == name } end def keys collect { |element| element.name } end def each @elements.each do |element| yield(element) end end def <<(rhs) @elements << rhs self end def delete(rhs) @elements.delete(rhs) end def +(rhs) o = NamedElements.new o.elements = @elements + rhs.elements o end def concat(rhs) @elements.concat(rhs.elements) self end Empty = NamedElements.new.freeze protected def elements=(rhs) @elements = rhs end def elements @elements end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/charset.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/charset.rb
# XSD4R - Charset handling library. # Copyright (C) 2001, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. module XSD module Charset @internal_encoding = $KCODE class XSDError < StandardError; end class CharsetError < XSDError; end class UnknownCharsetError < CharsetError; end class CharsetConversionError < CharsetError; end public ### ## Maps # EncodingConvertMap = {} def Charset.init EncodingConvertMap[['UTF8', 'X_ISO8859_1']] = Proc.new { |str| str.unpack('U*').pack('C*') } EncodingConvertMap[['X_ISO8859_1', 'UTF8']] = Proc.new { |str| str.unpack('C*').pack('U*') } begin require 'xsd/iconvcharset' @internal_encoding = 'UTF8' sjtag = (/(mswin|bccwin|mingw|cygwin|emx)/ =~ RUBY_PLATFORM) ? 'cp932' : 'shift_jis' EncodingConvertMap[['UTF8', 'EUC' ]] = Proc.new { |str| IconvCharset.safe_iconv("euc-jp", "utf-8", str) } EncodingConvertMap[['EUC' , 'UTF8']] = Proc.new { |str| IconvCharset.safe_iconv("utf-8", "euc-jp", str) } EncodingConvertMap[['EUC' , 'SJIS']] = Proc.new { |str| IconvCharset.safe_iconv(sjtag, "euc-jp", str) } EncodingConvertMap[['UTF8', 'SJIS']] = Proc.new { |str| IconvCharset.safe_iconv(sjtag, "utf-8", str) } EncodingConvertMap[['SJIS', 'UTF8']] = Proc.new { |str| IconvCharset.safe_iconv("utf-8", sjtag, str) } EncodingConvertMap[['SJIS', 'EUC' ]] = Proc.new { |str| IconvCharset.safe_iconv("euc-jp", sjtag, str) } rescue LoadError begin require 'nkf' EncodingConvertMap[['EUC' , 'SJIS']] = Proc.new { |str| NKF.nkf('-sXm0', str) } EncodingConvertMap[['SJIS', 'EUC' ]] = Proc.new { |str| NKF.nkf('-eXm0', str) } rescue LoadError end begin require 'uconv' @internal_encoding = 'UTF8' EncodingConvertMap[['UTF8', 'EUC' ]] = Uconv.method(:u8toeuc) EncodingConvertMap[['UTF8', 'SJIS']] = Uconv.method(:u8tosjis) EncodingConvertMap[['EUC' , 'UTF8']] = Uconv.method(:euctou8) EncodingConvertMap[['SJIS', 'UTF8']] = Uconv.method(:sjistou8) rescue LoadError end end end self.init CharsetMap = { 'NONE' => 'us-ascii', 'EUC' => 'euc-jp', 'SJIS' => 'shift_jis', 'UTF8' => 'utf-8', 'X_ISO_8859_1' => 'iso-8859-1', 'X_UNKNOWN' => nil, } ### ## handlers # def Charset.encoding @internal_encoding end def Charset.encoding=(encoding) warn("xsd charset is set to #{encoding}") if $DEBUG @internal_encoding = encoding end def Charset.xml_encoding_label charset_label(@internal_encoding) end def Charset.encoding_to_xml(str, charset) encoding_conv(str, @internal_encoding, charset_str(charset)) end def Charset.encoding_from_xml(str, charset) encoding_conv(str, charset_str(charset), @internal_encoding) end def Charset.encoding_conv(str, enc_from, enc_to) if enc_from == enc_to or enc_from == 'NONE' or enc_to == 'NONE' str elsif converter = EncodingConvertMap[[enc_from, enc_to]] converter.call(str) else raise CharsetConversionError.new( "Converter not found: #{enc_from} -> #{enc_to}") end end def Charset.charset_label(encoding) CharsetMap[encoding.upcase] end def Charset.charset_str(label) if CharsetMap.respond_to?(:key) CharsetMap.key(label.downcase) || 'X_UNKNOWN' else CharsetMap.index(label.downcase) || 'X_UNKNOWN' end end # us_ascii = '[\x00-\x7F]' us_ascii = '[\x9\xa\xd\x20-\x7F]' # XML 1.0 restricted. USASCIIRegexp = Regexp.new("\\A#{us_ascii}*\\z", nil, "NONE") twobytes_euc = '(?:[\x8E\xA1-\xFE][\xA1-\xFE])' threebytes_euc = '(?:\x8F[\xA1-\xFE][\xA1-\xFE])' character_euc = "(?:#{us_ascii}|#{twobytes_euc}|#{threebytes_euc})" EUCRegexp = Regexp.new("\\A#{character_euc}*\\z", nil, "NONE") # onebyte_sjis = '[\x00-\x7F\xA1-\xDF]' onebyte_sjis = '[\x9\xa\xd\x20-\x7F\xA1-\xDF]' # XML 1.0 restricted. twobytes_sjis = '(?:[\x81-\x9F\xE0-\xFC][\x40-\x7E\x80-\xFC])' character_sjis = "(?:#{onebyte_sjis}|#{twobytes_sjis})" SJISRegexp = Regexp.new("\\A#{character_sjis}*\\z", nil, "NONE") # 0xxxxxxx # 110yyyyy 10xxxxxx twobytes_utf8 = '(?:[\xC0-\xDF][\x80-\xBF])' # 1110zzzz 10yyyyyy 10xxxxxx threebytes_utf8 = '(?:[\xE0-\xEF][\x80-\xBF][\x80-\xBF])' # 11110uuu 10uuuzzz 10yyyyyy 10xxxxxx fourbytes_utf8 = '(?:[\xF0-\xF7][\x80-\xBF][\x80-\xBF][\x80-\xBF])' character_utf8 = "(?:#{us_ascii}|#{twobytes_utf8}|#{threebytes_utf8}|#{fourbytes_utf8})" UTF8Regexp = Regexp.new("\\A#{character_utf8}*\\z", nil, "NONE") def Charset.is_us_ascii(str) USASCIIRegexp =~ str end def Charset.is_utf8(str) UTF8Regexp =~ str end def Charset.is_euc(str) EUCRegexp =~ str end def Charset.is_sjis(str) SJISRegexp =~ str end def Charset.is_ces(str, code = $KCODE) case code when 'NONE' is_us_ascii(str) when 'UTF8' is_utf8(str) when 'EUC' is_euc(str) when 'SJIS' is_sjis(str) else raise UnknownCharsetError.new("Unknown charset: #{code}") end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/iconvcharset.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/iconvcharset.rb
# XSD4R - Charset handling with iconv. # Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'iconv' module XSD class IconvCharset def self.safe_iconv(to, from, str) iconv = Iconv.new(to, from) out = "" begin out << iconv.iconv(str) rescue Iconv::IllegalSequence => e out << e.success ch, str = e.failed.split(//, 2) out << '?' warn("Failed to convert #{ch}") retry end return out end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser/rexmlparser.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser/rexmlparser.rb
# XSD4R - REXMLParser XML parser library. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/xmlparser' require 'rexml/streamlistener' require 'rexml/document' module XSD module XMLParser class REXMLParser < XSD::XMLParser::Parser include REXML::StreamListener def do_parse(string_or_readable) source = nil source = REXML::SourceFactory.create_from(string_or_readable) source.encoding = charset if charset # Listener passes a String in utf-8. @charset = 'utf-8' REXML::Document.parse_stream(source, self) end def epilogue end def tag_start(name, attrs) start_element(name, attrs) end def tag_end(name) end_element(name) end def text(text) characters(text) end def xmldecl(version, encoding, standalone) # Version should be checked. end add_factory(self) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser/parser.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser/parser.rb
# XSD4R - XML Instance parser library. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' require 'xsd/ns' require 'xsd/charset' module XSD module XMLParser class Parser class ParseError < Error; end class FormatDecodeError < ParseError; end class UnknownElementError < FormatDecodeError; end class UnknownAttributeError < FormatDecodeError; end class UnexpectedElementError < FormatDecodeError; end class ElementConstraintError < FormatDecodeError; end @@parser_factory = nil def self.factory @@parser_factory end def self.create_parser(host, opt = {}) @@parser_factory.new(host, opt) end def self.add_factory(factory) if $DEBUG puts "Set #{ factory } as XML processor." end @@parser_factory = factory end public attr_accessor :charset def initialize(host, opt = {}) @host = host @charset = opt[:charset] || nil end def parse(string_or_readable) @textbuf = '' prologue do_parse(string_or_readable) epilogue end private def do_parse(string_or_readable) raise NotImplementError.new( 'Method do_parse must be defined in derived class.') end def start_element(name, attrs) @host.start_element(name, attrs) end def characters(text) @host.characters(text) end def end_element(name) @host.end_element(name) end def prologue end def epilogue end def xmldecl_encoding=(charset) if @charset.nil? @charset = charset else # Definition in a stream (like HTTP) has a priority. p "encoding definition: #{ charset } is ignored." if $DEBUG end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser/xmlparser.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser/xmlparser.rb
# XSD4R - XMLParser XML parser library. # Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/xmlparser' require 'xml/parser' module XSD module XMLParser class XMLParser < XSD::XMLParser::Parser class Listener < XML::Parser begin require 'xml/encoding-ja' include XML::Encoding_ja rescue LoadError # uconv may not be installed. end end def do_parse(string_or_readable) # XMLParser passes a String in utf-8. @charset = 'utf-8' @parser = Listener.new @parser.parse(string_or_readable) do |type, name, data| case type when XML::Parser::START_ELEM start_element(name, data) when XML::Parser::END_ELEM end_element(name) when XML::Parser::CDATA characters(data) else raise FormatDecodeError.new("Unexpected XML: #{ type }/#{ name }/#{ data }.") end end end add_factory(self) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser/xmlscanner.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/xmlparser/xmlscanner.rb
# XSD4R - XMLScan XML parser library. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/xmlparser' require 'xmlscan/scanner' module XSD module XMLParser class XMLScanner < XSD::XMLParser::Parser include XMLScan::Visitor def do_parse(string_or_readable) @attrs = {} @curattr = nil @scanner = XMLScan::XMLScanner.new(self) @scanner.kcode = XSD::Charset.charset_str(charset) if charset @scanner.parse(string_or_readable) end def scanner_kcode=(charset) @scanner.kcode = XSD::Charset.charset_str(charset) if charset self.xmldecl_encoding = charset end ENTITY_REF_MAP = { 'lt' => '<', 'gt' => '>', 'amp' => '&', 'quot' => '"', 'apos' => '\'' } def parse_error(msg) raise ParseError.new(msg) end def wellformed_error(msg) raise NotWellFormedError.new(msg) end def valid_error(msg) raise NotValidError.new(msg) end def warning(msg) p msg if $DEBUG end # def on_xmldecl; end def on_xmldecl_version(str) # 1.0 expected. end def on_xmldecl_encoding(str) self.scanner_kcode = str end # def on_xmldecl_standalone(str); end # def on_xmldecl_other(name, value); end # def on_xmldecl_end; end # def on_doctype(root, pubid, sysid); end # def on_prolog_space(str); end # def on_comment(str); end # def on_pi(target, pi); end def on_chardata(str) characters(str) end # def on_cdata(str); end def on_etag(name) end_element(name) end def on_entityref(ref) characters(ENTITY_REF_MAP[ref]) end def on_charref(code) characters([code].pack('U')) end def on_charref_hex(code) on_charref(code) end # def on_start_document; end # def on_end_document; end def on_stag(name) @attrs = {} end def on_attribute(name) @attrs[name] = @curattr = '' end def on_attr_value(str) @curattr << str end def on_attr_entityref(ref) @curattr << ENTITY_REF_MAP[ref] end def on_attr_charref(code) @curattr << [code].pack('U') end def on_attr_charref_hex(code) on_attr_charref(code) end # def on_attribute_end(name); end def on_stag_end_empty(name) on_stag_end(name) on_etag(name) end def on_stag_end(name) start_element(name, @attrs) end add_factory(self) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/gensupport.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/gensupport.rb
# XSD4R - Code generation support # Copyright (C) 2004, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. module XSD module CodeGen # from the file 'keywords' in 1.9. KEYWORD = {} %w( __LINE__ __FILE__ BEGIN END alias and begin break case class def defined? do else elsif end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield ).each { |k| KEYWORD[k] = nil } module GenSupport def capitalize(target) target.sub(/^([a-z])/) { $1.tr!('[a-z]', '[A-Z]') } end module_function :capitalize def uncapitalize(target) target.sub(/^([A-Z])/) { $1.tr!('[A-Z]', '[a-z]') } end module_function :uncapitalize def safeconstname(name) safename = name.scan(/[a-zA-Z0-9_]+/).collect { |ele| GenSupport.capitalize(ele) }.join if /^[A-Z]/ !~ safename or keyword?(safename) safename = "C_#{safename}" end safename end module_function :safeconstname def safeconstname?(name) /\A[A-Z][a-zA-Z0-9_]*\z/ =~ name and !keyword?(name) end module_function :safeconstname? def safemethodname(name) safename = name.scan(/[a-zA-Z0-9_]+/).join('_') safename = uncapitalize(safename) if /^[a-z]/ !~ safename safename = "m_#{safename}" end safename end module_function :safemethodname def safemethodname?(name) /\A[a-zA-Z_][a-zA-Z0-9_]*[=!?]?\z/ =~ name end module_function :safemethodname? def safevarname(name) safename = uncapitalize(name.scan(/[a-zA-Z0-9_]+/).join('_')) if /^[a-z]/ !~ safename or keyword?(safename) "v_#{safename}" else safename end end module_function :safevarname def safevarname?(name) /\A[a-z_][a-zA-Z0-9_]*\z/ =~ name and !keyword?(name) end module_function :safevarname? def keyword?(word) KEYWORD.key?(word) end module_function :keyword? def format(str, indent = nil) str = trim_eol(str) str = trim_indent(str) if indent str.gsub(/^/, " " * indent) else str end end private def trim_eol(str) str.collect { |line| line.sub(/\r?\n\z/, "") + "\n" }.join end def trim_indent(str) indent = nil str = str.collect { |line| untab(line) }.join str.each do |line| head = line.index(/\S/) if !head.nil? and (indent.nil? or head < indent) indent = head end end return str unless indent str.collect { |line| line.sub(/^ {0,#{indent}}/, "") }.join end def untab(line, ts = 8) while pos = line.index(/\t/) line = line.sub(/\t/, " " * (ts - (pos % ts))) end line end def dump_emptyline "\n" end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/classdef.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/classdef.rb
# XSD4R - Generating class definition code # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/codegen/gensupport' require 'xsd/codegen/moduledef' require 'xsd/codegen/methoddef' module XSD module CodeGen class ClassDef < ModuleDef include GenSupport def initialize(name, baseclass = nil) super(name) @baseclass = baseclass @classvar = [] @attrdef = [] end def def_classvar(var, value) var = var.sub(/\A@@/, "") unless safevarname?(var) raise ArgumentError.new("#{var} seems to be unsafe") end @classvar << [var, value] end def def_attr(attrname, writable = true, varname = nil) unless safevarname?(varname || attrname) raise ArgumentError.new("#{varname || attrname} seems to be unsafe") end @attrdef << [attrname, writable, varname] end def dump buf = "" unless @requirepath.empty? buf << dump_requirepath end buf << dump_emptyline unless buf.empty? package = @name.split(/::/)[0..-2] buf << dump_package_def(package) unless package.empty? buf << dump_comment if @comment buf << dump_class_def spacer = false unless @classvar.empty? spacer = true buf << dump_classvar end unless @const.empty? buf << dump_emptyline if spacer spacer = true buf << dump_const end unless @code.empty? buf << dump_emptyline if spacer spacer = true buf << dump_code end unless @attrdef.empty? buf << dump_emptyline if spacer spacer = true buf << dump_attributes end unless @methoddef.empty? buf << dump_emptyline if spacer spacer = true buf << dump_methods end buf << dump_class_def_end buf << dump_package_def_end(package) unless package.empty? buf.gsub(/^\s+$/, '') end private def dump_class_def name = @name.to_s.split(/::/) if @baseclass format("class #{name.last} < #{@baseclass}") else format("class #{name.last}") end end def dump_class_def_end str = format("end") end def dump_classvar dump_static( @classvar.collect { |var, value| %Q(@@#{var.sub(/^@@/, "")} = #{dump_value(value)}) }.join("\n") ) end def dump_attributes str = "" @attrdef.each do |attrname, writable, varname| varname ||= attrname if attrname == varname str << format(dump_accessor(attrname, writable), 2) end end @attrdef.each do |attrname, writable, varname| varname ||= attrname if attrname != varname str << "\n" unless str.empty? str << format(dump_attribute(attrname, writable, varname), 2) end end str end def dump_accessor(attrname, writable) if writable "attr_accessor :#{attrname}" else "attr_reader :#{attrname}" end end def dump_attribute(attrname, writable, varname) str = nil mr = MethodDef.new(attrname) mr.definition = "@#{varname}" str = mr.dump if writable mw = MethodDef.new(attrname + "=", 'value') mw.definition = "@#{varname} = value" str << "\n" + mw.dump end str end end end end if __FILE__ == $0 require 'xsd/codegen/classdef' include XSD::CodeGen c = ClassDef.new("Foo::Bar::HobbitName", String) c.def_require("foo/bar") c.comment = <<-EOD foo bar baz EOD c.def_const("FOO", 1) c.def_classvar("@@foo", "var".dump) c.def_classvar("baz", "1".dump) c.def_attr("Foo", true, "foo") c.def_attr("bar") c.def_attr("baz", true) c.def_attr("Foo2", true, "foo2") c.def_attr("foo3", false, "foo3") c.def_method("foo") do <<-EOD foo.bar = 1 \tbaz.each do |ele| \t ele end EOD end c.def_method("baz", "qux") do <<-EOD [1, 2, 3].each do |i| p i end EOD end m = MethodDef.new("qux", "quxx", "quxxx") do <<-EOD p quxx + quxxx EOD end m.comment = "hello world\n123" c.add_method(m) c.def_code <<-EOD Foo.new Bar.z EOD c.def_code <<-EOD Foo.new Bar.z EOD c.def_privatemethod("foo", "baz", "*arg", "&block") puts c.dump end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/moduledef.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/moduledef.rb
# XSD4R - Generating module definition code # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/codegen/gensupport' require 'xsd/codegen/methoddef' require 'xsd/codegen/commentdef' module XSD module CodeGen class ModuleDef include GenSupport include CommentDef def initialize(name) @name = name @comment = nil @const = [] @code = [] @requirepath = [] @methoddef = [] end def def_require(path) @requirepath << path end def def_const(const, value) unless safeconstname?(const) raise ArgumentError.new("#{const} seems to be unsafe") end @const << [const, value] end def def_code(code) @code << code end def def_method(name, *params) add_method(MethodDef.new(name, *params) { yield if block_given? }, :public) end alias def_publicmethod def_method def def_protectedmethod(name, *params) add_method(MethodDef.new(name, *params) { yield if block_given? }, :protected) end def def_privatemethod(name, *params) add_method(MethodDef.new(name, *params) { yield if block_given? }, :private) end def add_method(m, visibility = :public) @methoddef << [visibility, m] end def dump buf = "" unless @requirepath.empty? buf << dump_requirepath end buf << dump_emptyline unless buf.empty? package = @name.split(/::/)[0..-2] buf << dump_package_def(package) unless package.empty? buf << dump_comment if @comment buf << dump_module_def spacer = false unless @const.empty? buf << dump_emptyline if spacer spacer = true buf << dump_const end unless @code.empty? buf << dump_emptyline if spacer spacer = true buf << dump_code end unless @methoddef.empty? buf << dump_emptyline if spacer spacer = true buf << dump_methods end buf << dump_module_def_end buf << dump_package_def_end(package) unless package.empty? buf.gsub(/^\s+$/, '') end private def dump_requirepath format( @requirepath.collect { |path| %Q(require '#{path}') }.join("\n") ) end def dump_const dump_static( @const.sort.collect { |var, value| %Q(#{var} = #{dump_value(value)}) }.join("\n") ) end def dump_code dump_static(@code.join("\n")) end def dump_static(str) format(str, 2) end def dump_methods methods = {} @methoddef.each do |visibility, method| (methods[visibility] ||= []) << method end str = "" [:public, :protected, :private].each do |visibility| if methods[visibility] str << "\n" unless str.empty? str << visibility.to_s << "\n\n" unless visibility == :public str << methods[visibility].collect { |m| format(m.dump, 2) }.join("\n") end end str end def dump_value(value) if value.respond_to?(:to_src) value.to_src else value end end def dump_package_def(package) format(package.collect { |ele| "module #{ele}" }.join("; ")) + "\n\n" end def dump_package_def_end(package) "\n\n" + format(package.collect { |ele| "end" }.join("; ")) end def dump_module_def name = @name.to_s.split(/::/) format("module #{name.last}") end def dump_module_def_end format("end") end end end end if __FILE__ == $0 require 'xsd/codegen/moduledef' include XSD::CodeGen m = ModuleDef.new("Foo::Bar::HobbitName") m.def_require("foo/bar") m.def_require("baz") m.comment = <<-EOD foo bar baz EOD m.def_method("foo") do <<-EOD foo.bar = 1 baz.each do |ele| ele + 1 end EOD end m.def_method("baz", "qux") #m.def_protectedmethod("aaa") m.def_privatemethod("bbb") puts m.dump end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/commentdef.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/commentdef.rb
# XSD4R - Generating comment definition code # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/codegen/gensupport' module XSD module CodeGen module CommentDef include GenSupport attr_accessor :comment private def dump_comment if /\A#/ =~ @comment format(@comment) else format(@comment).gsub(/^/, '# ') end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/methoddef.rb
tools/jruby-1.5.1/lib/ruby/1.8/xsd/codegen/methoddef.rb
# XSD4R - Generating method definition code # Copyright (C) 2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/codegen/gensupport' require 'xsd/codegen/commentdef' module XSD module CodeGen class MethodDef include GenSupport include CommentDef attr_accessor :definition def initialize(name, *params) unless safemethodname?(name) raise ArgumentError.new("name '#{name}' seems to be unsafe") end @name = name @params = params @comment = nil @definition = yield if block_given? end def dump buf = "" buf << dump_comment if @comment buf << dump_method_def buf << dump_definition if @definition and !@definition.empty? buf << dump_method_def_end buf end private def dump_method_def if @params.empty? format("def #{@name}") else format("def #{@name}(#{@params.join(", ")})") end end def dump_method_def_end format("end") end def dump_definition format(@definition, 2) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/dl/win32.rb
tools/jruby-1.5.1/lib/ruby/1.8/dl/win32.rb
# -*- ruby -*- require 'dl' class Win32API DLL = {} def initialize(dllname, func, import, export = "0") prototype = (export + import.to_s).tr("VPpNnLlIi", "0SSI").sub(/^(.)0*$/, '\1') handle = DLL[dllname] ||= DL::Handle.new(dllname) @sym = handle.sym(func, prototype) end def call(*args) import = @sym.proto.split("", 2)[1] args.each_with_index do |x, i| args[i] = nil if x == 0 and import[i] == ?S args[i], = [x].pack("I").unpack("i") if import[i] == ?I end ret, = @sym.call(*args) return ret || 0 end alias Call call end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/dl/struct.rb
tools/jruby-1.5.1/lib/ruby/1.8/dl/struct.rb
# -*- ruby -*- require 'dl' require 'dl/import' module DL module Importable module Internal def define_struct(contents) init_types() Struct.new(@types, contents) end alias struct define_struct def define_union(contents) init_types() Union.new(@types, contents) end alias union define_union class Memory def initialize(ptr, names, ty, len, enc, dec) @ptr = ptr @names = names @ty = ty @len = len @enc = enc @dec = dec # define methods @names.each{|name| instance_eval [ "def #{name}", " v = @ptr[\"#{name}\"]", " if( @len[\"#{name}\"] )", " v = v.collect{|x| @dec[\"#{name}\"] ? @dec[\"#{name}\"].call(x) : x }", " else", " v = @dec[\"#{name}\"].call(v) if @dec[\"#{name}\"]", " end", " return v", "end", "def #{name}=(v)", " if( @len[\"#{name}\"] )", " v = v.collect{|x| @enc[\"#{name}\"] ? @enc[\"#{name}\"].call(x) : x }", " else", " v = @enc[\"#{name}\"].call(v) if @enc[\"#{name}\"]", " end", " @ptr[\"#{name}\"] = v", " return v", "end", ].join("\n") } end def to_ptr return @ptr end def size return @ptr.size end end class Struct def initialize(types, contents) @names = [] @ty = {} @len = {} @enc = {} @dec = {} @size = 0 @tys = "" @types = types parse(contents) end def size return @size end def members return @names end # ptr must be a PtrData object. def new(ptr) ptr.struct!(@tys, *@names) mem = Memory.new(ptr, @names, @ty, @len, @enc, @dec) return mem end def malloc(size = nil) if( !size ) size = @size end ptr = DL::malloc(size) return new(ptr) end def parse(contents) contents.each{|elem| name,ty,num,enc,dec = parse_elem(elem) @names.push(name) @ty[name] = ty @len[name] = num @enc[name] = enc @dec[name] = dec if( num ) @tys += "#{ty}#{num}" else @tys += ty end } @size = DL.sizeof(@tys) end def parse_elem(elem) elem.strip! case elem when /^([\w\d_\*]+)([\*\s]+)([\w\d_]+)$/ ty = ($1 + $2).strip name = $3 num = nil; when /^([\w\d_\*]+)([\*\s]+)([\w\d_]+)\[(\d+)\]$/ ty = ($1 + $2).strip name = $3 num = $4.to_i else raise(RuntimeError, "invalid element: #{elem}") end ty,enc,dec = @types.encode_struct_type(ty) if( !ty ) raise(TypeError, "unsupported type: #{ty}") end return [name,ty,num,enc,dec] end end # class Struct class Union < Struct def new ptr = DL::malloc(@size) ptr.union!(@tys, *@names) mem = Memory.new(ptr, @names, @ty, @len, @enc, @dec) return mem end end end # module Internal end # module Importable end # module DL
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/dl/types.rb
tools/jruby-1.5.1/lib/ruby/1.8/dl/types.rb
# -*- ruby -*- require 'dl' module DL class Types TYPES = [ # FORMAT: # ["alias name", # "type name", encoding_method, decoding_method, for function prototypes # "type name", encoding_method, decoding_method] for structures (not implemented) # for Windows ["DWORD", "unsigned long", nil, nil, "unsigned long", nil, nil], ["PDWORD", "unsigned long *", nil, nil, "unsigned long *", nil, nil], ["WORD", "unsigned short", nil, nil, "unsigned short", nil, nil], ["PWORD", "unsigned int *", nil, nil, "unsigned int *", nil, nil], ["BYTE", "unsigned char", nil, nil, "unsigned char", nil, nil], ["PBYTE", "unsigned char *", nil, nil, "unsigned char *", nil, nil], ["BOOL", "ibool", nil, nil, "ibool", nil, nil], ["ATOM", "int", nil, nil, "int", nil, nil], ["BYTE", "unsigned char", nil, nil, "unsigned char", nil, nil], ["PBYTE", "unsigned char *", nil, nil, "unsigned char *", nil, nil], ["UINT", "unsigned int", nil, nil, "unsigned int", nil, nil], ["ULONG", "unsigned long", nil, nil, "unsigned long", nil, nil], ["UCHAR", "unsigned char", nil, nil, "unsigned char", nil, nil], ["HANDLE", "unsigned long", nil, nil, "unsigned long", nil, nil], ["PHANDLE","void*", nil, nil, "void*", nil, nil], ["PVOID", "void*", nil, nil, "void*", nil, nil], ["LPCSTR", "char*", nil, nil, "char*", nil, nil], ["HDC", "unsigned int", nil, nil, "unsigned int", nil, nil], ["HWND", "unsigned int", nil, nil, "unsigned int", nil, nil], # Others ["uint", "unsigned int", nil, nil, "unsigned int", nil, nil], ["u_int", "unsigned int", nil, nil, "unsigned int", nil, nil], ["ulong", "unsigned long", nil, nil, "unsigned long", nil, nil], ["u_long", "unsigned long", nil, nil, "unsigned long", nil, nil], # DL::Importable primitive types ["ibool", "I", proc{|v| v ? 1 : 0}, proc{|v| (v != 0) ? true : false}, "I", proc{|v| v ? 1 : 0 }, proc{|v| (v != 0) ? true : false} ], ["cbool", "C", proc{|v| v ? 1 : 0}, proc{|v| (v != 0) ? true : false}, "C", proc{|v,len| v ? 1 : 0}, proc{|v,len| (v != 0) ? true : false}], ["lbool", "L", proc{|v| v ? 1 : 0}, proc{|v| (v != 0) ? true : false}, "L", proc{|v,len| v ? 1 : 0}, proc{|v,len| (v != 0) ? true : false}], ["unsigned char", "C", proc{|v| [v].pack("C").unpack("c")[0]}, proc{|v| [v].pack("c").unpack("C")[0]}, "C", proc{|v| [v].pack("C").unpack("c")[0]}, proc{|v| [v].pack("c").unpack("C")[0]}], ["unsigned short", "H", proc{|v| [v].pack("S").unpack("s")[0]}, proc{|v| [v].pack("s").unpack("S")[0]}, "H", proc{|v| [v].pack("S").unpack("s")[0]}, proc{|v| [v].pack("s").unpack("S")[0]}], ["unsigned int", "I", proc{|v| [v].pack("I").unpack("i")[0]}, proc{|v| [v].pack("i").unpack("I")[0]}, "I", proc{|v| [v].pack("I").unpack("i")[0]}, proc{|v| [v].pack("i").unpack("I")[0]}], ["unsigned long", "L", proc{|v| [v].pack("L").unpack("l")[0]}, proc{|v| [v].pack("l").unpack("L")[0]}, "L", proc{|v| [v].pack("L").unpack("l")[0]}, proc{|v| [v].pack("l").unpack("L")[0]}], ["unsigned char ref", "c", proc{|v| [v].pack("C").unpack("c")[0]}, proc{|v| [v].pack("c").unpack("C")[0]}, nil, nil, nil], ["unsigned int ref", "i", proc{|v| [v].pack("I").unpack("i")[0]}, proc{|v| [v].pack("i").unpack("I")[0]}, nil, nil, nil], ["unsigned long ref", "l", proc{|v| [v].pack("L").unpack("l")[0]}, proc{|v| [v].pack("l").unpack("L")[0]}, nil, nil, nil], ["char ref", "c", nil, nil, nil, nil, nil], ["short ref", "h", nil, nil, nil, nil, nil], ["int ref", "i", nil, nil, nil, nil, nil], ["long ref", "l", nil, nil, nil, nil, nil], ["float ref", "f", nil, nil, nil, nil, nil], ["double ref","d", nil, nil, nil, nil, nil], ["char", "C", nil, nil, "C", nil, nil], ["short", "H", nil, nil, "H", nil, nil], ["int", "I", nil, nil, "I", nil, nil], ["long", "L", nil, nil, "L", nil, nil], ["float", "F", nil, nil, "F", nil, nil], ["double", "D", nil, nil, "D", nil, nil], [/^char\s*\*$/,"s",nil, nil, "S",nil, nil], [/^const char\s*\*$/,"S",nil, nil, "S",nil, nil], [/^.+\*$/, "P", nil, nil, "P", nil, nil], [/^.+\[\]$/, "a", nil, nil, "a", nil, nil], ["void", "0", nil, nil, nil, nil, nil], ] def initialize init_types() end def typealias(ty1, ty2, enc=nil, dec=nil, ty3=nil, senc=nil, sdec=nil) @TYDEFS.unshift([ty1, ty2, enc, dec, ty3, senc, sdec]) end def init_types @TYDEFS = TYPES.dup end def encode_argument_type(alias_type) proc_encode = nil proc_decode = nil @TYDEFS.each{|aty,ty,enc,dec,_,_,_| if( (aty.is_a?(Regexp) && (aty =~ alias_type)) || (aty == alias_type) ) alias_type = alias_type.gsub(aty,ty) if ty alias_type.strip! if alias_type if( proc_encode ) if( enc ) conv1 = proc_encode proc_encode = proc{|v| enc.call(conv1.call(v))} end else if( enc ) proc_encode = enc end end if( proc_decode ) if( dec ) conv2 = proc_decode proc_decode = proc{|v| dec.call(conv2.call(v))} end else if( dec ) proc_decode = dec end end end } return [alias_type, proc_encode, proc_decode] end def encode_return_type(ty) ty, enc, dec = encode_argument_type(ty) return [ty, enc, dec] end def encode_struct_type(alias_type) proc_encode = nil proc_decode = nil @TYDEFS.each{|aty,_,_,_,ty,enc,dec| if( (aty.is_a?(Regexp) && (aty =~ alias_type)) || (aty == alias_type) ) alias_type = alias_type.gsub(aty,ty) if ty alias_type.strip! if alias_type if( proc_encode ) if( enc ) conv1 = proc_encode proc_encode = proc{|v| enc.call(conv1.call(v))} end else if( enc ) proc_encode = enc end end if( proc_decode ) if( dec ) conv2 = proc_decode proc_decode = proc{|v| dec.call(conv2.call(v))} end else if( dec ) proc_decode = dec end end end } return [alias_type, proc_encode, proc_decode] end end # end of Types end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/dl/import.rb
tools/jruby-1.5.1/lib/ruby/1.8/dl/import.rb
# -*- ruby -*- require 'dl' require 'dl/types' module DL module Importable LIB_MAP = {} module Internal def init_types() @types ||= ::DL::Types.new end def init_sym() @SYM ||= {} end def [](name) return @SYM[name.to_s][0] end def dlload(*libnames) if( !defined?(@LIBS) ) @LIBS = [] end libnames.each{|libname| if( !LIB_MAP[libname] ) LIB_MAP[libname] = DL.dlopen(libname) end @LIBS.push(LIB_MAP[libname]) } end alias dllink :dlload def parse_cproto(proto) proto = proto.gsub(/\s+/, " ").strip case proto when /^([\d\w\*_\s]+)\(([\d\w\*_\s\,\[\]]*)\)$/ ret = $1 args = $2.strip() ret = ret.split(/\s+/) args = args.split(/\s*,\s*/) func = ret.pop() if( func =~ /^\*/ ) func.gsub!(/^\*+/,"") ret.push("*") end ret = ret.join(" ") return [func, ret, args] else raise(RuntimeError,"can't parse the function prototype: #{proto}") end end # example: # extern "int strlen(char*)" # def extern(proto) func,ret,args = parse_cproto(proto) return import(func, ret, args) end # example: # callback "int method_name(int, char*)" # def callback(proto) func,ret,args = parse_cproto(proto) init_types() init_sym() rty,renc,rdec = @types.encode_return_type(ret) if( !rty ) raise(TypeError, "unsupported type: #{ret}") end ty,enc,dec = encode_argument_types(args) symty = rty + ty module_eval("module_function :#{func}") sym = module_eval([ "DL::callback(\"#{symty}\"){|*args|", " sym,rdec,enc,dec = @SYM['#{func}']", " args = enc.call(args) if enc", " r,rs = #{func}(*args)", " r = renc.call(r) if rdec", " rs = dec.call(rs) if (dec && rs)", " @retval = r", " @args = rs", " r", "}", ].join("\n")) @SYM[func] = [sym,rdec,enc,dec] return sym end # example: # typealias("uint", "unsigned int") # def typealias(alias_type, ty1, enc1=nil, dec1=nil, ty2=nil, enc2=nil, dec2=nil) init_types() @types.typealias(alias_type, ty1, enc1, dec1, ty2||ty1, enc2, dec2) end # example: # symbol "foo_value" # symbol "foo_func", "IIP" # def symbol(name, ty = nil) sym = nil @LIBS.each{|lib| begin if( ty ) sym = lib[name, ty] else sym = lib[name] end rescue next end } if( !sym ) raise(RuntimeError, "can't find the symbol `#{name}'") end return sym end # example: # import("get_length", "int", ["void*", "int"]) # def import(name, rettype, argtypes = nil) init_types() init_sym() rty,_,rdec = @types.encode_return_type(rettype) if( !rty ) raise(TypeError, "unsupported type: #{rettype}") end ty,enc,dec = encode_argument_types(argtypes) symty = rty + ty sym = symbol(name, symty) mname = name.dup if( ?A <= mname[0] && mname[0] <= ?Z ) mname[0,1] = mname[0,1].downcase end @SYM[mname] = [sym,rdec,enc,dec] module_eval [ "def #{mname}(*args)", " sym,rdec,enc,dec = @SYM['#{mname}']", " args = enc.call(args) if enc", if( $DEBUG ) " p \"[DL] call #{mname} with \#{args.inspect}\"" else "" end, " r,rs = sym.call(*args)", if( $DEBUG ) " p \"[DL] retval=\#{r.inspect} args=\#{rs.inspect}\"" else "" end, " r = rdec.call(r) if rdec", " rs = dec.call(rs) if dec", " @retval = r", " @args = rs", " return r", "end", "module_function :#{mname}", ].join("\n") return sym end def _args_ return @args end def _retval_ return @retval end def encode_argument_types(tys) init_types() encty = [] enc = nil dec = nil tys.each_with_index{|ty,idx| ty,c1,c2 = @types.encode_argument_type(ty) if( !ty ) raise(TypeError, "unsupported type: #{ty}") end encty.push(ty) if( enc ) if( c1 ) conv1 = enc enc = proc{|v| v = conv1.call(v); v[idx] = c1.call(v[idx]); v} end else if( c1 ) enc = proc{|v| v[idx] = c1.call(v[idx]); v} end end if( dec ) if( c2 ) conv2 = dec dec = proc{|v| v = conv2.call(v); v[idx] = c2.call(v[idx]); v} end else if( c2 ) dec = proc{|v| v[idx] = c2.call(v[idx]); v} end end } return [encty.join, enc, dec] end end # end of Internal include Internal end # end of Importable end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/date/format.rb
tools/jruby-1.5.1/lib/ruby/1.8/date/format.rb
# format.rb: Written by Tadayoshi Funaba 1999-2008 # $Id: format.rb,v 2.43 2008-01-17 20:16:31+09 tadf Exp $ require 'rational' class Date module Format # :nodoc: MONTHS = { 'january' => 1, 'february' => 2, 'march' => 3, 'april' => 4, 'may' => 5, 'june' => 6, 'july' => 7, 'august' => 8, 'september'=> 9, 'october' =>10, 'november' =>11, 'december' =>12 } DAYS = { 'sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday'=> 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6 } ABBR_MONTHS = { 'jan' => 1, 'feb' => 2, 'mar' => 3, 'apr' => 4, 'may' => 5, 'jun' => 6, 'jul' => 7, 'aug' => 8, 'sep' => 9, 'oct' =>10, 'nov' =>11, 'dec' =>12 } ABBR_DAYS = { 'sun' => 0, 'mon' => 1, 'tue' => 2, 'wed' => 3, 'thu' => 4, 'fri' => 5, 'sat' => 6 } ZONES = { 'ut' => 0*3600, 'gmt' => 0*3600, 'est' => -5*3600, 'edt' => -4*3600, 'cst' => -6*3600, 'cdt' => -5*3600, 'mst' => -7*3600, 'mdt' => -6*3600, 'pst' => -8*3600, 'pdt' => -7*3600, 'a' => 1*3600, 'b' => 2*3600, 'c' => 3*3600, 'd' => 4*3600, 'e' => 5*3600, 'f' => 6*3600, 'g' => 7*3600, 'h' => 8*3600, 'i' => 9*3600, 'k' => 10*3600, 'l' => 11*3600, 'm' => 12*3600, 'n' => -1*3600, 'o' => -2*3600, 'p' => -3*3600, 'q' => -4*3600, 'r' => -5*3600, 's' => -6*3600, 't' => -7*3600, 'u' => -8*3600, 'v' => -9*3600, 'w' =>-10*3600, 'x' =>-11*3600, 'y' =>-12*3600, 'z' => 0*3600, 'utc' => 0*3600, 'wet' => 0*3600, 'at' => -2*3600, 'brst'=> -2*3600, 'ndt' => -(2*3600+1800), 'art' => -3*3600, 'adt' => -3*3600, 'brt' => -3*3600, 'clst'=> -3*3600, 'nst' => -(3*3600+1800), 'ast' => -4*3600, 'clt' => -4*3600, 'akdt'=> -8*3600, 'ydt' => -8*3600, 'akst'=> -9*3600, 'hadt'=> -9*3600, 'hdt' => -9*3600, 'yst' => -9*3600, 'ahst'=>-10*3600, 'cat' =>-10*3600, 'hast'=>-10*3600, 'hst' =>-10*3600, 'nt' =>-11*3600, 'idlw'=>-12*3600, 'bst' => 1*3600, 'cet' => 1*3600, 'fwt' => 1*3600, 'met' => 1*3600, 'mewt'=> 1*3600, 'mez' => 1*3600, 'swt' => 1*3600, 'wat' => 1*3600, 'west'=> 1*3600, 'cest'=> 2*3600, 'eet' => 2*3600, 'fst' => 2*3600, 'mest'=> 2*3600, 'mesz'=> 2*3600, 'sast'=> 2*3600, 'sst' => 2*3600, 'bt' => 3*3600, 'eat' => 3*3600, 'eest'=> 3*3600, 'msk' => 3*3600, 'msd' => 4*3600, 'zp4' => 4*3600, 'zp5' => 5*3600, 'ist' => (5*3600+1800), 'zp6' => 6*3600, 'wast'=> 7*3600, 'cct' => 8*3600, 'sgt' => 8*3600, 'wadt'=> 8*3600, 'jst' => 9*3600, 'kst' => 9*3600, 'east'=> 10*3600, 'gst' => 10*3600, 'eadt'=> 11*3600, 'idle'=> 12*3600, 'nzst'=> 12*3600, 'nzt' => 12*3600, 'nzdt'=> 13*3600, 'afghanistan' => 16200, 'alaskan' => -32400, 'arab' => 10800, 'arabian' => 14400, 'arabic' => 10800, 'atlantic' => -14400, 'aus central' => 34200, 'aus eastern' => 36000, 'azores' => -3600, 'canada central' => -21600, 'cape verde' => -3600, 'caucasus' => 14400, 'cen. australia' => 34200, 'central america' => -21600, 'central asia' => 21600, 'central europe' => 3600, 'central european' => 3600, 'central pacific' => 39600, 'central' => -21600, 'china' => 28800, 'dateline' => -43200, 'e. africa' => 10800, 'e. australia' => 36000, 'e. europe' => 7200, 'e. south america' => -10800, 'eastern' => -18000, 'egypt' => 7200, 'ekaterinburg' => 18000, 'fiji' => 43200, 'fle' => 7200, 'greenland' => -10800, 'greenwich' => 0, 'gtb' => 7200, 'hawaiian' => -36000, 'india' => 19800, 'iran' => 12600, 'jerusalem' => 7200, 'korea' => 32400, 'mexico' => -21600, 'mid-atlantic' => -7200, 'mountain' => -25200, 'myanmar' => 23400, 'n. central asia' => 21600, 'nepal' => 20700, 'new zealand' => 43200, 'newfoundland' => -12600, 'north asia east' => 28800, 'north asia' => 25200, 'pacific sa' => -14400, 'pacific' => -28800, 'romance' => 3600, 'russian' => 10800, 'sa eastern' => -10800, 'sa pacific' => -18000, 'sa western' => -14400, 'samoa' => -39600, 'se asia' => 25200, 'malay peninsula' => 28800, 'south africa' => 7200, 'sri lanka' => 21600, 'taipei' => 28800, 'tasmania' => 36000, 'tokyo' => 32400, 'tonga' => 46800, 'us eastern' => -18000, 'us mountain' => -25200, 'vladivostok' => 36000, 'w. australia' => 28800, 'w. central africa' => 3600, 'w. europe' => 3600, 'west asia' => 18000, 'west pacific' => 36000, 'yakutsk' => 32400 } [MONTHS, DAYS, ABBR_MONTHS, ABBR_DAYS, ZONES].each do |x| x.freeze end class Bag # :nodoc: def initialize @elem = {} end def method_missing(t, *args, &block) t = t.to_s set = t.chomp!('=') t = t.intern if set @elem[t] = args[0] else @elem[t] end end def to_hash @elem.reject{|k, v| /\A_/ =~ k.to_s || v.nil?} end end end def emit(e, f) # :nodoc: case e when Numeric sign = %w(+ + -)[e <=> 0] e = e.abs end s = e.to_s if f[:s] && f[:p] == '0' f[:w] -= 1 end if f[:s] && f[:p] == "\s" s[0,0] = sign end if f[:p] != '-' s = s.rjust(f[:w], f[:p]) end if f[:s] && f[:p] != "\s" s[0,0] = sign end s = s.upcase if f[:u] s = s.downcase if f[:d] s end def emit_w(e, w, f) # :nodoc: f[:w] = [f[:w], w].compact.max emit(e, f) end def emit_n(e, w, f) # :nodoc: f[:p] ||= '0' emit_w(e, w, f) end def emit_sn(e, w, f) # :nodoc: if e < 0 w += 1 f[:s] = true end emit_n(e, w, f) end def emit_z(e, w, f) # :nodoc: w += 1 f[:s] = true emit_n(e, w, f) end def emit_a(e, w, f) # :nodoc: f[:p] ||= "\s" emit_w(e, w, f) end def emit_ad(e, w, f) # :nodoc: if f[:x] f[:u] = true f[:d] = false end emit_a(e, w, f) end def emit_au(e, w, f) # :nodoc: if f[:x] f[:u] = false f[:d] = true end emit_a(e, w, f) end private :emit, :emit_w, :emit_n, :emit_sn, :emit_z, :emit_a, :emit_ad, :emit_au def strftime(fmt='%F') fmt.gsub(/%([-_0^#]+)?(\d+)?([EO]?(?::{1,3}z|.))/m) do |m| f = {} a = $& s, w, c = $1, $2, $3 if s s.scan(/./) do |k| case k when '-'; f[:p] = '-' when '_'; f[:p] = "\s" when '0'; f[:p] = '0' when '^'; f[:u] = true when '#'; f[:x] = true end end end if w f[:w] = w.to_i end case c when 'A'; emit_ad(DAYNAMES[wday], 0, f) when 'a'; emit_ad(ABBR_DAYNAMES[wday], 0, f) when 'B'; emit_ad(MONTHNAMES[mon], 0, f) when 'b'; emit_ad(ABBR_MONTHNAMES[mon], 0, f) when 'C', 'EC'; emit_sn((year / 100).floor, 2, f) when 'c', 'Ec'; emit_a(strftime('%a %b %e %H:%M:%S %Y'), 0, f) when 'D'; emit_a(strftime('%m/%d/%y'), 0, f) when 'd', 'Od'; emit_n(mday, 2, f) when 'e', 'Oe'; emit_a(mday, 2, f) when 'F' if m == '%F' format('%.4d-%02d-%02d', year, mon, mday) # 4p else emit_a(strftime('%Y-%m-%d'), 0, f) end when 'G'; emit_sn(cwyear, 4, f) when 'g'; emit_n(cwyear % 100, 2, f) when 'H', 'OH'; emit_n(hour, 2, f) when 'h'; emit_ad(strftime('%b'), 0, f) when 'I', 'OI'; emit_n((hour % 12).nonzero? || 12, 2, f) when 'j'; emit_n(yday, 3, f) when 'k'; emit_a(hour, 2, f) when 'L' emit_n((sec_fraction / MILLISECONDS_IN_DAY).floor, 3, f) when 'l'; emit_a((hour % 12).nonzero? || 12, 2, f) when 'M', 'OM'; emit_n(min, 2, f) when 'm', 'Om'; emit_n(mon, 2, f) when 'N' emit_n((sec_fraction / NANOSECONDS_IN_DAY).floor, 9, f) when 'n'; "\n" when 'P'; emit_ad(strftime('%p').downcase, 0, f) when 'p'; emit_au(if hour < 12 then 'AM' else 'PM' end, 0, f) when 'Q' s = ((ajd - UNIX_EPOCH_IN_AJD) / MILLISECONDS_IN_DAY).round emit_sn(s, 1, f) when 'R'; emit_a(strftime('%H:%M'), 0, f) when 'r'; emit_a(strftime('%I:%M:%S %p'), 0, f) when 'S', 'OS'; emit_n(sec, 2, f) when 's' s = ((ajd - UNIX_EPOCH_IN_AJD) / SECONDS_IN_DAY).round emit_sn(s, 1, f) when 'T' if m == '%T' format('%02d:%02d:%02d', hour, min, sec) # 4p else emit_a(strftime('%H:%M:%S'), 0, f) end when 't'; "\t" when 'U', 'W', 'OU', 'OW' emit_n(if c[-1,1] == 'U' then wnum0 else wnum1 end, 2, f) when 'u', 'Ou'; emit_n(cwday, 1, f) when 'V', 'OV'; emit_n(cweek, 2, f) when 'v'; emit_a(strftime('%e-%b-%Y'), 0, f) when 'w', 'Ow'; emit_n(wday, 1, f) when 'X', 'EX'; emit_a(strftime('%H:%M:%S'), 0, f) when 'x', 'Ex'; emit_a(strftime('%m/%d/%y'), 0, f) when 'Y', 'EY'; emit_sn(year, 4, f) when 'y', 'Ey', 'Oy'; emit_n(year % 100, 2, f) when 'Z'; emit_au(strftime('%:z'), 0, f) when /\A(:{0,3})z/ t = $1.size sign = if offset < 0 then -1 else +1 end fr = offset.abs ss = fr.div(SECONDS_IN_DAY) # 4p hh, ss = ss.divmod(3600) mm, ss = ss.divmod(60) if t == 3 if ss.nonzero? then t = 2 elsif mm.nonzero? then t = 1 else t = -1 end end case t when -1 tail = [] sep = '' when 0 f[:w] -= 2 if f[:w] tail = ['%02d' % mm] sep = '' when 1 f[:w] -= 3 if f[:w] tail = ['%02d' % mm] sep = ':' when 2 f[:w] -= 6 if f[:w] tail = ['%02d' % mm, '%02d' % ss] sep = ':' end ([emit_z(sign * hh, 2, f)] + tail).join(sep) when '%'; emit_a('%', 0, f) when '+'; emit_a(strftime('%a %b %e %H:%M:%S %Z %Y'), 0, f) when '1' if $VERBOSE warn("warning: strftime: %1 is deprecated; forget this") end emit_n(jd, 1, f) when '2' if $VERBOSE warn("warning: strftime: %2 is deprecated; use '%Y-%j'") end emit_a(strftime('%Y-%j'), 0, f) when '3' if $VERBOSE warn("warning: strftime: %3 is deprecated; use '%F'") end emit_a(strftime('%F'), 0, f) else a end end end # alias_method :format, :strftime def asctime() strftime('%c') end alias_method :ctime, :asctime =begin def iso8601() strftime('%F') end def rfc3339() iso8601 end def rfc2822() strftime('%a, %-d %b %Y %T %z') end alias_method :rfc822, :rfc2822 def jisx0301 if jd < 2405160 iso8601 else case jd when 2405160...2419614 g = 'M%02d' % (year - 1867) when 2419614...2424875 g = 'T%02d' % (year - 1911) when 2424875...2447535 g = 'S%02d' % (year - 1925) else g = 'H%02d' % (year - 1988) end g + strftime('.%m.%d') end end def beat(n=0) i, f = (new_offset(HOURS_IN_DAY).day_fraction * 1000).divmod(1) ('@%03d' % i) + if n < 1 '' else '.%0*d' % [n, (f / Rational(1, 10**n)).round] end end =end def self.num_pattern? (s) # :nodoc: /\A%[EO]?[CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy\d]/ =~ s || /\A\d/ =~ s end private_class_method :num_pattern? def self._strptime_i(str, fmt, e) # :nodoc: fmt.scan(/%([EO]?(?::{1,3}z|.))|(.)/m) do |s, c| a = $& if s case s when 'A', 'a' return unless str.sub!(/\A(#{Format::DAYS.keys.join('|')})/io, '') || str.sub!(/\A(#{Format::ABBR_DAYS.keys.join('|')})/io, '') val = Format::DAYS[$1.downcase] || Format::ABBR_DAYS[$1.downcase] return unless val e.wday = val when 'B', 'b', 'h' return unless str.sub!(/\A(#{Format::MONTHS.keys.join('|')})/io, '') || str.sub!(/\A(#{Format::ABBR_MONTHS.keys.join('|')})/io, '') val = Format::MONTHS[$1.downcase] || Format::ABBR_MONTHS[$1.downcase] return unless val e.mon = val when 'C', 'EC' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,2})/ else /\A([-+]?\d{1,})/ end, '') val = $1.to_i e._cent = val when 'c', 'Ec' return unless _strptime_i(str, '%a %b %e %H:%M:%S %Y', e) when 'D' return unless _strptime_i(str, '%m/%d/%y', e) when 'd', 'e', 'Od', 'Oe' return unless str.sub!(/\A( \d|\d{1,2})/, '') val = $1.to_i return unless (1..31) === val e.mday = val when 'F' return unless _strptime_i(str, '%Y-%m-%d', e) when 'G' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,4})/ else /\A([-+]?\d{1,})/ end, '') val = $1.to_i e.cwyear = val when 'g' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..99) === val e.cwyear = val e._cent ||= if val >= 69 then 19 else 20 end when 'H', 'k', 'OH' return unless str.sub!(/\A( \d|\d{1,2})/, '') val = $1.to_i return unless (0..24) === val e.hour = val when 'I', 'l', 'OI' return unless str.sub!(/\A( \d|\d{1,2})/, '') val = $1.to_i return unless (1..12) === val e.hour = val when 'j' return unless str.sub!(/\A(\d{1,3})/, '') val = $1.to_i return unless (1..366) === val e.yday = val when 'L' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,3})/ else /\A([-+]?\d{1,})/ end, '') # val = Rational($1.to_i, 10**3) val = Rational($1.to_i, 10**$1.size) e.sec_fraction = val when 'M', 'OM' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..59) === val e.min = val when 'm', 'Om' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (1..12) === val e.mon = val when 'N' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,9})/ else /\A([-+]?\d{1,})/ end, '') # val = Rational($1.to_i, 10**9) val = Rational($1.to_i, 10**$1.size) e.sec_fraction = val when 'n', 't' return unless _strptime_i(str, "\s", e) when 'P', 'p' return unless str.sub!(/\A([ap])(?:m\b|\.m\.)/i, '') e._merid = if $1.downcase == 'a' then 0 else 12 end when 'Q' return unless str.sub!(/\A(-?\d{1,})/, '') val = Rational($1.to_i, 10**3) e.seconds = val when 'R' return unless _strptime_i(str, '%H:%M', e) when 'r' return unless _strptime_i(str, '%I:%M:%S %p', e) when 'S', 'OS' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..60) === val e.sec = val when 's' return unless str.sub!(/\A(-?\d{1,})/, '') val = $1.to_i e.seconds = val when 'T' return unless _strptime_i(str, '%H:%M:%S', e) when 'U', 'W', 'OU', 'OW' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..53) === val e.__send__(if s[-1,1] == 'U' then :wnum0= else :wnum1= end, val) when 'u', 'Ou' return unless str.sub!(/\A(\d{1})/, '') val = $1.to_i return unless (1..7) === val e.cwday = val when 'V', 'OV' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (1..53) === val e.cweek = val when 'v' return unless _strptime_i(str, '%e-%b-%Y', e) when 'w' return unless str.sub!(/\A(\d{1})/, '') val = $1.to_i return unless (0..6) === val e.wday = val when 'X', 'EX' return unless _strptime_i(str, '%H:%M:%S', e) when 'x', 'Ex' return unless _strptime_i(str, '%m/%d/%y', e) when 'Y', 'EY' return unless str.sub!(if num_pattern?($') then /\A([-+]?\d{1,4})/ else /\A([-+]?\d{1,})/ end, '') val = $1.to_i e.year = val when 'y', 'Ey', 'Oy' return unless str.sub!(/\A(\d{1,2})/, '') val = $1.to_i return unless (0..99) === val e.year = val e._cent ||= if val >= 69 then 19 else 20 end when 'Z', /\A:{0,3}z/ return unless str.sub!(/\A((?:gmt|utc?)?[-+]\d+(?:[,.:]\d+(?::\d+)?)? |[[:alpha:].\s]+(?:standard|daylight)\s+time\b |[[:alpha:]]+(?:\s+dst)?\b )/ix, '') val = $1 e.zone = val offset = zone_to_diff(val) e.offset = offset when '%' return unless str.sub!(/\A%/, '') when '+' return unless _strptime_i(str, '%a %b %e %H:%M:%S %Z %Y', e) when '1' if $VERBOSE warn("warning: strptime: %1 is deprecated; forget this") end return unless str.sub!(/\A(\d+)/, '') val = $1.to_i e.jd = val when '2' if $VERBOSE warn("warning: strptime: %2 is deprecated; use '%Y-%j'") end return unless _strptime_i(str, '%Y-%j', e) when '3' if $VERBOSE warn("warning: strptime: %3 is deprecated; use '%F'") end return unless _strptime_i(str, '%F', e) else return unless str.sub!(Regexp.new('\\A' + Regexp.quote(a)), '') end else case c when /\A[\s\v]/ str.sub!(/\A[\s\v]+/, '') else return unless str.sub!(Regexp.new('\\A' + Regexp.quote(a)), '') end end end end private_class_method :_strptime_i def self._strptime(str, fmt='%F') str = str.dup e = Format::Bag.new return unless _strptime_i(str, fmt, e) if e._cent if e.cwyear e.cwyear += e._cent * 100 end if e.year e. year += e._cent * 100 end end if e._merid if e.hour e.hour %= 12 e.hour += e._merid end end unless str.empty? e.leftover = str end e.to_hash end def self.s3e(e, y, m, d, bc=false) unless String === m m = m.to_s end if y && m && !d y, m, d = d, y, m end if y == nil if d && d.size > 2 y = d d = nil end if d && d[0,1] == "'" y = d d = nil end end if y y.scan(/(\d+)(.+)?/) if $2 y, d = d, $1 end end if m if m[0,1] == "'" || m.size > 2 y, m, d = m, d, y # us -> be end end if d if d[0,1] == "'" || d.size > 2 y, d = d, y end end if y y =~ /([-+])?(\d+)/ if $1 || $2.size > 2 c = false end iy = $&.to_i if bc iy = -iy + 1 end e.year = iy end if m m =~ /\d+/ e.mon = $&.to_i end if d d =~ /\d+/ e.mday = $&.to_i end if c != nil e._comp = c end end private_class_method :s3e def self._parse_day(str, e) # :nodoc: if str.sub!(/\b(#{Format::ABBR_DAYS.keys.join('|')})[^-\d\s]*/ino, ' ') e.wday = Format::ABBR_DAYS[$1.downcase] true =begin elsif str.sub!(/\b(?!\dth)(su|mo|tu|we|th|fr|sa)\b/in, ' ') e.wday = %w(su mo tu we th fr sa).index($1.downcase) true =end end end def self._parse_time(str, e) # :nodoc: if str.sub!( /( (?: \d+\s*:\s*\d+ (?: \s*:\s*\d+(?:[,.]\d*)? )? | \d+\s*h(?:\s*\d+m?(?:\s*\d+s?)?)? ) (?: \s* [ap](?:m\b|\.m\.) )? | \d+\s*[ap](?:m\b|\.m\.) ) (?: \s* ( (?:gmt|utc?)?[-+]\d+(?:[,.:]\d+(?::\d+)?)? | [[:alpha:].\s]+(?:standard|daylight)\stime\b | [[:alpha:]]+(?:\sdst)?\b ) )? /inx, ' ') t = $1 e.zone = $2 if $2 t =~ /\A(\d+)h? (?:\s*:?\s*(\d+)m? (?: \s*:?\s*(\d+)(?:[,.](\d+))?s? )? )? (?:\s*([ap])(?:m\b|\.m\.))?/inx e.hour = $1.to_i e.min = $2.to_i if $2 e.sec = $3.to_i if $3 e.sec_fraction = Rational($4.to_i, 10**$4.size) if $4 if $5 e.hour %= 12 if $5.downcase == 'p' e.hour += 12 end end true end end =begin def self._parse_beat(str, e) # :nodoc: if str.sub!(/@\s*(\d+)(?:[,.](\d*))?/, ' ') beat = Rational($1.to_i) beat += Rational($2.to_i, 10**$2.size) if $2 secs = Rational(beat, 1000) h, min, s, fr = self.day_fraction_to_time(secs) e.hour = h e.min = min e.sec = s e.sec_fraction = fr * 86400 e.zone = '+01:00' true end end =end def self._parse_eu(str, e) # :nodoc: if str.sub!( /'?(\d+)[^-\d\s]* \s* (#{Format::ABBR_MONTHS.keys.join('|')})[^-\d\s']* (?: \s* (c(?:e|\.e\.)|b(?:ce|\.c\.e\.)|a(?:d|\.d\.)|b(?:c|\.c\.))? \s* ('?-?\d+(?:(?:st|nd|rd|th)\b)?) )? /inox, ' ') # ' s3e(e, $4, Format::ABBR_MONTHS[$2.downcase], $1, $3 && $3[0,1].downcase == 'b') true end end def self._parse_us(str, e) # :nodoc: if str.sub!( /\b(#{Format::ABBR_MONTHS.keys.join('|')})[^-\d\s']* \s* ('?\d+)[^-\d\s']* (?: \s* (c(?:e|\.e\.)|b(?:ce|\.c\.e\.)|a(?:d|\.d\.)|b(?:c|\.c\.))? \s* ('?-?\d+) )? /inox, ' ') # ' s3e(e, $4, Format::ABBR_MONTHS[$1.downcase], $2, $3 && $3[0,1].downcase == 'b') true end end def self._parse_iso(str, e) # :nodoc: if str.sub!(/('?[-+]?\d+)-(\d+)-('?-?\d+)/n, ' ') s3e(e, $1, $2, $3) true end end def self._parse_iso2(str, e) # :nodoc: if str.sub!(/\b(\d{2}|\d{4})?-?w(\d{2})(?:-?(\d))?\b/in, ' ') e.cwyear = $1.to_i if $1 e.cweek = $2.to_i e.cwday = $3.to_i if $3 true elsif str.sub!(/-w-(\d)\b/in, ' ') e.cwday = $1.to_i true elsif str.sub!(/--(\d{2})?-(\d{2})\b/n, ' ') e.mon = $1.to_i if $1 e.mday = $2.to_i true elsif str.sub!(/--(\d{2})(\d{2})?\b/n, ' ') e.mon = $1.to_i e.mday = $2.to_i if $2 true elsif /[,.](\d{2}|\d{4})-\d{3}\b/n !~ str && str.sub!(/\b(\d{2}|\d{4})-(\d{3})\b/n, ' ') e.year = $1.to_i e.yday = $2.to_i true elsif /\d-\d{3}\b/n !~ str && str.sub!(/\b-(\d{3})\b/n, ' ') e.yday = $1.to_i true end end def self._parse_jis(str, e) # :nodoc: if str.sub!(/\b([mtsh])(\d+)\.(\d+)\.(\d+)/in, ' ') era = { 'm'=>1867, 't'=>1911, 's'=>1925, 'h'=>1988 }[$1.downcase] e.year = $2.to_i + era e.mon = $3.to_i e.mday = $4.to_i true end end def self._parse_vms(str, e) # :nodoc: if str.sub!(/('?-?\d+)-(#{Format::ABBR_MONTHS.keys.join('|')})[^-]* -('?-?\d+)/inox, ' ') s3e(e, $3, Format::ABBR_MONTHS[$2.downcase], $1) true elsif str.sub!(/\b(#{Format::ABBR_MONTHS.keys.join('|')})[^-]* -('?-?\d+)(?:-('?-?\d+))?/inox, ' ') s3e(e, $3, Format::ABBR_MONTHS[$1.downcase], $2) true end end def self._parse_sla(str, e) # :nodoc: if str.sub!(%r|('?-?\d+)/\s*('?\d+)(?:\D\s*('?-?\d+))?|n, ' ') # ' s3e(e, $3, $1, $2) true end end def self._parse_dot(str, e) # :nodoc: if str.sub!(%r|('?-?\d+)\.\s*('?\d+)\.\s*('?-?\d+)|n, ' ') # ' s3e(e, $1, $2, $3) true end end def self._parse_year(str, e) # :nodoc: if str.sub!(/'(\d+)\b/n, ' ') e.year = $1.to_i true end end def self._parse_mon(str, e) # :nodoc: if str.sub!(/\b(#{Format::ABBR_MONTHS.keys.join('|')})\S*/ino, ' ') e.mon = Format::ABBR_MONTHS[$1.downcase] true end end def self._parse_mday(str, e) # :nodoc: if str.sub!(/(\d+)(st|nd|rd|th)\b/in, ' ') e.mday = $1.to_i true end end def self._parse_ddd(str, e) # :nodoc: if str.sub!( /([-+]?)(\d{2,14}) (?: \s* t? \s* (\d{2,6})?(?:[,.](\d*))? )? (?: \s* ( z\b | [-+]\d{1,4}\b | \[[-+]?\d[^\]]*\] ) )? /inx, ' ') case $2.size when 2 if $3.nil? && $4 e.sec = $2[-2, 2].to_i else e.mday = $2[ 0, 2].to_i end when 4 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i else e.mon = $2[ 0, 2].to_i e.mday = $2[ 2, 2].to_i end when 6 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i e.hour = $2[-6, 2].to_i else e.year = ($1 + $2[ 0, 2]).to_i e.mon = $2[ 2, 2].to_i e.mday = $2[ 4, 2].to_i end when 8, 10, 12, 14 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i e.hour = $2[-6, 2].to_i e.mday = $2[-8, 2].to_i if $2.size >= 10 e.mon = $2[-10, 2].to_i end if $2.size == 12 e.year = ($1 + $2[-12, 2]).to_i end if $2.size == 14 e.year = ($1 + $2[-14, 4]).to_i e._comp = false end else e.year = ($1 + $2[ 0, 4]).to_i e.mon = $2[ 4, 2].to_i e.mday = $2[ 6, 2].to_i e.hour = $2[ 8, 2].to_i if $2.size >= 10 e.min = $2[10, 2].to_i if $2.size >= 12 e.sec = $2[12, 2].to_i if $2.size >= 14 e._comp = false end when 3 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-3, 1].to_i else e.yday = $2[ 0, 3].to_i end when 5 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i e.hour = $2[-5, 1].to_i else e.year = ($1 + $2[ 0, 2]).to_i e.yday = $2[ 2, 3].to_i end when 7 if $3.nil? && $4 e.sec = $2[-2, 2].to_i e.min = $2[-4, 2].to_i e.hour = $2[-6, 2].to_i e.mday = $2[-7, 1].to_i else e.year = ($1 + $2[ 0, 4]).to_i e.yday = $2[ 4, 3].to_i end end if $3 if $4 case $3.size when 2, 4, 6 e.sec = $3[-2, 2].to_i e.min = $3[-4, 2].to_i if $3.size >= 4 e.hour = $3[-6, 2].to_i if $3.size >= 6 end else case $3.size when 2, 4, 6 e.hour = $3[ 0, 2].to_i e.min = $3[ 2, 2].to_i if $3.size >= 4 e.sec = $3[ 4, 2].to_i if $3.size >= 6 end end end if $4 e.sec_fraction = Rational($4.to_i, 10**$4.size) end if $5 e.zone = $5 if e.zone[0,1] == '[' o, n, = e.zone[1..-2].split(':') e.zone = n || o if /\A\d/ =~ o o = format('+%s', o) end e.offset = zone_to_diff(o) end end true end end private_class_method :_parse_day, :_parse_time, # :_parse_beat, :_parse_eu, :_parse_us, :_parse_iso, :_parse_iso2, :_parse_jis, :_parse_vms, :_parse_sla, :_parse_dot, :_parse_year, :_parse_mon, :_parse_mday, :_parse_ddd def self._parse(str, comp=false) str = str.dup e = Format::Bag.new e._comp = comp str.gsub!(/[^-+',.\/:@[:alnum:]\[\]\x80-\xff]+/n, ' ') _parse_time(str, e) # || _parse_beat(str, e) _parse_day(str, e) _parse_eu(str, e) || _parse_us(str, e) || _parse_iso(str, e) || _parse_jis(str, e) || _parse_vms(str, e) || _parse_sla(str, e) || _parse_dot(str, e) || _parse_iso2(str, e) || _parse_year(str, e) || _parse_mon(str, e) || _parse_mday(str, e) || _parse_ddd(str, e) if str.sub!(/\b(bc\b|bce\b|b\.c\.|b\.c\.e\.)/in, ' ') if e.year e.year = -e.year + 1 end end if str.sub!(/\A\s*(\d{1,2})\s*\z/n, ' ') if e.hour && !e.mday v = $1.to_i if (1..31) === v e.mday = v end end if e.mday && !e.hour v = $1.to_i if (0..24) === v e.hour = v end end end if e._comp if e.cwyear if e.cwyear >= 0 && e.cwyear <= 99 e.cwyear += if e.cwyear >= 69 then 1900 else 2000 end end end if e.year if e.year >= 0 && e.year <= 99 e.year += if e.year >= 69 then 1900 else 2000 end end end end e.offset ||= zone_to_diff(e.zone) if e.zone e.to_hash end def self.zone_to_diff(zone) # :nodoc: zone = zone.downcase if zone.sub!(/\s+(standard|daylight)\s+time\z/, '') dst = $1 == 'daylight' else dst = zone.sub!(/\s+dst\z/, '') end if Format::ZONES.include?(zone) offset = Format::ZONES[zone] offset += 3600 if dst elsif zone.sub!(/\A(?:gmt|utc?)?([-+])/, '') sign = $1 if zone.include?(':') hour, min, sec, = zone.split(':') elsif zone.include?(',') || zone.include?('.') hour, fr, = zone.split(/[,.]/) min = Rational(fr.to_i, 10**fr.size) * 60 else case zone.size when 3 hour = zone[0,1] min = zone[1,2] else hour = zone[0,2] min = zone[2,2] sec = zone[4,2] end end offset = hour.to_i * 3600 + min.to_i * 60 + sec.to_i offset *= -1 if sign == '-' end offset end end class DateTime < Date def strftime(fmt='%FT%T%:z') super(fmt) end def self._strptime(str, fmt='%FT%T%z') super(str, fmt) end =begin def iso8601_timediv(n) # :nodoc: strftime('T%T' + if n < 1 '' else '.%0*d' % [n, (sec_fraction / SECONDS_IN_DAY / (10**n)).round] end + '%:z') end private :iso8601_timediv def iso8601(n=0) super() + iso8601_timediv(n) end def rfc3339(n=0) iso8601(n) end def jisx0301(n=0) super() + iso8601_timediv(n) end =end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/optparse/version.rb
tools/jruby-1.5.1/lib/ruby/1.8/optparse/version.rb
# OptionParser internal utility class << OptionParser def show_version(*pkg) progname = ARGV.options.program_name result = false show = proc do |klass, cname, version| str = "#{progname}" unless klass == ::Object and cname == :VERSION version = version.join(".") if Array === version str << ": #{klass}" unless klass == Object str << " version #{version}" end [:Release, :RELEASE].find do |rel| if klass.const_defined?(rel) str << " (#{klass.const_get(rel)})" end end puts str result = true end if pkg.size == 1 and pkg[0] == "all" self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version| unless cname[1] == ?e and klass.const_defined?(:Version) show.call(klass, cname.intern, version) end end else pkg.each do |pkg| begin pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)} v = case when pkg.const_defined?(:Version) pkg.const_get(n = :Version) when pkg.const_defined?(:VERSION) pkg.const_get(n = :VERSION) else n = nil "unknown" end show.call(pkg, n, v) rescue NameError end end end result end def each_const(path, klass = ::Object) path.split(/::|\//).inject(klass) do |klass, name| raise NameError, path unless Module === klass klass.constants.grep(/#{name}/i) do |c| klass.const_defined?(c) or next c = klass.const_get(c) end end end def search_const(klass, name) klasses = [klass] while klass = klasses.shift klass.constants.each do |cname| klass.const_defined?(cname) or next const = klass.const_get(cname) yield klass, cname, const if name === cname klasses << const if Module === const and const != ::Object end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/optparse/time.rb
tools/jruby-1.5.1/lib/ruby/1.8/optparse/time.rb
require 'optparse' require 'time' OptionParser.accept(Time) do |s,| begin (Time.httpdate(s) rescue Time.parse(s)) if s rescue raise OptionParser::InvalidArgument, s end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/optparse/uri.rb
tools/jruby-1.5.1/lib/ruby/1.8/optparse/uri.rb
# -*- ruby -*- require 'optparse' require 'uri' OptionParser.accept(URI) {|s,| URI.parse(s) if s}
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/optparse/shellwords.rb
tools/jruby-1.5.1/lib/ruby/1.8/optparse/shellwords.rb
# -*- ruby -*- require 'shellwords' require 'optparse' OptionParser.accept(Shellwords) {|s,| Shellwords.shellwords(s)}
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/optparse/date.rb
tools/jruby-1.5.1/lib/ruby/1.8/optparse/date.rb
require 'optparse' require 'date' OptionParser.accept(DateTime) do |s,| begin DateTime.parse(s) if s rescue ArgumentError raise OptionParser::InvalidArgument, s end end OptionParser.accept(Date) do |s,| begin Date.parse(s) if s rescue ArgumentError raise OptionParser::InvalidArgument, s end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/element.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/element.rb
# SOAP4R - SOAP elements library # Copyright (C) 2000, 2001, 2003-2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' require 'soap/baseData' module SOAP ### ## SOAP elements # module SOAPEnvelopeElement; end class SOAPFault < SOAPStruct include SOAPEnvelopeElement include SOAPCompoundtype public def faultcode self['faultcode'] end def faultstring self['faultstring'] end def faultactor self['faultactor'] end def detail self['detail'] end def faultcode=(rhs) self['faultcode'] = rhs end def faultstring=(rhs) self['faultstring'] = rhs end def faultactor=(rhs) self['faultactor'] = rhs end def detail=(rhs) self['detail'] = rhs end def initialize(faultcode = nil, faultstring = nil, faultactor = nil, detail = nil) super(EleFaultName) @elename = EleFaultName @encodingstyle = EncodingNamespace if faultcode self.faultcode = faultcode self.faultstring = faultstring self.faultactor = faultactor self.detail = detail self.faultcode.elename = EleFaultCodeName if self.faultcode self.faultstring.elename = EleFaultStringName if self.faultstring self.faultactor.elename = EleFaultActorName if self.faultactor self.detail.elename = EleFaultDetailName if self.detail end faultcode.parent = self if faultcode faultstring.parent = self if faultstring faultactor.parent = self if faultactor detail.parent = self if detail end def encode(generator, ns, attrs = {}) SOAPGenerator.assign_ns(attrs, ns, EnvelopeNamespace) SOAPGenerator.assign_ns(attrs, ns, EncodingNamespace) attrs[ns.name(AttrEncodingStyleName)] = EncodingNamespace name = ns.name(@elename) generator.encode_tag(name, attrs) yield(self.faultcode) yield(self.faultstring) yield(self.faultactor) yield(self.detail) if self.detail generator.encode_tag_end(name, true) end end class SOAPBody < SOAPStruct include SOAPEnvelopeElement def initialize(data = nil, is_fault = false) super(nil) @elename = EleBodyName @encodingstyle = nil if data if data.respond_to?(:elename) add(data.elename.name, data) else data.to_a.each do |datum| add(datum.elename.name, datum) end end end @is_fault = is_fault end def encode(generator, ns, attrs = {}) name = ns.name(@elename) generator.encode_tag(name, attrs) if @is_fault yield(@data) else @data.each do |data| yield(data) end end generator.encode_tag_end(name, true) end def root_node @data.each do |node| if node.root == 1 return node end end # No specified root... @data.each do |node| if node.root != 0 return node end end raise Parser::FormatDecodeError.new('no root element') end end class SOAPHeaderItem < XSD::NSDBase include SOAPEnvelopeElement include SOAPCompoundtype public attr_accessor :element attr_accessor :mustunderstand attr_accessor :encodingstyle def initialize(element, mustunderstand = true, encodingstyle = nil) super() @type = nil @element = element @mustunderstand = mustunderstand @encodingstyle = encodingstyle element.parent = self if element end def encode(generator, ns, attrs = {}) attrs.each do |key, value| @element.extraattr[key] = value end @element.extraattr[ns.name(AttrMustUnderstandName)] = (@mustunderstand ? '1' : '0') if @encodingstyle @element.extraattr[ns.name(AttrEncodingStyleName)] = @encodingstyle end @element.encodingstyle = @encodingstyle if !@element.encodingstyle yield(@element) end end class SOAPHeader < SOAPStruct include SOAPEnvelopeElement def initialize super(nil) @elename = EleHeaderName @encodingstyle = nil end def encode(generator, ns, attrs = {}) name = ns.name(@elename) generator.encode_tag(name, attrs) @data.each do |data| yield(data) end generator.encode_tag_end(name, true) end def add(name, value) mu = (value.extraattr[AttrMustUnderstandName] == '1') encstyle = value.extraattr[AttrEncodingStyleName] item = SOAPHeaderItem.new(value, mu, encstyle) super(name, item) end def length @data.length end alias size length end class SOAPEnvelope < XSD::NSDBase include SOAPEnvelopeElement include SOAPCompoundtype attr_reader :header attr_reader :body attr_reader :external_content def initialize(header = nil, body = nil) super() @type = nil @elename = EleEnvelopeName @encodingstyle = nil @header = header @body = body @external_content = {} header.parent = self if header body.parent = self if body end def header=(header) header.parent = self @header = header end def body=(body) body.parent = self @body = body end def encode(generator, ns, attrs = {}) SOAPGenerator.assign_ns(attrs, ns, elename.namespace, SOAPNamespaceTag) name = ns.name(@elename) generator.encode_tag(name, attrs) yield(@header) if @header and @header.length > 0 yield(@body) generator.encode_tag_end(name, true) end def to_ary [header, body] end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/netHttpClient.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/netHttpClient.rb
# SOAP4R - net/http wrapper # Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'net/http' module SOAP class NetHttpClient SSLEnabled = begin require 'net/https' true rescue LoadError false end attr_reader :proxy attr_accessor :no_proxy attr_accessor :debug_dev attr_accessor :ssl_config # ignored for now. attr_accessor :protocol_version # ignored for now. attr_accessor :connect_timeout attr_accessor :send_timeout # ignored for now. attr_accessor :receive_timeout def initialize(proxy = nil, agent = nil) @proxy = proxy ? URI.parse(proxy) : nil @agent = agent @debug_dev = nil @session_manager = SessionManager.new @no_proxy = @ssl_config = @protocol_version = nil @connect_timeout = @send_timeout = @receive_timeout = nil end def test_loopback_response raise NotImplementedError.new("not supported for now") end def proxy=(proxy) if proxy.nil? @proxy = nil else if proxy.is_a?(URI) @proxy = proxy else @proxy = URI.parse(proxy) end if @proxy.scheme == nil or @proxy.scheme.downcase != 'http' or @proxy.host == nil or @proxy.port == nil raise ArgumentError.new("unsupported proxy `#{proxy}'") end end reset_all @proxy end def set_basic_auth(uri, user_id, passwd) # net/http does not handle url. @basic_auth = [user_id, passwd] raise NotImplementedError.new("basic_auth is not supported under soap4r + net/http.") end def set_cookie_store(filename) raise NotImplementedError.new end def save_cookie_store(filename) raise NotImplementedError.new end def reset(url) # no persistent connection. ignored. end def reset_all # no persistent connection. ignored. end def post(url, req_body, header = {}) unless url.is_a?(URI) url = URI.parse(url) end extra = header.dup extra['User-Agent'] = @agent if @agent res = start(url) { |http| http.post(url.request_uri, req_body, extra) } Response.new(res) end def get_content(url, header = {}) unless url.is_a?(URI) url = URI.parse(url) end extra = header.dup extra['User-Agent'] = @agent if @agent res = start(url) { |http| http.get(url.request_uri, extra) } res.body end private def start(url) http = create_connection(url) response = nil http.start { |worker| response = yield(worker) worker.finish } @debug_dev << response.body if @debug_dev response end def create_connection(url) proxy_host = proxy_port = nil unless no_proxy?(url) proxy_host = @proxy.host proxy_port = @proxy.port end http = Net::HTTP::Proxy(proxy_host, proxy_port).new(url.host, url.port) if http.respond_to?(:set_debug_output) http.set_debug_output(@debug_dev) end http.open_timeout = @connect_timeout if @connect_timeout http.read_timeout = @receive_timeout if @receive_timeout case url when URI::HTTPS if SSLEnabled http.use_ssl = true else raise RuntimeError.new("Cannot connect to #{url} (OpenSSL is not installed.)") end when URI::HTTP # OK else raise RuntimeError.new("Cannot connect to #{url} (Not HTTP.)") end http end NO_PROXY_HOSTS = ['localhost'] def no_proxy?(uri) if !@proxy or NO_PROXY_HOSTS.include?(uri.host) return true end if @no_proxy @no_proxy.scan(/([^:,]*)(?::(\d+))?/) do |host, port| if /(\A|\.)#{Regexp.quote(host)}\z/i =~ uri.host && (!port || uri.port == port.to_i) return true end end else false end end class SessionManager attr_accessor :connect_timeout attr_accessor :send_timeout attr_accessor :receive_timeout end class Response attr_reader :content attr_reader :status attr_reader :reason attr_reader :contenttype def initialize(res) @status = res.code.to_i @reason = res.message @contenttype = res['content-type'] @content = res.body end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping.rb
# SOAP4R - Ruby type mapping utility. # Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'soap/mapping/mapping' require 'soap/mapping/registry'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/wsdlDriver.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/wsdlDriver.rb
# SOAP4R - SOAP WSDL driver # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/parser' require 'wsdl/importer' require 'xsd/qname' require 'xsd/codegen/gensupport' require 'soap/mapping/wsdlencodedregistry' require 'soap/mapping/wsdlliteralregistry' require 'soap/rpc/driver' require 'wsdl/soap/methodDefCreator' module SOAP class WSDLDriverFactory class FactoryError < StandardError; end attr_reader :wsdl def initialize(wsdl) @wsdl = import(wsdl) @methoddefcreator = WSDL::SOAP::MethodDefCreator.new(@wsdl) end def inspect "#<#{self.class}:#{@wsdl.name}>" end def create_rpc_driver(servicename = nil, portname = nil) port = find_port(servicename, portname) drv = SOAP::RPC::Driver.new(port.soap_address.location) init_driver(drv, port) add_operation(drv, port) drv end # depricated old interface def create_driver(servicename = nil, portname = nil) warn("WSDLDriverFactory#create_driver is depricated. Use create_rpc_driver instead.") port = find_port(servicename, portname) WSDLDriver.new(@wsdl, port, nil) end # Backward compatibility. alias createDriver create_driver private def find_port(servicename = nil, portname = nil) service = port = nil if servicename service = @wsdl.service( XSD::QName.new(@wsdl.targetnamespace, servicename)) else service = @wsdl.services[0] end if service.nil? raise FactoryError.new("service #{servicename} not found in WSDL") end if portname port = service.ports[XSD::QName.new(@wsdl.targetnamespace, portname)] if port.nil? raise FactoryError.new("port #{portname} not found in WSDL") end else port = service.ports.find { |port| !port.soap_address.nil? } if port.nil? raise FactoryError.new("no ports have soap:address") end end if port.soap_address.nil? raise FactoryError.new("soap:address element not found in WSDL") end port end def init_driver(drv, port) wsdl_elements = @wsdl.collect_elements wsdl_types = @wsdl.collect_complextypes + @wsdl.collect_simpletypes rpc_decode_typemap = wsdl_types + @wsdl.soap_rpc_complextypes(port.find_binding) drv.proxy.mapping_registry = Mapping::WSDLEncodedRegistry.new(rpc_decode_typemap) drv.proxy.literal_mapping_registry = Mapping::WSDLLiteralRegistry.new(wsdl_types, wsdl_elements) end def add_operation(drv, port) port.find_binding.operations.each do |op_bind| op_name = op_bind.soapoperation_name soapaction = op_bind.soapaction || '' orgname = op_name.name name = XSD::CodeGen::GenSupport.safemethodname(orgname) param_def = create_param_def(op_bind) opt = { :request_style => op_bind.soapoperation_style, :response_style => op_bind.soapoperation_style, :request_use => op_bind.input.soapbody_use, :response_use => op_bind.output.soapbody_use, :elementformdefault => false, :attributeformdefault => false } if op_bind.soapoperation_style == :rpc drv.add_rpc_operation(op_name, soapaction, name, param_def, opt) else drv.add_document_operation(soapaction, name, param_def, opt) end if orgname != name and orgname.capitalize == name.capitalize ::SOAP::Mapping.define_singleton_method(drv, orgname) do |*arg| __send__(name, *arg) end end end end def import(location) WSDL::Importer.import(location) end def create_param_def(op_bind) op = op_bind.find_operation if op_bind.soapoperation_style == :rpc param_def = @methoddefcreator.collect_rpcparameter(op) else param_def = @methoddefcreator.collect_documentparameter(op) end # the first element of typedef in param_def is a String like # "::SOAP::SOAPStruct". turn this String to a class. param_def.collect { |io, name, typedef| typedef[0] = Mapping.class_from_name(typedef[0]) [io, name, typedef] } end def partqname(part) if part.type part.type else part.element end end def param_def(type, name, klass, partqname) [type, name, [klass, partqname.namespace, partqname.name]] end def filter_parts(partsdef, partssource) parts = partsdef.split(/\s+/) partssource.find_all { |part| parts.include?(part.name) } end end class WSDLDriver class << self if RUBY_VERSION >= "1.7.0" def __attr_proxy(symbol, assignable = false) name = symbol.to_s define_method(name) { @servant.__send__(name) } if assignable aname = name + '=' define_method(aname) { |rhs| @servant.__send__(aname, rhs) } end end else def __attr_proxy(symbol, assignable = false) name = symbol.to_s module_eval <<-EOS def #{name} @servant.#{name} end EOS if assignable module_eval <<-EOS def #{name}=(value) @servant.#{name} = value end EOS end end end end __attr_proxy :options __attr_proxy :headerhandler __attr_proxy :streamhandler __attr_proxy :test_loopback_response __attr_proxy :endpoint_url, true __attr_proxy :mapping_registry, true # for RPC unmarshal __attr_proxy :wsdl_mapping_registry, true # for RPC marshal __attr_proxy :default_encodingstyle, true __attr_proxy :generate_explicit_type, true __attr_proxy :allow_unqualified_element, true def httpproxy @servant.options["protocol.http.proxy"] end def httpproxy=(httpproxy) @servant.options["protocol.http.proxy"] = httpproxy end def wiredump_dev @servant.options["protocol.http.wiredump_dev"] end def wiredump_dev=(wiredump_dev) @servant.options["protocol.http.wiredump_dev"] = wiredump_dev end def mandatorycharset @servant.options["protocol.mandatorycharset"] end def mandatorycharset=(mandatorycharset) @servant.options["protocol.mandatorycharset"] = mandatorycharset end def wiredump_file_base @servant.options["protocol.wiredump_file_base"] end def wiredump_file_base=(wiredump_file_base) @servant.options["protocol.wiredump_file_base"] = wiredump_file_base end def initialize(wsdl, port, logdev) @servant = Servant__.new(self, wsdl, port, logdev) end def inspect "#<#{self.class}:#{@servant.port.name}>" end def reset_stream @servant.reset_stream end # Backward compatibility. alias generateEncodeType= generate_explicit_type= class Servant__ include SOAP attr_reader :options attr_reader :port attr_accessor :soapaction attr_accessor :default_encodingstyle attr_accessor :allow_unqualified_element attr_accessor :generate_explicit_type attr_accessor :mapping_registry attr_accessor :wsdl_mapping_registry def initialize(host, wsdl, port, logdev) @host = host @wsdl = wsdl @port = port @logdev = logdev @soapaction = nil @options = setup_options @default_encodingstyle = nil @allow_unqualified_element = nil @generate_explicit_type = false @mapping_registry = nil # for rpc unmarshal @wsdl_mapping_registry = nil # for rpc marshal @wiredump_file_base = nil @mandatorycharset = nil @wsdl_elements = @wsdl.collect_elements @wsdl_types = @wsdl.collect_complextypes + @wsdl.collect_simpletypes @rpc_decode_typemap = @wsdl_types + @wsdl.soap_rpc_complextypes(port.find_binding) @wsdl_mapping_registry = Mapping::WSDLEncodedRegistry.new( @rpc_decode_typemap) @doc_mapper = Mapping::WSDLLiteralRegistry.new( @wsdl_types, @wsdl_elements) endpoint_url = @port.soap_address.location # Convert a map which key is QName, to a Hash which key is String. @operation = {} @port.inputoperation_map.each do |op_name, op_info| orgname = op_name.name name = XSD::CodeGen::GenSupport.safemethodname(orgname) @operation[name] = @operation[orgname] = op_info add_method_interface(op_info) end @proxy = ::SOAP::RPC::Proxy.new(endpoint_url, @soapaction, @options) end def inspect "#<#{self.class}:#{@proxy.inspect}>" end def endpoint_url @proxy.endpoint_url end def endpoint_url=(endpoint_url) @proxy.endpoint_url = endpoint_url end def headerhandler @proxy.headerhandler end def streamhandler @proxy.streamhandler end def test_loopback_response @proxy.test_loopback_response end def reset_stream @proxy.reset_stream end def rpc_call(name, *values) set_wiredump_file_base(name) unless op_info = @operation[name] raise RuntimeError, "method: #{name} not defined" end req_header = create_request_header req_body = create_request_body(op_info, *values) reqopt = create_options({ :soapaction => op_info.soapaction || @soapaction}) resopt = create_options({ :decode_typemap => @rpc_decode_typemap}) env = @proxy.route(req_header, req_body, reqopt, resopt) raise EmptyResponseError unless env receive_headers(env.header) begin @proxy.check_fault(env.body) rescue ::SOAP::FaultError => e Mapping.fault2exception(e) end ret = env.body.response ? Mapping.soap2obj(env.body.response, @mapping_registry) : nil if env.body.outparams outparams = env.body.outparams.collect { |outparam| Mapping.soap2obj(outparam) } return [ret].concat(outparams) else return ret end end # req_header: [[element, mustunderstand, encodingstyle(QName/String)], ...] # req_body: SOAPBasetype/SOAPCompoundtype def document_send(name, header_obj, body_obj) set_wiredump_file_base(name) unless op_info = @operation[name] raise RuntimeError, "method: #{name} not defined" end req_header = header_obj ? header_from_obj(header_obj, op_info) : nil req_body = body_from_obj(body_obj, op_info) opt = create_options({ :soapaction => op_info.soapaction || @soapaction, :decode_typemap => @wsdl_types}) env = @proxy.invoke(req_header, req_body, opt) raise EmptyResponseError unless env if env.body.fault raise ::SOAP::FaultError.new(env.body.fault) end res_body_obj = env.body.response ? Mapping.soap2obj(env.body.response, @mapping_registry) : nil return env.header, res_body_obj end private def create_options(hash = nil) opt = {} opt[:default_encodingstyle] = @default_encodingstyle opt[:allow_unqualified_element] = @allow_unqualified_element opt[:generate_explicit_type] = @generate_explicit_type opt.update(hash) if hash opt end def set_wiredump_file_base(name) if @wiredump_file_base @proxy.set_wiredump_file_base(@wiredump_file_base + "_#{name}") end end def create_request_header headers = @proxy.headerhandler.on_outbound if headers.empty? nil else h = SOAPHeader.new headers.each do |header| h.add(header.elename.name, header) end h end end def receive_headers(headers) @proxy.headerhandler.on_inbound(headers) if headers end def create_request_body(op_info, *values) method = create_method_struct(op_info, *values) SOAPBody.new(method) end def create_method_struct(op_info, *params) parts_names = op_info.bodyparts.collect { |part| part.name } obj = create_method_obj(parts_names, params) method = Mapping.obj2soap(obj, @wsdl_mapping_registry, op_info.op_name) if method.members.size != parts_names.size new_method = SOAPStruct.new method.each do |key, value| if parts_names.include?(key) new_method.add(key, value) end end method = new_method end method.elename = op_info.op_name method.type = XSD::QName.new # Request should not be typed. method end def create_method_obj(names, params) o = Object.new idx = 0 while idx < params.length o.instance_variable_set('@' + names[idx], params[idx]) idx += 1 end o end def header_from_obj(obj, op_info) if obj.is_a?(SOAPHeader) obj elsif op_info.headerparts.empty? if obj.nil? nil else raise RuntimeError.new("no header definition in schema: #{obj}") end elsif op_info.headerparts.size == 1 part = op_info.headerparts[0] header = SOAPHeader.new() header.add(headeritem_from_obj(obj, part.element || part.eletype)) header else header = SOAPHeader.new() op_info.headerparts.each do |part| child = Mapping.get_attribute(obj, part.name) ele = headeritem_from_obj(child, part.element || part.eletype) header.add(part.name, ele) end header end end def headeritem_from_obj(obj, name) if obj.nil? SOAPElement.new(name) elsif obj.is_a?(SOAPHeaderItem) obj else Mapping.obj2soap(obj, @doc_mapper, name) end end def body_from_obj(obj, op_info) if obj.is_a?(SOAPBody) obj elsif op_info.bodyparts.empty? if obj.nil? nil else raise RuntimeError.new("no body found in schema") end elsif op_info.bodyparts.size == 1 part = op_info.bodyparts[0] ele = bodyitem_from_obj(obj, part.element || part.type) SOAPBody.new(ele) else body = SOAPBody.new op_info.bodyparts.each do |part| child = Mapping.get_attribute(obj, part.name) ele = bodyitem_from_obj(child, part.element || part.type) body.add(ele.elename.name, ele) end body end end def bodyitem_from_obj(obj, name) if obj.nil? SOAPElement.new(name) elsif obj.is_a?(SOAPElement) obj else Mapping.obj2soap(obj, @doc_mapper, name) end end def add_method_interface(op_info) name = XSD::CodeGen::GenSupport.safemethodname(op_info.op_name.name) orgname = op_info.op_name.name parts_names = op_info.bodyparts.collect { |part| part.name } case op_info.style when :document if orgname != name and orgname.capitalize == name.capitalize add_document_method_interface(orgname, parts_names) end add_document_method_interface(name, parts_names) when :rpc if orgname != name and orgname.capitalize == name.capitalize add_rpc_method_interface(orgname, parts_names) end add_rpc_method_interface(name, parts_names) else raise RuntimeError.new("unknown style: #{op_info.style}") end end def add_rpc_method_interface(name, parts_names) ::SOAP::Mapping.define_singleton_method(@host, name) do |*arg| unless arg.size == parts_names.size raise ArgumentError.new( "wrong number of arguments (#{arg.size} for #{parts_names.size})") end @servant.rpc_call(name, *arg) end @host.method(name) end def add_document_method_interface(name, parts_names) ::SOAP::Mapping.define_singleton_method(@host, name) do |h, b| @servant.document_send(name, h, b) end @host.method(name) end def setup_options if opt = Property.loadproperty(::SOAP::PropertyName) opt = opt["client"] end opt ||= Property.new opt.add_hook("protocol.mandatorycharset") do |key, value| @mandatorycharset = value end opt.add_hook("protocol.wiredump_file_base") do |key, value| @wiredump_file_base = value end opt["protocol.http.charset"] ||= XSD::Charset.xml_encoding_label opt["protocol.http.proxy"] ||= Env::HTTP_PROXY opt["protocol.http.no_proxy"] ||= Env::NO_PROXY opt end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/streamHandler.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/streamHandler.rb
# SOAP4R - Stream handler. # Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'soap/soap' require 'soap/httpconfigloader' begin require 'stringio' require 'zlib' rescue LoadError warn("Loading stringio or zlib failed. No gzipped response support.") if $DEBUG end module SOAP class StreamHandler RUBY_VERSION_STRING = "ruby #{ RUBY_VERSION } (#{ RUBY_RELEASE_DATE }) [#{ RUBY_PLATFORM }]" class ConnectionData attr_accessor :send_string attr_accessor :send_contenttype attr_accessor :receive_string attr_accessor :receive_contenttype attr_accessor :is_fault attr_accessor :soapaction def initialize(send_string = nil) @send_string = send_string @send_contenttype = nil @receive_string = nil @receive_contenttype = nil @is_fault = false @soapaction = nil end end def self.parse_media_type(str) if /^#{ MediaType }(?:\s*;\s*charset=([^"]+|"[^"]+"))?$/i !~ str return nil end charset = $1 charset.gsub!(/"/, '') if charset charset || 'us-ascii' end def self.create_media_type(charset) "#{ MediaType }; charset=#{ charset }" end end class HTTPStreamHandler < StreamHandler include SOAP begin require 'http-access2' if HTTPAccess2::VERSION < "2.0" raise LoadError.new("http-access/2.0 or later is required.") end Client = HTTPAccess2::Client RETRYABLE = true rescue LoadError warn("Loading http-access2 failed. Net/http is used.") if $DEBUG require 'soap/netHttpClient' Client = SOAP::NetHttpClient RETRYABLE = false end public attr_reader :client attr_accessor :wiredump_file_base MAX_RETRY_COUNT = 10 # [times] def initialize(options) super() @client = Client.new(nil, "SOAP4R/#{ Version }") @wiredump_file_base = nil @charset = @wiredump_dev = nil @options = options set_options @client.debug_dev = @wiredump_dev @cookie_store = nil @accept_encoding_gzip = false end def test_loopback_response @client.test_loopback_response end def accept_encoding_gzip=(allow) @accept_encoding_gzip = allow end def inspect "#<#{self.class}>" end def send(endpoint_url, conn_data, soapaction = nil, charset = @charset) conn_data.soapaction ||= soapaction # for backward conpatibility send_post(endpoint_url, conn_data, charset) end def reset(endpoint_url = nil) if endpoint_url.nil? @client.reset_all else @client.reset(endpoint_url) end @client.save_cookie_store if @cookie_store end private def set_options HTTPConfigLoader.set_options(@client, @options) @charset = @options["charset"] || XSD::Charset.xml_encoding_label @options.add_hook("charset") do |key, value| @charset = value end @wiredump_dev = @options["wiredump_dev"] @options.add_hook("wiredump_dev") do |key, value| @wiredump_dev = value @client.debug_dev = @wiredump_dev end set_cookie_store_file(@options["cookie_store_file"]) @options.add_hook("cookie_store_file") do |key, value| set_cookie_store_file(value) end ssl_config = @options["ssl_config"] basic_auth = @options["basic_auth"] @options.lock(true) ssl_config.unlock basic_auth.unlock end def set_cookie_store_file(value) value = nil if value and value.empty? @cookie_store = value @client.set_cookie_store(@cookie_store) if @cookie_store end def send_post(endpoint_url, conn_data, charset) conn_data.send_contenttype ||= StreamHandler.create_media_type(charset) if @wiredump_file_base filename = @wiredump_file_base + '_request.xml' f = File.open(filename, "w") f << conn_data.send_string f.close end extra = {} extra['Content-Type'] = conn_data.send_contenttype extra['SOAPAction'] = "\"#{ conn_data.soapaction }\"" extra['Accept-Encoding'] = 'gzip' if send_accept_encoding_gzip? send_string = conn_data.send_string @wiredump_dev << "Wire dump:\n\n" if @wiredump_dev begin retry_count = 0 while true res = @client.post(endpoint_url, send_string, extra) if RETRYABLE and HTTP::Status.redirect?(res.status) retry_count += 1 if retry_count >= MAX_RETRY_COUNT raise HTTPStreamError.new("redirect count exceeded") end endpoint_url = res.header["location"][0] puts "redirected to #{endpoint_url}" if $DEBUG else break end end rescue @client.reset(endpoint_url) raise end @wiredump_dev << "\n\n" if @wiredump_dev receive_string = res.content if @wiredump_file_base filename = @wiredump_file_base + '_response.xml' f = File.open(filename, "w") f << receive_string f.close end case res.status when 405 raise PostUnavailableError.new("#{ res.status }: #{ res.reason }") when 200, 500 # Nothing to do. else raise HTTPStreamError.new("#{ res.status }: #{ res.reason }") end if res.respond_to?(:header) and !res.header['content-encoding'].empty? and res.header['content-encoding'][0].downcase == 'gzip' receive_string = decode_gzip(receive_string) end conn_data.receive_string = receive_string conn_data.receive_contenttype = res.contenttype conn_data end def send_accept_encoding_gzip? @accept_encoding_gzip and defined?(::Zlib) end def decode_gzip(instring) unless send_accept_encoding_gzip? raise HTTPStreamError.new("Gzipped response content.") end begin gz = Zlib::GzipReader.new(StringIO.new(instring)) gz.read ensure gz.close end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/processor.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/processor.rb
# SOAP4R - marshal/unmarshal interface. # Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/datatypes' require 'soap/soap' require 'soap/element' require 'soap/parser' require 'soap/generator' require 'soap/encodingstyle/soapHandler' require 'soap/encodingstyle/literalHandler' require 'soap/encodingstyle/aspDotNetHandler' module SOAP module Processor @@default_parser_option = {} class << self public def marshal(env, opt = {}, io = nil) generator = create_generator(opt) marshalled_str = generator.generate(env, io) unless env.external_content.empty? opt[:external_content] = env.external_content end marshalled_str end def unmarshal(stream, opt = {}) parser = create_parser(opt) parser.parse(stream) end def default_parser_option=(rhs) @@default_parser_option = rhs end def default_parser_option @@default_parser_option end private def create_generator(opt) SOAPGenerator.new(opt) end def create_parser(opt) if opt.empty? opt = @@default_parser_option end ::SOAP::Parser.new(opt) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/parser.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/parser.rb
# SOAP4R - SOAP XML Instance Parser library. # Copyright (C) 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/ns' require 'xsd/xmlparser' require 'soap/soap' require 'soap/baseData' require 'soap/encodingstyle/handler' module SOAP class Parser include SOAP class ParseError < Error; end class FormatDecodeError < ParseError; end class UnexpectedElementError < ParseError; end private class ParseFrame attr_reader :node attr_reader :name attr_reader :ns, :encodingstyle class NodeContainer def initialize(node) @node = node end def node @node end def replace_node(node) @node = node end end public def initialize(ns, name, node, encodingstyle) @ns = ns @name = name self.node = node @encodingstyle = encodingstyle end def node=(node) @node = NodeContainer.new(node) end end public attr_accessor :envelopenamespace attr_accessor :default_encodingstyle attr_accessor :decode_typemap attr_accessor :allow_unqualified_element def initialize(opt = {}) @opt = opt @parser = XSD::XMLParser.create_parser(self, opt) @parsestack = nil @lastnode = nil @handlers = {} @envelopenamespace = opt[:envelopenamespace] || EnvelopeNamespace @default_encodingstyle = opt[:default_encodingstyle] || EncodingNamespace @decode_typemap = opt[:decode_typemap] || nil @allow_unqualified_element = opt[:allow_unqualified_element] || false end def charset @parser.charset end def parse(string_or_readable) @parsestack = [] @lastnode = nil @handlers.each do |uri, handler| handler.decode_prologue end @parser.do_parse(string_or_readable) unless @parsestack.empty? raise FormatDecodeError.new("Unbalanced tag in XML.") end @handlers.each do |uri, handler| handler.decode_epilogue end @lastnode end def start_element(name, attrs) lastframe = @parsestack.last ns = parent = parent_encodingstyle = nil if lastframe ns = lastframe.ns.clone_ns parent = lastframe.node parent_encodingstyle = lastframe.encodingstyle else ns = XSD::NS.new parent = ParseFrame::NodeContainer.new(nil) parent_encodingstyle = nil end attrs = XSD::XMLParser.filter_ns(ns, attrs) encodingstyle = find_encodingstyle(ns, attrs) # Children's encodingstyle is derived from its parent. if encodingstyle.nil? if parent.node.is_a?(SOAPHeader) encodingstyle = LiteralNamespace else encodingstyle = parent_encodingstyle || @default_encodingstyle end end node = decode_tag(ns, name, attrs, parent, encodingstyle) @parsestack << ParseFrame.new(ns, name, node, encodingstyle) end def characters(text) lastframe = @parsestack.last if lastframe # Need not to be cloned because character does not have attr. decode_text(lastframe.ns, text, lastframe.encodingstyle) else # Ignore Text outside of SOAP Envelope. p text if $DEBUG end end def end_element(name) lastframe = @parsestack.pop unless name == lastframe.name raise UnexpectedElementError.new("Closing element name '#{ name }' does not match with opening element '#{ lastframe.name }'.") end decode_tag_end(lastframe.ns, lastframe.node, lastframe.encodingstyle) @lastnode = lastframe.node.node end private def find_encodingstyle(ns, attrs) attrs.each do |key, value| if (ns.compare(@envelopenamespace, AttrEncodingStyle, key)) return value end end nil end def decode_tag(ns, name, attrs, parent, encodingstyle) ele = ns.parse(name) # Envelope based parsing. if ((ele.namespace == @envelopenamespace) || (@allow_unqualified_element && ele.namespace.nil?)) o = decode_soap_envelope(ns, ele, attrs, parent) return o if o end # Encoding based parsing. handler = find_handler(encodingstyle) if handler return handler.decode_tag(ns, ele, attrs, parent) else raise FormatDecodeError.new("Unknown encodingStyle: #{ encodingstyle }.") end end def decode_tag_end(ns, node, encodingstyle) return unless encodingstyle handler = find_handler(encodingstyle) if handler return handler.decode_tag_end(ns, node) else raise FormatDecodeError.new("Unknown encodingStyle: #{ encodingstyle }.") end end def decode_text(ns, text, encodingstyle) handler = find_handler(encodingstyle) if handler handler.decode_text(ns, text) else # How should I do? end end def decode_soap_envelope(ns, ele, attrs, parent) o = nil if ele.name == EleEnvelope o = SOAPEnvelope.new if ext = @opt[:external_content] ext.each do |k, v| o.external_content[k] = v end end elsif ele.name == EleHeader unless parent.node.is_a?(SOAPEnvelope) raise FormatDecodeError.new("Header should be a child of Envelope.") end o = SOAPHeader.new parent.node.header = o elsif ele.name == EleBody unless parent.node.is_a?(SOAPEnvelope) raise FormatDecodeError.new("Body should be a child of Envelope.") end o = SOAPBody.new parent.node.body = o elsif ele.name == EleFault unless parent.node.is_a?(SOAPBody) raise FormatDecodeError.new("Fault should be a child of Body.") end o = SOAPFault.new parent.node.fault = o end o end def find_handler(encodingstyle) unless @handlers.key?(encodingstyle) handler_factory = SOAP::EncodingStyle::Handler.handler(encodingstyle) || SOAP::EncodingStyle::Handler.handler(EncodingNamespace) handler = handler_factory.new(@parser.charset) handler.decode_typemap = @decode_typemap handler.decode_prologue @handlers[encodingstyle] = handler end @handlers[encodingstyle] end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/attachment.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/attachment.rb
# soap/attachment.rb: SOAP4R - SwA implementation. # Copyright (C) 2002, 2003 Jamie Herre and NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'soap/baseData' require 'soap/mapping' module SOAP class SOAPAttachment < SOAPExternalReference attr_reader :data def initialize(value) super() @data = value end private def external_contentid @data.contentid end end class Attachment attr_reader :io attr_accessor :contenttype def initialize(string_or_readable = nil) @string_or_readable = string_or_readable @contenttype = "application/octet-stream" @contentid = nil end def contentid @contentid ||= Attachment.contentid(self) end def contentid=(contentid) @contentid = contentid end def mime_contentid '<' + contentid + '>' end def content if @content == nil and @string_or_readable != nil @content = @string_or_readable.respond_to?(:read) ? @string_or_readable.read : @string_or_readable end @content end def to_s content end def write(out) out.write(content) end def save(filename) File.open(filename, "wb") do |f| write(f) end end def self.contentid(obj) # this needs to be fixed [obj.__id__.to_s, Process.pid.to_s].join('.') end def self.mime_contentid(obj) '<' + contentid(obj) + '>' end end module Mapping class AttachmentFactory < SOAP::Mapping::Factory def obj2soap(soap_class, obj, info, map) soap_obj = soap_class.new(obj) mark_marshalled_obj(obj, soap_obj) soap_obj end def soap2obj(obj_class, node, info, map) obj = node.data mark_unmarshalled_obj(node, obj) return true, obj end end DefaultRegistry.add(::SOAP::Attachment, ::SOAP::SOAPAttachment, AttachmentFactory.new, nil) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/property.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/property.rb
# soap/property.rb: SOAP4R - Property implementation. # Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. module SOAP # Property stream format: # # line separator is \r?\n. 1 line per a property. # line which begins with '#' is a comment line. empty line is ignored, too. # key/value separator is ':' or '='. # '\' as escape character. but line separator cannot be escaped. # \s at the head/tail of key/value are trimmed. # # '[' + key + ']' indicates property section. for example, # # [aaa.bbb] # ccc = ddd # eee.fff = ggg # [] # aaa.hhh = iii # # is the same as; # # aaa.bbb.ccc = ddd # aaa.bbb.eee.fff = ggg # aaa.hhh = iii # class Property FrozenError = (RUBY_VERSION >= "1.9.0") ? RuntimeError : TypeError include Enumerable module Util def const_from_name(fqname) fqname.split("::").inject(Kernel) { |klass, name| klass.const_get(name) } end module_function :const_from_name def require_from_name(fqname) require File.join(fqname.split("::").collect { |ele| ele.downcase }) end module_function :require_from_name end def self.load(stream) new.load(stream) end def self.loadproperty(propname) new.loadproperty(propname) end def initialize @store = Hash.new @hook = Hash.new @self_hook = Array.new @locked = false end KEY_REGSRC = '([^=:\\\\]*(?:\\\\.[^=:\\\\]*)*)' DEF_REGSRC = '\\s*' + KEY_REGSRC + '\\s*[=:]\\s*(.*)' COMMENT_REGEXP = Regexp.new('^(?:#.*|)$') CATDEF_REGEXP = Regexp.new("^\\[\\s*#{KEY_REGSRC}\\s*\\]$") LINE_REGEXP = Regexp.new("^#{DEF_REGSRC}$") def load(stream) key_prefix = "" stream.each_with_index do |line, lineno| line.sub!(/\r?\n\z/, '') case line when COMMENT_REGEXP next when CATDEF_REGEXP key_prefix = $1.strip when LINE_REGEXP key, value = $1.strip, $2.strip key = "#{key_prefix}.#{key}" unless key_prefix.empty? key, value = loadstr(key), loadstr(value) self[key] = value else raise TypeError.new( "property format error at line #{lineno + 1}: `#{line}'") end end self end # find property from $:. def loadproperty(propname) return loadpropertyfile(propname) if File.file?(propname) $:.each do |path| if File.file?(file = File.join(path, propname)) return loadpropertyfile(file) end end nil end # name: a Symbol, String or an Array def [](name) referent(name_to_a(name)) end # name: a Symbol, String or an Array # value: an Object def []=(name, value) name_pair = name_to_a(name).freeze hooks = assign(name_pair, value) hooks.each do |hook| hook.call(name_pair, value) end value end # value: an Object # key is generated by property def <<(value) self[generate_new_key] = value end # name: a Symbol, String or an Array; nil means hook to the root # cascade: true/false; for cascading hook of sub key # hook: block which will be called with 2 args, name and value def add_hook(name = nil, cascade = false, &hook) if name == nil or name == true or name == false cascade = name assign_self_hook(cascade, &hook) else assign_hook(name_to_a(name), cascade, &hook) end end def each @store.each do |key, value| yield(key, value) end end def empty? @store.empty? end def keys @store.keys end def values @store.values end def lock(cascade = false) if cascade each_key do |key| key.lock(cascade) end end @locked = true self end def unlock(cascade = false) @locked = false if cascade each_key do |key| key.unlock(cascade) end end self end def locked? @locked end protected def deref_key(key) check_lock(key) ref = @store[key] ||= self.class.new unless propkey?(ref) raise ArgumentError.new("key `#{key}' already defined as a value") end ref end def local_referent(key) check_lock(key) if propkey?(@store[key]) and @store[key].locked? raise FrozenError.new("cannot split any key from locked property") end @store[key] end def local_assign(key, value) check_lock(key) if @locked if propkey?(value) raise FrozenError.new("cannot add any key to locked property") elsif propkey?(@store[key]) raise FrozenError.new("cannot override any key in locked property") end end @store[key] = value end def local_hook(key, direct) hooks = [] (@self_hook + (@hook[key] || NO_HOOK)).each do |hook, cascade| hooks << hook if direct or cascade end hooks end def local_assign_hook(key, cascade, &hook) check_lock(key) @store[key] ||= nil (@hook[key] ||= []) << [hook, cascade] end private NO_HOOK = [].freeze def referent(ary) ary[0..-2].inject(self) { |ref, name| ref.deref_key(to_key(name)) }.local_referent(to_key(ary.last)) end def assign(ary, value) ref = self hook = NO_HOOK ary[0..-2].each do |name| key = to_key(name) hook += ref.local_hook(key, false) ref = ref.deref_key(key) end last_key = to_key(ary.last) ref.local_assign(last_key, value) hook + ref.local_hook(last_key, true) end def assign_hook(ary, cascade, &hook) ary[0..-2].inject(self) { |ref, name| ref.deref_key(to_key(name)) }.local_assign_hook(to_key(ary.last), cascade, &hook) end def assign_self_hook(cascade, &hook) check_lock(nil) @self_hook << [hook, cascade] end def each_key self.each do |key, value| if propkey?(value) yield(value) end end end def check_lock(key) if @locked and (key.nil? or !@store.key?(key)) raise FrozenError.new("cannot add any key to locked property") end end def propkey?(value) value.is_a?(::SOAP::Property) end def name_to_a(name) case name when Symbol [name] when String name.scan(/[^.\\]+(?:\\.[^.\\])*/) # split with unescaped '.' when Array name else raise ArgumentError.new("Unknown name #{name}(#{name.class})") end end def to_key(name) name.to_s.downcase end def generate_new_key if @store.empty? "0" else (key_max + 1).to_s end end def key_max (@store.keys.max { |l, r| l.to_s.to_i <=> r.to_s.to_i }).to_s.to_i end def loadpropertyfile(file) puts "find property at #{file}" if $DEBUG File.open(file) do |f| load(f) end end def loadstr(str) str.gsub(/\\./) { |c| eval("\"#{c}\"") } end end end # for ruby/1.6. unless Enumerable.instance_methods.include?('inject') module Enumerable def inject(init) result = init each do |item| result = yield(result, item) end result end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/soap/soap.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/soap.rb
# soap/soap.rb: SOAP4R - Base definitions. # Copyright (C) 2000-2004 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' require 'xsd/charset' module SOAP VERSION = Version = '1.5.5' PropertyName = 'soap/property' EnvelopeNamespace = 'http://schemas.xmlsoap.org/soap/envelope/' EncodingNamespace = 'http://schemas.xmlsoap.org/soap/encoding/' LiteralNamespace = 'http://xml.apache.org/xml-soap/literalxml' NextActor = 'http://schemas.xmlsoap.org/soap/actor/next' EleEnvelope = 'Envelope' EleHeader = 'Header' EleBody = 'Body' EleFault = 'Fault' EleFaultString = 'faultstring' EleFaultActor = 'faultactor' EleFaultCode = 'faultcode' EleFaultDetail = 'detail' AttrMustUnderstand = 'mustUnderstand' AttrEncodingStyle = 'encodingStyle' AttrActor = 'actor' AttrRoot = 'root' AttrArrayType = 'arrayType' AttrOffset = 'offset' AttrPosition = 'position' ValueArray = 'Array' EleEnvelopeName = XSD::QName.new(EnvelopeNamespace, EleEnvelope).freeze EleHeaderName = XSD::QName.new(EnvelopeNamespace, EleHeader).freeze EleBodyName = XSD::QName.new(EnvelopeNamespace, EleBody).freeze EleFaultName = XSD::QName.new(EnvelopeNamespace, EleFault).freeze EleFaultStringName = XSD::QName.new(nil, EleFaultString).freeze EleFaultActorName = XSD::QName.new(nil, EleFaultActor).freeze EleFaultCodeName = XSD::QName.new(nil, EleFaultCode).freeze EleFaultDetailName = XSD::QName.new(nil, EleFaultDetail).freeze AttrMustUnderstandName = XSD::QName.new(EnvelopeNamespace, AttrMustUnderstand).freeze AttrEncodingStyleName = XSD::QName.new(EnvelopeNamespace, AttrEncodingStyle).freeze AttrRootName = XSD::QName.new(EncodingNamespace, AttrRoot).freeze AttrArrayTypeName = XSD::QName.new(EncodingNamespace, AttrArrayType).freeze AttrOffsetName = XSD::QName.new(EncodingNamespace, AttrOffset).freeze AttrPositionName = XSD::QName.new(EncodingNamespace, AttrPosition).freeze ValueArrayName = XSD::QName.new(EncodingNamespace, ValueArray).freeze Base64Literal = 'base64' SOAPNamespaceTag = 'env' XSDNamespaceTag = 'xsd' XSINamespaceTag = 'xsi' MediaType = 'text/xml' class Error < StandardError; end class StreamError < Error; end class HTTPStreamError < StreamError; end class PostUnavailableError < HTTPStreamError; end class MPostUnavailableError < HTTPStreamError; end class ArrayIndexOutOfBoundsError < Error; end class ArrayStoreError < Error; end class RPCRoutingError < Error; end class EmptyResponseError < Error; end class ResponseFormatError < Error; end class UnhandledMustUnderstandHeaderError < Error; end class FaultError < Error attr_reader :faultcode attr_reader :faultstring attr_reader :faultactor attr_accessor :detail def initialize(fault) @faultcode = fault.faultcode @faultstring = fault.faultstring @faultactor = fault.faultactor @detail = fault.detail super(self.to_s) end def to_s str = nil if @faultstring and @faultstring.respond_to?('data') str = @faultstring.data end str || '(No faultstring)' end end module Env def self.getenv(name) ENV[name.downcase] || ENV[name.upcase] end use_proxy = getenv('soap_use_proxy') == 'on' HTTP_PROXY = use_proxy ? getenv('http_proxy') : nil NO_PROXY = use_proxy ? getenv('no_proxy') : nil end end unless Object.respond_to?(:instance_variable_get) class Object def instance_variable_get(ivarname) instance_eval(ivarname) end def instance_variable_set(ivarname, value) instance_eval("#{ivarname} = value") end end end unless Kernel.respond_to?(:warn) module Kernel def warn(msg) STDERR.puts(msg + "\n") unless $VERBOSE.nil? end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false